@rpamis/comet 0.4.0-beta.16 → 0.4.0-beta.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +85 -56
- 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 +26 -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 +128 -128
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +77 -77
- package/assets/skills/comet/scripts/comet-guard.mjs +144 -144
- package/assets/skills/comet/scripts/comet-handoff.mjs +107 -107
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +128 -128
- package/assets/skills/comet/scripts/comet-hook-router.mjs +143 -141
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +100 -100
- package/assets/skills/comet/scripts/comet-runtime.mjs +194 -193
- package/assets/skills/comet/scripts/comet-state.mjs +118 -118
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +95 -95
- 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 +28 -68
- package/assets/skills/comet-build/agents/openai.yaml +5 -0
- package/assets/skills/comet-classic/SKILL.md +28 -22
- 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 +3 -3
- 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 +4 -2
- package/assets/skills/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
- package/assets/skills/comet-classic/reference/workspace.md +23 -0
- 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 +60 -171
- package/assets/skills/comet-native/agents/openai.yaml +3 -0
- package/assets/skills/comet-native/reference/artifacts.md +24 -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 +214 -158
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +132 -123
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +134 -124
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +165 -158
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +183 -152
- 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 +150 -143
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +128 -121
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +133 -151
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +147 -140
- package/assets/skills/comet-open/SKILL.md +31 -11
- 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 +28 -68
- package/assets/skills-zh/comet-build/agents/openai.yaml +5 -0
- package/assets/skills-zh/comet-classic/SKILL.md +29 -23
- 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 +3 -3
- 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 +4 -2
- package/assets/skills-zh/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
- package/assets/skills-zh/comet-classic/reference/workspace.md +23 -0
- 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 +60 -171
- package/assets/skills-zh/comet-native/agents/openai.yaml +3 -0
- package/assets/skills-zh/comet-native/reference/artifacts.md +24 -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 +31 -11
- 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/cli/index.js +20 -1
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/classic.d.ts.map +1 -1
- package/dist/app/commands/classic.js +2 -0
- package/dist/app/commands/classic.js.map +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +8 -0
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/eval.d.ts +9 -2
- package/dist/app/commands/eval.d.ts.map +1 -1
- package/dist/app/commands/eval.js +293 -48
- package/dist/app/commands/eval.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +11 -2
- 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 +13 -3
- 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-cli.d.ts +1 -1
- package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-cli.js +3 -0
- package/dist/domains/comet-classic/classic-cli.js.map +1 -1
- package/dist/domains/comet-classic/classic-current-change.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-current-change.js +29 -3
- package/dist/domains/comet-classic/classic-current-change.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard.js +2 -2
- package/dist/domains/comet-classic/classic-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.js +14 -1
- package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.js +31 -8
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-workspace-command.d.ts +3 -0
- package/dist/domains/comet-classic/classic-workspace-command.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-workspace-command.js +45 -0
- package/dist/domains/comet-classic/classic-workspace-command.js.map +1 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts +38 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-workspace.js +315 -0
- package/dist/domains/comet-classic/classic-workspace.js.map +1 -0
- package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.js +3 -0
- package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.d.ts +2 -0
- package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.js +32 -3
- package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
- package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
- package/dist/domains/comet-entry/init-workflow.js +13 -5
- package/dist/domains/comet-entry/init-workflow.js.map +1 -1
- package/dist/domains/comet-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/index.d.ts +1 -0
- package/dist/domains/comet-native/index.d.ts.map +1 -1
- package/dist/domains/comet-native/index.js +1 -0
- package/dist/domains/comet-native/index.js.map +1 -1
- package/dist/domains/comet-native/native-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-children.d.ts +49 -0
- package/dist/domains/comet-native/native-children.d.ts.map +1 -0
- package/dist/domains/comet-native/native-children.js +388 -0
- package/dist/domains/comet-native/native-children.js.map +1 -0
- package/dist/domains/comet-native/native-cli-help.d.ts +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 +332 -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 +199 -19
- 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 +193 -62
- 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 +30 -0
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-continuation.js +403 -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 +155 -0
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-runtime.js +1550 -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 +701 -0
- package/dist/domains/comet-native/native-portable-state.js.map +1 -0
- package/dist/domains/comet-native/native-portable-status.d.ts +65 -0
- package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -0
- package/dist/domains/comet-native/native-portable-status.js +133 -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 +166 -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 +37 -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 +324 -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/collector.d.ts +1 -1
- package/dist/domains/dashboard/collector.d.ts.map +1 -1
- package/dist/domains/dashboard/collector.js +102 -87
- package/dist/domains/dashboard/collector.js.map +1 -1
- package/dist/domains/dashboard/native-adapter.d.ts +155 -126
- package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-adapter.js +165 -268
- package/dist/domains/dashboard/native-adapter.js.map +1 -1
- package/dist/domains/dashboard/native-collector.d.ts +5 -4
- package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
- package/dist/domains/dashboard/native-collector.js +506 -439
- package/dist/domains/dashboard/native-collector.js.map +1 -1
- package/dist/domains/dashboard/native-legacy-adapter.d.ts +37 -0
- package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -0
- package/dist/domains/dashboard/native-legacy-adapter.js +127 -0
- package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -0
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +5 -3
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/types.d.ts +5 -0
- package/dist/domains/dashboard/types.d.ts.map +1 -1
- package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-B5cFR6hS.js +1 -0
- package/dist/domains/dashboard/web/assets/arc-CVQDtMsu.js +1 -0
- package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-C0v0kULK.js +36 -0
- package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-DpHLuxu4.js +132 -0
- package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-Ca5zba3N.js → c4Diagram-5PPSVZJV-BHnFxUs1.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-eM0x3m1G.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-Bj6HWRwi.js → chunk-2GRJ4B5K-CGC9gh5n.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-B1kXfg5N.js → chunk-2Q5K7J3B-l4puLU_O.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-ls9jQHZc.js +231 -0
- package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-BAJLB5V6.js → chunk-5VM5RSS4-BVavmTEq.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-Dungt2g9.js +88 -0
- package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-CwghIMO9.js → chunk-GF5L2VYU-BidXO_ZP.js} +5 -5
- package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-JYluRsP-.js → chunk-JWPE2WC7-57L5Up5X.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-CCVPBm0J.js → chunk-KBJHAD2P-C5u5vbwr.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-CvLz21I2.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-DfYm7pN7.js → chunk-XXDRQBXY-D5nJpckG.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-CEFhao2K.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-CEFhao2K.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-BBrkuiAU.js → cose-bilkent-JH36ORCC-Dp0JAGyE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-DlFhgQHt.js → cynefin-VYW2F7L2-EjC54l1g.js} +2 -2
- package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-CpYrW3w3.js +62 -0
- package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-h5K39rCk.js +4 -0
- package/dist/domains/dashboard/web/assets/demo-BfLsKrIL.js +45 -0
- package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-CKQj9O4H.js +30 -0
- package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-BQahyP-C.js → diagram-B4RE2ZJO-DXRIYcnW.js} +3 -3
- package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-wWutQYmv.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-EgXLJQYi.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-CsQRXDQZ.js +41 -0
- package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-gm328Eho.js +1 -0
- package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-BbbMVUx_.js +85 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-1Y7scCns.js +156 -0
- package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-BAoBqczv.js +292 -0
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-DCxvMAUJ.js → gitGraphDiagram-DS77QQ5N-CMUAyEzl.js} +3 -3
- package/dist/domains/dashboard/web/assets/{graph--OzhPTMs.js → graph-DOmOIIwC.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-Blit0P5Z.js → index-CCApJ0Yr.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-DWdm_XBi.js +257 -0
- package/dist/domains/dashboard/web/assets/index-DhhbseFJ.css +1 -0
- package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-9qXEkzDe.js → infoDiagram-6WML65LV-BaCdtYYC.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-Dkf5othW.js → ishikawaDiagram-WSZJBQD7-DQQlNnjU.js} +4 -4
- package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-C2_IkO4s.js → journeyDiagram-NVQOT4AX-DW9wUMqn.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-BxWgu4DL.js → kanban-definition-27J2QSJJ-C_ITaZ0q.js} +7 -7
- package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +1 -0
- package/dist/domains/dashboard/web/assets/{linear-Dkr6p-Ro.js → linear-DXOo6ZRT.js} +1 -1
- package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +1 -0
- package/dist/domains/dashboard/web/assets/mermaid.core-ol-0NI97.js +306 -0
- package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-C9xyxGfa.js → mindmap-definition-FAOFIHXS-CHF_HOLV.js} +1 -1
- package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-wQEvkNF8.js +1 -0
- package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-C3H3kiIP.js +39 -0
- package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +3 -0
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-Cy6iOcxc.js → quadrantDiagram-CIZ2JOQS-S0FdVzJb.js} +4 -4
- package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-DCDXDaVg.js +1 -0
- package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-B_gZONhx.js → requirementDiagram-LRYGKXZP-BW8J4gO_.js} +1 -1
- package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-DQQBmLoy.js +40 -0
- package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-2tDcli0Y.js +162 -0
- package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-4sEZLBKb.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-OgPb8pyR.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-CiDNPr4P.js +1 -0
- package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-DR7lwtxd.js +2 -0
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-DggHFP9q.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-DvONX2YQ.js → timeline-definition-Z64GVDOM-DNIJVlQV.js} +4 -4
- package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-CClhw4QZ.js +34 -0
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-cf39WX2o.js → wardleyDiagram-T6FBY63Y-DzR3aFPS.js} +3 -3
- package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DZhq0ZRj.js +7 -0
- package/dist/domains/dashboard/web/index.html +16 -16
- package/dist/domains/dashboard/workspace.d.ts +24 -0
- package/dist/domains/dashboard/workspace.d.ts.map +1 -0
- package/dist/domains/dashboard/workspace.js +87 -0
- package/dist/domains/dashboard/workspace.js.map +1 -0
- package/dist/domains/eval/index.d.ts +3 -0
- package/dist/domains/eval/index.d.ts.map +1 -1
- package/dist/domains/eval/index.js +3 -0
- package/dist/domains/eval/index.js.map +1 -1
- package/dist/domains/eval/standalone-context.d.ts +19 -0
- package/dist/domains/eval/standalone-context.d.ts.map +1 -0
- package/dist/domains/eval/standalone-context.js +107 -0
- package/dist/domains/eval/standalone-context.js.map +1 -0
- package/dist/domains/eval/standalone-static-collect.d.ts +22 -0
- package/dist/domains/eval/standalone-static-collect.d.ts.map +1 -0
- package/dist/domains/eval/standalone-static-collect.js +779 -0
- package/dist/domains/eval/standalone-static-collect.js.map +1 -0
- package/dist/domains/eval/user-environment.d.ts +6 -0
- package/dist/domains/eval/user-environment.d.ts.map +1 -0
- package/dist/domains/eval/user-environment.js +73 -0
- package/dist/domains/eval/user-environment.js.map +1 -0
- package/dist/domains/integrations/openspec.d.ts +1 -1
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +110 -26
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/integrations/superpowers.d.ts +5 -1
- package/dist/domains/integrations/superpowers.d.ts.map +1 -1
- package/dist/domains/integrations/superpowers.js +21 -2
- package/dist/domains/integrations/superpowers.js.map +1 -1
- package/dist/domains/skill/platform-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 +8 -2
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +115 -34
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/project-instructions.d.ts.map +1 -1
- package/dist/domains/skill/project-instructions.js +5 -3
- package/dist/domains/skill/project-instructions.js.map +1 -1
- package/dist/domains/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/hook-write-policy.d.ts +9 -0
- package/dist/domains/workflow-contract/hook-write-policy.d.ts.map +1 -0
- package/dist/domains/workflow-contract/hook-write-policy.js +52 -0
- package/dist/domains/workflow-contract/hook-write-policy.js.map +1 -0
- package/dist/domains/workflow-contract/index.d.ts +3 -0
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +2 -0
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +3 -1
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +119 -19
- 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/domains/workflow-contract/protected-project-path.d.ts +13 -0
- package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.js +83 -0
- package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
- package/dist/domains/workflow-contract/types.d.ts +4 -0
- package/dist/domains/workflow-contract/types.d.ts.map +1 -1
- package/dist/platform/install/platforms.d.ts +3 -1
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +22 -2
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/paths/git-worktree.d.ts +8 -1
- package/dist/platform/paths/git-worktree.d.ts.map +1 -1
- package/dist/platform/paths/git-worktree.js +41 -7
- 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/.env.example +115 -0
- package/eval/README.md +237 -14
- package/eval/langfuse/.env.example +9 -0
- package/eval/langfuse/tests/conftest.py +146 -0
- package/eval/langfuse/tests/tasks/test_tasks.py +109 -0
- package/eval/langfuse/tests/test_adapter.py +272 -0
- package/eval/langsmith/.env.example +16 -0
- package/eval/langsmith/tests/conftest.py +10 -1
- package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +4 -2
- package/eval/local/tasks/comet-native-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/environment/current-comet-package.json +2 -2
- 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/conftest.py +701 -80
- package/eval/local/tests/scaffold/fixtures/custom-agent/adapter.yaml +19 -0
- package/eval/local/tests/scaffold/test_agents.py +76 -0
- package/eval/local/tests/scaffold/test_aligned_comparison.py +70 -0
- package/eval/local/tests/scaffold/test_auto_tasks.py +350 -0
- package/eval/local/tests/scaffold/test_conftest_helpers.py +267 -18
- package/eval/local/tests/scaffold/test_custom_agents.py +174 -0
- package/eval/local/tests/scaffold/test_eval_context.py +217 -0
- package/eval/local/tests/scaffold/test_execution.py +364 -0
- package/eval/local/tests/scaffold/test_inline_tasks.py +56 -0
- package/eval/local/tests/scaffold/test_langfuse_trajectory.py +263 -0
- package/eval/local/tests/scaffold/test_langsmith_conftest.py +63 -0
- package/eval/local/tests/scaffold/test_logging.py +162 -0
- package/eval/local/tests/scaffold/test_manifest_tasks.py +76 -0
- package/eval/local/tests/scaffold/test_manifests.py +396 -0
- package/eval/local/tests/scaffold/test_native_aligned_eval.py +163 -35
- package/eval/local/tests/scaffold/test_native_wave_evaluations.py +75 -2054
- package/eval/local/tests/scaffold/test_profiles.py +64 -6
- package/eval/local/tests/scaffold/test_task_resolution.py +212 -0
- package/eval/local/tests/scaffold/test_tasks.py +38 -52
- package/eval/local/tests/scaffold/test_utils.py +480 -4
- package/eval/local/tests/tasks/test_tasks.py +219 -17
- package/eval/local/treatments/comet/comet_native_phase1.yaml +7 -4
- package/eval/pyproject.toml +9 -4
- package/eval/scaffold/__init__.py +6 -0
- package/eval/scaffold/docker/agent-overlay.Dockerfile +41 -0
- package/eval/scaffold/python/__init__.py +128 -20
- package/eval/scaffold/python/agents.py +239 -0
- package/eval/scaffold/python/aligned_comparison.py +156 -27
- package/eval/scaffold/python/auto_tasks.py +700 -0
- package/eval/scaffold/python/custom_agents.py +172 -0
- package/eval/scaffold/python/eval_context.py +236 -0
- package/eval/scaffold/python/eval_schema.py +135 -0
- package/eval/scaffold/python/execution.py +544 -0
- package/eval/scaffold/python/generated_task_cache.py +230 -0
- package/eval/scaffold/python/generic_llm_judge.py +41 -14
- package/eval/scaffold/python/inline_tasks.py +118 -0
- package/eval/scaffold/python/judge_config.py +158 -37
- package/eval/scaffold/python/langfuse_adapter.py +1023 -0
- package/eval/scaffold/python/llm_judge.py +68 -11
- package/eval/scaffold/python/logging.py +157 -17
- package/eval/scaffold/python/manifest_tasks.py +69 -0
- package/eval/scaffold/python/manifests.py +443 -22
- package/eval/scaffold/python/native_eval.py +10 -5
- package/eval/scaffold/python/paths.py +11 -1
- package/eval/scaffold/python/task_resolution.py +176 -0
- package/eval/scaffold/python/tasks.py +17 -4
- package/eval/scaffold/python/utils.py +167 -11
- package/eval/scaffold/python/validation/core.py +48 -2
- package/eval/scaffold/python/validation/generic_rubric.py +9 -0
- package/eval/scaffold/python/validation/native_v4.py +249 -0
- package/eval/scaffold/python/validation/native_wave.py +4 -5
- package/eval/scaffold/python/validation/native_workflow.py +199 -98
- package/eval/scaffold/python/validation/rubric.py +130 -2
- package/eval/scaffold/shell/agent-runtime-config.sh +88 -0
- package/eval/scaffold/shell/docker.sh +534 -33
- package/eval/scaffold/shell/run-agent-runtime.sh +49 -0
- package/eval/scaffold/shell/run-claude-loop.sh +153 -14
- package/eval/schemas/comet.eval/v1alpha1.schema.json +244 -0
- package/package.json +9 -3
- 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/arc-ClrSujVb.js +0 -1
- package/dist/domains/dashboard/web/assets/architectureDiagram-3BPJPVTR-B4A_t84A.js +0 -36
- package/dist/domains/dashboard/web/assets/blockDiagram-GPEHLZMM-D72u2953.js +0 -132
- package/dist/domains/dashboard/web/assets/channel-B_u-_i2t.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-AQP2D5EJ-BA_zgMXZ.js +0 -231
- 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/dagre-BM42HDAG-B0Bk5oiP.js +0 -4
- package/dist/domains/dashboard/web/assets/demo-DZYPLZpF.js +0 -25
- package/dist/domains/dashboard/web/assets/diagram-2AECGRRQ-tvTUiBA2.js +0 -43
- package/dist/domains/dashboard/web/assets/diagram-5GNKFQAL-BZfcK29q.js +0 -10
- package/dist/domains/dashboard/web/assets/diagram-LMA3HP47-D5bJnW2C.js +0 -24
- package/dist/domains/dashboard/web/assets/diagram-OG6HWLK6-DTwWdzWJ.js +0 -24
- package/dist/domains/dashboard/web/assets/erDiagram-TEJ5UH35-BbvrdCp9.js +0 -85
- package/dist/domains/dashboard/web/assets/flowDiagram-I6XJVG4X-DgbR7Tcc.js +0 -162
- package/dist/domains/dashboard/web/assets/ganttDiagram-6RSMTGT7-wWMOA7F4.js +0 -292
- 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/layout-SsrduOYp.js +0 -1
- package/dist/domains/dashboard/web/assets/mermaid.core-DZUcsoG4.js +0 -301
- package/dist/domains/dashboard/web/assets/pieDiagram-4H26LBE5-Dn67tdOF.js +0 -30
- package/dist/domains/dashboard/web/assets/purify.es-VaSPOPhr.js +0 -3
- package/dist/domains/dashboard/web/assets/sankeyDiagram-5OEKKPKP-C3u-4dOk.js +0 -40
- package/dist/domains/dashboard/web/assets/sequenceDiagram-3UESZ5HK-Xd3ByTVF.js +0 -162
- package/dist/domains/dashboard/web/assets/stateDiagram-AJRCARHV-CJGHL7Up.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-rKvBgr6I.js +0 -1
- package/dist/domains/dashboard/web/assets/vennDiagram-CIIHVFJN-B-L4qWy4.js +0 -34
- package/dist/domains/dashboard/web/assets/xychartDiagram-2RQKCTM6-Dk1vcm3u.js +0 -7
- /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,181 +1,163 @@
|
|
|
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 Ld=Object.create;var us=Object.defineProperty;var Md=Object.getOwnPropertyDescriptor;var Fd=Object.getOwnPropertyNames;var Vd=Object.getPrototypeOf,qd=Object.prototype.hasOwnProperty;var $i=(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 g=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var Wd=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fd(e))!qd.call(t,n)&&n!==i&&us(t,n,{get:()=>e[n],enumerable:!(r=Md(e,n))||r.enumerable});return t};var jt=(t,e,i)=>(i=t!=null?Ld(Vd(t)):{},Wd(e||!t||!t.__esModule?us(i,"default",{value:t,enumerable:!0}):i,t));var P=g(H=>{"use strict";var jn=Symbol.for("yaml.alias"),ms=Symbol.for("yaml.document"),Bi=Symbol.for("yaml.map"),vs=Symbol.for("yaml.pair"),$n=Symbol.for("yaml.scalar"),Li=Symbol.for("yaml.seq"),Se=Symbol.for("yaml.node.type"),cf=t=>!!t&&typeof t=="object"&&t[Se]===jn,lf=t=>!!t&&typeof t=="object"&&t[Se]===ms,uf=t=>!!t&&typeof t=="object"&&t[Se]===Bi,df=t=>!!t&&typeof t=="object"&&t[Se]===vs,gs=t=>!!t&&typeof t=="object"&&t[Se]===$n,ff=t=>!!t&&typeof t=="object"&&t[Se]===Li;function ws(t){if(t&&typeof t=="object")switch(t[Se]){case Bi:case Li:return!0}return!1}function hf(t){if(t&&typeof t=="object")switch(t[Se]){case jn:case Bi:case $n:case Li:return!0}return!1}var pf=t=>(gs(t)||ws(t))&&!!t.anchor;H.ALIAS=jn;H.DOC=ms;H.MAP=Bi;H.NODE_TYPE=Se;H.PAIR=vs;H.SCALAR=$n;H.SEQ=Li;H.hasAnchor=pf;H.isAlias=cf;H.isCollection=ws;H.isDocument=lf;H.isMap=uf;H.isNode=hf;H.isPair=df;H.isScalar=gs;H.isSeq=ff});var Ht=g(On=>{"use strict";var O=P(),q=Symbol("break visit"),ys=Symbol("skip children"),fe=Symbol("remove node");function Mi(t,e){let i=Ns(e);O.isDocument(t)?st(null,t.contents,i,Object.freeze([t]))===fe&&(t.contents=null):st(null,t,i,Object.freeze([]))}Mi.BREAK=q;Mi.SKIP=ys;Mi.REMOVE=fe;function st(t,e,i,r){let n=bs(t,e,i,r);if(O.isNode(n)||O.isPair(n))return ks(t,r,n),st(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=st(a,e.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===q)return q;o===fe&&(e.items.splice(a,1),a-=1)}}}else if(O.isPair(e)){r=Object.freeze(r.concat(e));let a=st("key",e.key,i,r);if(a===q)return q;a===fe&&(e.key=null);let o=st("value",e.value,i,r);if(o===q)return q;o===fe&&(e.value=null)}}return n}async function Fi(t,e){let i=Ns(e);O.isDocument(t)?await ct(null,t.contents,i,Object.freeze([t]))===fe&&(t.contents=null):await ct(null,t,i,Object.freeze([]))}Fi.BREAK=q;Fi.SKIP=ys;Fi.REMOVE=fe;async function ct(t,e,i,r){let n=await bs(t,e,i,r);if(O.isNode(n)||O.isPair(n))return ks(t,r,n),ct(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 ct(a,e.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===q)return q;o===fe&&(e.items.splice(a,1),a-=1)}}}else if(O.isPair(e)){r=Object.freeze(r.concat(e));let a=await ct("key",e.key,i,r);if(a===q)return q;a===fe&&(e.key=null);let o=await ct("value",e.value,i,r);if(o===q)return q;o===fe&&(e.value=null)}}return n}function Ns(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 bs(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 ks(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`)}}On.visit=Mi;On.visitAsync=Fi});var Hn=g(Es=>{"use strict";var Ss=P(),mf=Ht(),vf={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},gf=t=>t.replace(/[!,[\]{}]/g,e=>vf[e]),Dt=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+gf(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&&Ss.isNode(e.contents)){let a={};mf.visit(e.contents,(o,s)=>{Ss.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
|
+
`)}};Dt.defaultYaml={explicit:!1,version:"1.2"};Dt.defaultTags={"!!":"tag:yaml.org,2002:"};Es.Directives=Dt});var Vi=g(Bt=>{"use strict";var Ps=P(),wf=Ht();function yf(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 xs(t){let e=new Set;return wf.visit(t,{Value(i,r){r.anchor&&e.add(r.anchor)}}),e}function Cs(t,e){for(let i=1;;++i){let r=`${t}${i}`;if(!e.has(r))return r}}function Nf(t,e){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=xs(t));let o=Cs(e,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Ps.isScalar(o.node)||Ps.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}}Bt.anchorIsValid=yf;Bt.anchorNames=xs;Bt.createNodeAnchors=Nf;Bt.findNewAnchor=Cs});var Dn=g(Rs=>{"use strict";function Lt(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=Lt(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=Lt(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=Lt(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=Lt(t,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return t.call(e,i,r)}Rs.applyReviver=Lt});var Ie=g(_s=>{"use strict";var bf=P();function As(t,e,i){if(Array.isArray(t))return t.map((r,n)=>As(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=As});var qi=g(Is=>{"use strict";var kf=Dn(),Ts=P(),Sf=Ie(),Bn=class{constructor(e){Object.defineProperty(this,Ts.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(!Ts.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=Sf.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?kf.applyReviver(a,{"":s},"",s):s}};Is.NodeBase=Bn});var Mt=g(js=>{"use strict";var Ef=Vi(),Pf=Ht(),lt=P(),xf=qi(),Cf=Ie(),Ln=class extends xf.NodeBase{constructor(e){super(lt.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=[],Pf.visit(e,{Node:(a,o)=>{(lt.isAlias(o)||lt.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||(Cf.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=Wi(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(Ef.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 Wi(t,e,i){if(lt.isAlias(e)){let r=e.resolve(t),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(lt.isCollection(e)){let r=0;for(let n of e.items){let a=Wi(t,n,i);a>r&&(r=a)}return r}else if(lt.isPair(e)){let r=Wi(t,e.key,i),n=Wi(t,e.value,i);return Math.max(r,n)}return 1}js.Alias=Ln});var I=g(Mn=>{"use strict";var Rf=P(),Af=qi(),_f=Ie(),Tf=t=>!t||typeof t!="function"&&typeof t!="object",je=class extends Af.NodeBase{constructor(e){super(Rf.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:_f.toJS(this.value,e,i)}toString(){return String(this.value)}};je.BLOCK_FOLDED="BLOCK_FOLDED";je.BLOCK_LITERAL="BLOCK_LITERAL";je.PLAIN="PLAIN";je.QUOTE_DOUBLE="QUOTE_DOUBLE";je.QUOTE_SINGLE="QUOTE_SINGLE";Mn.Scalar=je;Mn.isScalarValue=Tf});var Ft=g(Os=>{"use strict";var If=Mt(),Je=P(),$s=I(),jf="tag:yaml.org,2002:";function $f(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 Of(t,e,i){if(Je.isDocument(t)&&(t=t.contents),Je.isNode(t))return t;if(Je.isPair(t)){let d=i.schema[Je.MAP].createNode?.(i.schema,null,i);return d.items.push(t),d}(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 If.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=jf+e.slice(2));let l=$f(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new $s.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[Je.MAP]:Symbol.iterator in Object(t)?o[Je.SEQ]:o[Je.MAP]}a&&(a(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new $s.Scalar(t);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}Os.createNode=Of});var Ji=g(zi=>{"use strict";var Hf=Ft(),he=P(),Df=qi();function Fn(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 Hf.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 Hs=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Vn=class extends Df.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=>he.isNode(r)||he.isPair(r)?r.clone(e):r),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(Hs(e))this.add(i);else{let[r,...n]=e,a=this.get(r,!0);if(he.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Fn(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(he.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&&he.isScalar(a)?a.value:a:he.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!he.isPair(i))return!1;let r=i.value;return r==null||e&&he.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 he.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(he.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Fn(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};zi.Collection=Vn;zi.collectionFromPath=Fn;zi.isEmptyPath=Hs});var Vt=g(Gi=>{"use strict";var Bf=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function qn(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Lf=(t,e,i)=>t.endsWith(`
|
|
6
|
+
`)?qn(i,e):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
10
|
-
`&&p!==" "){let
|
|
11
|
-
`&&
|
|
12
|
-
${
|
|
13
|
-
${
|
|
14
|
-
`);
|
|
15
|
-
`){if(a-o>
|
|
8
|
+
`+qn(i,e):(t.endsWith(" ")?"":" ")+i;Gi.indentComment=qn;Gi.lineComment=Lf;Gi.stringifyComment=Bf});var Bs=g(qt=>{"use strict";var Mf="flow",Wn="block",Ui="quoted";function Ff(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=[],f={},d=n-e.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let u,p,v=!1,h=-1,m=-1,w=-1;i===Wn&&(h=Ds(t,h,e.length),h!==-1&&(d=h+c));for(let b;b=t[h+=1];){if(i===Ui&&b==="\\"){switch(m=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(b===`
|
|
9
|
+
`)i===Wn&&(h=Ds(t,h,e.length)),d=h+e.length+c,u=void 0;else{if(b===" "&&p&&p!==" "&&p!==`
|
|
10
|
+
`&&p!==" "){let k=t[h+1];k&&k!==" "&&k!==`
|
|
11
|
+
`&&k!==" "&&(u=h)}if(h>=d)if(u)l.push(u),d=u+c,u=void 0;else if(i===Ui){for(;p===" "||p===" ";)p=b,b=t[h+=1],v=!0;let k=h>w+1?h-2:m-1;if(f[k])return t;l.push(k),f[k]=!0,d=k+c,u=void 0}else v=!0}p=b}if(v&&s&&s(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let b=0;b<l.length;++b){let k=l[b],S=l[b+1]||t.length;k===0?y=`
|
|
12
|
+
${e}${t.slice(0,S)}`:(i===Ui&&f[k]&&(y+=`${t[k]}\\`),y+=`
|
|
13
|
+
${e}${t.slice(k+1,S)}`)}return y}function Ds(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}qt.FOLD_BLOCK=Wn;qt.FOLD_FLOW=Mf;qt.FOLD_QUOTED=Ui;qt.foldFlowLines=Ff});var zt=g(Ls=>{"use strict";var ne=I(),$e=Bs(),Yi=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Xi=t=>/^(%|---|\.\.\.)/m.test(t);function Vf(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 Wt(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(Xi(t)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let f=i.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(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:$e.foldFlowLines(o,a,$e.FOLD_QUOTED,Yi(e,!1))}function zn(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return Wt(t,e);let i=e.indent||(Xi(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return e.implicitKey?r:$e.foldFlowLines(r,i,$e.FOLD_FLOW,Yi(e,!1))}function ut(t,e){let{singleQuote:i}=e.options,r;if(i===!1)r=Wt;else{let n=t.includes('"'),a=t.includes("'");n&&!a?r=zn:a&&!n?r=Wt:r=i?zn:Wt}return r(t,e)}var Jn;try{Jn=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Jn=/\n+(?!\n|$)/g}function Ki({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 ut(i,r);let l=r.indent||(r.forceBlockIndent||Xi(i)?" ":""),f=o==="literal"?!0:o==="folded"||e===ne.Scalar.BLOCK_FOLDED?!1:e===ne.Scalar.BLOCK_LITERAL?!0:!Vf(i,c,l.length);if(!i)return f?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let d,
|
|
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}${
|
|
33
|
-
`)||
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let
|
|
37
|
-
${
|
|
38
|
-
${s}:`):(
|
|
39
|
-
`:"",
|
|
40
|
-
${
|
|
41
|
-
`&&
|
|
25
|
+
`;let d,u;for(u=i.length;u>0;--u){let S=i[u-1];if(S!==`
|
|
26
|
+
`&&S!==" "&&S!==" ")break}let p=i.substring(u),v=p.indexOf(`
|
|
27
|
+
`);v===-1?d="-":i===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(Jn,`$&${l}`));let h=!1,m,w=-1;for(m=0;m<i.length;++m){let S=i[m];if(S===" ")h=!0;else if(S===`
|
|
29
|
+
`)w=m;else break}let y=i.substring(0,w<m?w+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let k=(h?l?"2":"1":"")+d;if(t&&(k+=" "+s(t.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let S=i.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,R=Yi(r,!0);o!=="folded"&&e!==ne.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{E=!0});let N=$e.foldFlowLines(`${y}${S}${p}`,l,$e.FOLD_BLOCK,R);if(!E)return`>${k}
|
|
31
|
+
${l}${N}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
|
|
32
|
+
${l}${y}${i}${p}`}function qf(t,e,i,r){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=e;if(s&&a.includes(`
|
|
33
|
+
`)||f&&/[[\]{},]/.test(a))return ut(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
|
|
34
|
+
`)?ut(a,e):Ki(t,e,i,r);if(!s&&!f&&n!==ne.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return Ki(t,e,i,r);if(Xi(a)){if(c==="")return e.forceBlockIndent=!0,Ki(t,e,i,r);if(s&&c===l)return ut(a,e)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=e.doc.schema;if(v.some(u)||p?.some(u))return ut(a,e)}return s?d:$e.foldFlowLines(d,c,$e.FOLD_FLOW,Yi(e,!1))}function Wf(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!==ne.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ne.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case ne.Scalar.BLOCK_FOLDED:case ne.Scalar.BLOCK_LITERAL:return n||a?ut(o.value,e):Ki(o,e,i,r);case ne.Scalar.QUOTE_DOUBLE:return Wt(o.value,e);case ne.Scalar.QUOTE_SINGLE:return zn(o.value,e);case ne.Scalar.PLAIN:return qf(o,e,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=e.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Ls.stringifyString=Wf});var Jt=g(Gn=>{"use strict";var zf=Vi(),Oe=P(),Jf=Vt(),Gf=zt();function Uf(t,e){let i=Object.assign({blockQuote:!0,commentString:Jf.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 Kf(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(Oe.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 Yf(t,e,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Oe.isScalar(t)||Oe.isCollection(t))&&t.anchor;a&&zf.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 Xf(t,e,i,r){if(Oe.isPair(t))return t.toString(e,i,r);if(Oe.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=Oe.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=Kf(e.doc.schema.tags,a));let o=Yf(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):Oe.isScalar(a)?Gf.stringifyString(a,e,i,r):a.toString(e,i,r);return o?Oe.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${e.indent}${s}`:s}Gn.createStringifyContext=Uf;Gn.stringify=Xf});var qs=g(Vs=>{"use strict";var Ee=P(),Ms=I(),Fs=Jt(),Gt=Vt();function Qf({key:t,value:e},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=i,u=Ee.isNode(t)&&t.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(Ee.isCollection(t)||!Ee.isNode(t)&&typeof t=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!t||u&&e==null&&!i.inFlow||Ee.isCollection(t)||(Ee.isScalar(t)?t.type===Ms.Scalar.BLOCK_FOLDED||t.type===Ms.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Fs.stringify(t,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)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 v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||e==null&&p)return m=`? ${m}`,u&&!v?m+=Gt.lineComment(m,i.indent,l(u)):h&&n&&n(),m;v&&(u=null),p?(u&&(m+=Gt.lineComment(m,i.indent,l(u))),m=`? ${m}
|
|
38
|
+
${s}:`):(m=`${m}:`,u&&(m+=Gt.lineComment(m,i.indent,l(u))));let w,y,b;Ee.isNode(e)?(w=!!e.spaceBefore,y=e.commentBefore,b=e.comment):(w=!1,y=null,b=null,e&&typeof e=="object"&&(e=o.createNode(e))),i.implicitKey=!1,!p&&!u&&Ee.isScalar(e)&&(i.indentAtStart=m.length+1),h=!1,!f&&c.length>=2&&!i.inFlow&&!p&&Ee.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let k=!1,S=Fs.stringify(e,i,()=>k=!0,()=>h=!0),E=" ";if(u||w||y){if(E=w?`
|
|
39
|
+
`:"",y){let R=l(y);E+=`
|
|
40
|
+
${Gt.indentComment(R,i.indent)}`}S===""&&!i.inFlow?E===`
|
|
41
|
+
`&&b&&(E=`
|
|
42
42
|
|
|
43
|
-
`):
|
|
44
|
-
${i.indent}`}else if(!p&&
|
|
45
|
-
`),
|
|
46
|
-
${i.indent}`)}}else(
|
|
47
|
-
`)&&(
|
|
43
|
+
`):E+=`
|
|
44
|
+
${i.indent}`}else if(!p&&Ee.isCollection(e)){let R=S[0],N=S.indexOf(`
|
|
45
|
+
`),j=N!==-1,_e=i.inFlow??e.flow??e.items.length===0;if(j||!_e){let ot=!1;if(j&&(R==="&"||R==="!")){let $=S.indexOf(" ");R==="&"&&$!==-1&&$<N&&S[$+1]==="!"&&($=S.indexOf(" ",$+1)),($===-1||N<$)&&(ot=!0)}ot||(E=`
|
|
46
|
+
${i.indent}`)}}else(S===""||S[0]===`
|
|
47
|
+
`)&&(E="");return m+=E+S,i.inFlow?k&&r&&r():b&&!k?m+=Gt.lineComment(m,i.indent,l(b)):h&&n&&n(),m}Vs.stringifyPair=Qf});var Kn=g(Un=>{"use strict";var Ws=$i("process");function Zf(t,...e){t==="debug"&&console.log(...e)}function eh(t,e){(t==="debug"||t==="warn")&&(typeof Ws.emitWarning=="function"?Ws.emitWarning(e):console.warn(e))}Un.debug=Zf;Un.warn=eh});var ir=g(tr=>{"use strict";var er=P(),zs=I(),Qi="<<",Zi={identify:t=>t===Qi||typeof t=="symbol"&&t.description===Qi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new zs.Scalar(Symbol(Qi)),{addToJSMap:Js}),stringify:()=>Qi},th=(t,e)=>(Zi.identify(e)||er.isScalar(e)&&(!e.type||e.type===zs.Scalar.PLAIN)&&Zi.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===Zi.tag&&i.default);function Js(t,e,i){let r=Gs(t,i);if(er.isSeq(r))for(let n of r.items)Yn(t,e,n);else if(Array.isArray(r))for(let n of r)Yn(t,e,n);else Yn(t,e,r)}function Yn(t,e,i){let r=Gs(t,i);if(!er.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 Gs(t,e){return t&&er.isAlias(e)?e.resolve(t.doc,t):e}tr.addMergeToJSMap=Js;tr.isMergeKey=th;tr.merge=Zi});var Qn=g(Ys=>{"use strict";var ih=Kn(),Us=ir(),rh=Jt(),Ks=P(),Xn=Ie();function nh(t,e,{key:i,value:r}){if(Ks.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,r);else if(Us.isMergeKey(t,i))Us.addMergeToJSMap(t,e,r);else{let n=Xn.toJS(i,"",t);if(e instanceof Map)e.set(n,Xn.toJS(r,n,t));else if(e instanceof Set)e.add(n);else{let a=ah(i,n,t),o=Xn.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 ah(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Ks.isNode(t)&&i?.doc){let r=rh.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)+'..."'),ih.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)}Ys.addPairToJSMap=nh});var He=g(Zn=>{"use strict";var Xs=Ft(),oh=qs(),sh=Qn(),rr=P();function ch(t,e,i){let r=Xs.createNode(t,void 0,i),n=Xs.createNode(e,void 0,i);return new nr(r,n)}var nr=class t{constructor(e,i=null){Object.defineProperty(this,rr.NODE_TYPE,{value:rr.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:r}=this;return rr.isNode(i)&&(i=i.clone(e)),rr.isNode(r)&&(r=r.clone(e)),new t(i,r)}toJSON(e,i){let r=i?.mapAsMap?new Map:{};return sh.addPairToJSMap(i,r,this)}toString(e,i,r){return e?.doc?oh.stringifyPair(this,e,i,r):JSON.stringify(this)}};Zn.Pair=nr;Zn.createPair=ch});var ea=g(Zs=>{"use strict";var Ge=P(),Qs=Jt(),ar=Vt();function lh(t,e,i){return(e.inFlow??t.flow?dh:uh)(t,e,i)}function uh({comment:t,items:e},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,f=Object.assign({},i,{indent:a,type:null}),d=!1,u=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(Ge.isNode(h))!d&&h.spaceBefore&&u.push(""),or(i,u,h.commentBefore,d),h.comment&&(m=h.comment);else if(Ge.isPair(h)){let y=Ge.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&u.push(""),or(i,u,y.commentBefore,d))}d=!1;let w=Qs.stringify(h,f,()=>m=null,()=>d=!0);m&&(w+=ar.lineComment(w,a,l(m))),d&&m&&(d=!1),u.push(r+w)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;v<u.length;++v){let h=u[v];p+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
|
-
`}}return
|
|
50
|
-
`+
|
|
51
|
-
`)),
|
|
52
|
-
${a}${
|
|
53
|
-
`;return`${
|
|
54
|
-
${
|
|
55
|
-
`:" ")}return
|
|
56
|
-
${
|
|
57
|
-
${a.comment}`:n.comment}n=r}e.items[i]=da.isPair(n)?n:new As.Pair(n)}}else t("Expected a sequence for this tag");return e}function Vd(e,t,i){let{replacer:n}=i,r=new Sy.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(As.createPair(s,c,i))}return r}var Ey={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qd,createNode:Vd};fa.createPairs=Vd;fa.pairs=Ey;fa.resolvePairs=qd});var Is=R(Ts=>{"use strict";var Wd=M(),xs=bt(),Nn=Pt(),Cy=At(),zd=ha(),Yt=class e extends Cy.YAMLSeq{constructor(){super(),this.add=Nn.YAMLMap.prototype.add.bind(this),this.delete=Nn.YAMLMap.prototype.delete.bind(this),this.get=Nn.YAMLMap.prototype.get.bind(this),this.has=Nn.YAMLMap.prototype.has.bind(this),this.set=Nn.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(Wd.isPair(r)?(a=xs.toJS(r.key,"",i),o=xs.toJS(r.value,a,i)):a=xs.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=zd.createPairs(t,i,n),a=new this;return a.items=r.items,a}};Yt.tag="tag:yaml.org,2002:omap";var Ry={collection:"seq",identify:e=>e instanceof Map,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=zd.resolvePairs(e,t),n=[];for(let{key:r}of i.items)Wd.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Yt,i)},createNode:(e,t,i)=>Yt.from(e,t,i)};Ts.YAMLOMap=Yt;Ts.omap=Ry});var Yd=R(_s=>{"use strict";var Jd=te();function Gd({value:e,source:t},i){return t&&(e?Ud:Kd).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Ud={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 Jd.Scalar(!0),stringify:Gd},Kd={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 Jd.Scalar(!1),stringify:Gd};_s.falseTag=Kd;_s.trueTag=Ud});var Xd=R(pa=>{"use strict";var Py=te(),js=Pi(),Ay={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:js.stringifyNumber},xy={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():js.stringifyNumber(e)}},Ty={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 Py.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:js.stringifyNumber};pa.float=Ty;pa.floatExp=xy;pa.floatNaN=Ay});var Zd=R(kn=>{"use strict";var Qd=Pi(),bn=e=>typeof e=="bigint"||Number.isInteger(e);function ma(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 Os(e,t,i){let{value:n}=e;if(bn(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return Qd.stringifyNumber(e)}var Iy={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>ma(e,2,2,i),stringify:e=>Os(e,2,"0b")},_y={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>ma(e,1,8,i),stringify:e=>Os(e,8,"0")},jy={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>ma(e,0,10,i),stringify:Qd.stringifyNumber},Oy={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>ma(e,2,16,i),stringify:e=>Os(e,16,"0x")};kn.int=jy;kn.intBin=Iy;kn.intHex=Oy;kn.intOct=_y});var Hs=R($s=>{"use strict";var wa=M(),va=Ct(),ga=Pt(),Xt=class e extends ga.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;wa.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new va.Pair(t.key,null):i=new va.Pair(t,null),ga.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=ga.findPair(this.items,t);return!i&&wa.isPair(n)?wa.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=ga.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new va.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(va.createPair(o,null,n));return a}};Xt.tag="tag:yaml.org,2002:set";var $y={collection:"map",identify:e=>e instanceof Set,nodeClass:Xt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Xt.from(e,t,i),resolve(e,t){if(wa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Xt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};$s.YAMLSet=Xt;$s.set=$y});var Ds=R(ya=>{"use strict";var Hy=Pi();function Fs(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 ef(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Hy.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 Fy={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})=>Fs(e,i),stringify:ef},Dy={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=>Fs(e,!1),stringify:ef},tf={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(tf.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=Fs(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$/,"")??""};ya.floatTime=Dy;ya.intTime=Fy;ya.timestamp=tf});var af=R(rf=>{"use strict";var Ly=Ci(),My=oa(),By=Ri(),qy=wn(),Vy=Ps(),nf=Yd(),Ls=Xd(),Na=Zd(),Wy=Qr(),zy=Is(),Jy=ha(),Gy=Hs(),Ms=Ds(),Uy=[Ly.map,By.seq,qy.string,My.nullTag,nf.trueTag,nf.falseTag,Na.intBin,Na.intOct,Na.int,Na.intHex,Ls.floatNaN,Ls.floatExp,Ls.float,Vy.binary,Wy.merge,zy.omap,Jy.pairs,Gy.set,Ms.intTime,Ms.floatTime,Ms.timestamp];rf.schema=Uy});var mf=R(Vs=>{"use strict";var lf=Ci(),Ky=oa(),uf=Ri(),Yy=wn(),Xy=ys(),Bs=bs(),qs=Ss(),Qy=Fd(),Zy=Md(),df=Ps(),Sn=Qr(),ff=Is(),hf=ha(),of=af(),pf=Hs(),ba=Ds(),sf=new Map([["core",Qy.schema],["failsafe",[lf.map,uf.seq,Yy.string]],["json",Zy.schema],["yaml11",of.schema],["yaml-1.1",of.schema]]),cf={binary:df.binary,bool:Xy.boolTag,float:Bs.float,floatExp:Bs.floatExp,floatNaN:Bs.floatNaN,floatTime:ba.floatTime,int:qs.int,intHex:qs.intHex,intOct:qs.intOct,intTime:ba.intTime,map:lf.map,merge:Sn.merge,null:Ky.nullTag,omap:ff.omap,pairs:hf.pairs,seq:uf.seq,set:pf.set,timestamp:ba.timestamp},eN={"tag:yaml.org,2002:binary":df.binary,"tag:yaml.org,2002:merge":Sn.merge,"tag:yaml.org,2002:omap":ff.omap,"tag:yaml.org,2002:pairs":hf.pairs,"tag:yaml.org,2002:set":pf.set,"tag:yaml.org,2002:timestamp":ba.timestamp};function tN(e,t,i){let n=sf.get(t);if(n&&!e)return i&&!n.includes(Sn.merge)?n.concat(Sn.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(sf.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(Sn.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?cf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(cf).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},[])}Vs.coreKnownTags=eN;Vs.getTags=tN});var Js=R(vf=>{"use strict";var Ws=M(),iN=Ci(),nN=Ri(),rN=wn(),ka=mf(),aN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,zs=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ka.getTags(t,"compat"):t?ka.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?ka.coreKnownTags:{},this.tags=ka.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Ws.MAP,{value:iN.map}),Object.defineProperty(this,Ws.SCALAR,{value:rN.string}),Object.defineProperty(this,Ws.SEQ,{value:nN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?aN:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};vf.Schema=zs});var wf=R(gf=>{"use strict";var oN=M(),Gs=mn(),En=dn();function sN(e,t){let i=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&i.push("---");let r=Gs.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(En.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(oN.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(En.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Gs.stringify(e.contents,r,()=>s=null,c);s&&(l+=En.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Gs.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
49
|
+
`}}return t?(p+=`
|
|
50
|
+
`+ar.indentComment(l(t),c),s&&s()):d&&o&&o(),p}function dh({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,f=0,d=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(Ge.isNode(h))h.spaceBefore&&d.push(""),or(e,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(Ge.isPair(h)){let y=Ge.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),or(e,d,y.commentBefore,!1),y.comment&&(l=!0));let b=Ge.isNode(h.value)?h.value:null;b?(b.comment&&(m=b.comment),b.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let w=Qs.stringify(h,c,()=>m=null);l||(l=d.length>f||w.includes(`
|
|
51
|
+
`)),v<t.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=d.reduce((y,b)=>y+b.length+2,2)+(w.length+2)>e.options.lineWidth)),l&&(w+=",")),m&&(w+=ar.lineComment(w,r,s(m))),d.push(w),f=d.length}let{start:u,end:p}=i;if(d.length===0)return u+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=e.options.lineWidth>0&&v>e.options.lineWidth}if(l){let v=u;for(let h of d)v+=h?`
|
|
52
|
+
${a}${n}${h}`:`
|
|
53
|
+
`;return`${v}
|
|
54
|
+
${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function or({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=ar.indentComment(e(r),t);i.push(a.trimStart())}}Zs.stringifyCollection=lh});var Be=g(ia=>{"use strict";var fh=ea(),hh=Qn(),ph=Ji(),De=P(),sr=He(),mh=I();function Ut(t,e){let i=De.isScalar(e)?e.value:e;for(let r of t)if(De.isPair(r)&&(r.key===e||r.key===i||De.isScalar(r.key)&&r.key.value===i))return r}var ta=class extends ph.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(De.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(sr.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;De.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new sr.Pair(e,e?.value):r=new sr.Pair(e.key,e.value);let n=Ut(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);De.isScalar(n.value)&&mh.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=Ut(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let n=Ut(this.items,e)?.value;return(!i&&De.isScalar(n)?n.value:n)??void 0}has(e){return!!Ut(this.items,e)}set(e,i){this.add(new sr.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)hh.addPairToJSMap(i,n,a);return n}toString(e,i,r){if(!e)return JSON.stringify(this);for(let n of this.items)if(!De.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})),fh.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:i})}};ia.YAMLMap=ta;ia.findPair=Ut});var dt=g(tc=>{"use strict";var vh=P(),ec=Be(),gh={collection:"map",default:!0,nodeClass:ec.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return vh.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>ec.YAMLMap.from(t,e,i)};tc.map=gh});var Le=g(ic=>{"use strict";var wh=Ft(),yh=ea(),Nh=Ji(),lr=P(),bh=I(),kh=Ie(),ra=class extends Nh.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(lr.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=cr(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let r=cr(e);if(typeof r!="number")return;let n=this.items[r];return!i&&lr.isScalar(n)?n.value:n}has(e){let i=cr(e);return typeof i=="number"&&i<this.items.length}set(e,i){let r=cr(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[r];lr.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(kh.toJS(a,String(n++),i));return r}toString(e,i,r){return e?yh.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(wh.createNode(s,void 0,r))}}return a}};function cr(t){let e=lr.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}ic.YAMLSeq=ra});var ft=g(nc=>{"use strict";var Sh=P(),rc=Le(),Eh={collection:"seq",default:!0,nodeClass:rc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Sh.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>rc.YAMLSeq.from(t,e,i)};nc.seq=Eh});var Kt=g(ac=>{"use strict";var Ph=zt(),xh={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),Ph.stringifyString(t,e,i,r)}};ac.string=xh});var ur=g(cc=>{"use strict";var oc=I(),sc={identify:t=>t==null,createNode:()=>new oc.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new oc.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&sc.test.test(t)?t:e.options.nullStr};cc.nullTag=sc});var na=g(uc=>{"use strict";var Ch=I(),lc={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Ch.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&lc.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?i.options.trueStr:i.options.falseStr}};uc.boolTag=lc});var ht=g(dc=>{"use strict";function Rh({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}dc.stringifyNumber=Rh});var oa=g(dr=>{"use strict";var Ah=I(),aa=ht(),_h={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:aa.stringifyNumber},Th={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():aa.stringifyNumber(t)}},Ih={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 Ah.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:aa.stringifyNumber};dr.float=Ih;dr.floatExp=Th;dr.floatNaN=_h});var ca=g(hr=>{"use strict";var fc=ht(),fr=t=>typeof t=="bigint"||Number.isInteger(t),sa=(t,e,i,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),i);function hc(t,e,i){let{value:r}=t;return fr(r)&&r>=0?i+r.toString(e):fc.stringifyNumber(t)}var jh={identify:t=>fr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>sa(t,2,8,i),stringify:t=>hc(t,8,"0o")},$h={identify:fr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>sa(t,0,10,i),stringify:fc.stringifyNumber},Oh={identify:t=>fr(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>sa(t,2,16,i),stringify:t=>hc(t,16,"0x")};hr.int=$h;hr.intHex=Oh;hr.intOct=jh});var mc=g(pc=>{"use strict";var Hh=dt(),Dh=ur(),Bh=ft(),Lh=Kt(),Mh=na(),la=oa(),ua=ca(),Fh=[Hh.map,Bh.seq,Lh.string,Dh.nullTag,Mh.boolTag,ua.intOct,ua.int,ua.intHex,la.floatNaN,la.floatExp,la.float];pc.schema=Fh});var wc=g(gc=>{"use strict";var Vh=I(),qh=dt(),Wh=ft();function vc(t){return typeof t=="bigint"||Number.isInteger(t)}var pr=({value:t})=>JSON.stringify(t),zh=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:pr},{identify:t=>t==null,createNode:()=>new Vh.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:pr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:pr},{identify:vc,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})=>vc(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:pr}],Jh={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Gh=[qh.map,Wh.seq].concat(zh,Jh);gc.schema=Gh});var fa=g(yc=>{"use strict";var Yt=$i("buffer"),da=I(),Uh=zt(),Kh={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Yt.Buffer=="function")return Yt.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 Yt.Buffer=="function")s=o instanceof Yt.Buffer?o.toString("base64"):Yt.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=da.Scalar.BLOCK_LITERAL),e!==da.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let d=0,u=0;d<l;++d,u+=c)f[d]=s.substr(u,c);s=f.join(e===da.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return Uh.stringifyString({comment:t,type:e,value:s},r,n,a)}};yc.binary=Kh});var gr=g(vr=>{"use strict";var mr=P(),ha=He(),Yh=I(),Xh=Le();function Nc(t,e){if(mr.isSeq(t))for(let i=0;i<t.items.length;++i){let r=t.items[i];if(!mr.isPair(r)){if(mr.isMap(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let n=r.items[0]||new ha.Pair(new Yh.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]=mr.isPair(r)?r:new ha.Pair(r)}}else e("Expected a sequence for this tag");return t}function bc(t,e,i){let{replacer:r}=i,n=new Xh.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(ha.createPair(s,c,i))}return n}var Qh={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Nc,createNode:bc};vr.createPairs=bc;vr.pairs=Qh;vr.resolvePairs=Nc});var va=g(ma=>{"use strict";var kc=P(),pa=Ie(),Xt=Be(),Zh=Le(),Sc=gr(),Ue=class t extends Zh.YAMLSeq{constructor(){super(),this.add=Xt.YAMLMap.prototype.add.bind(this),this.delete=Xt.YAMLMap.prototype.delete.bind(this),this.get=Xt.YAMLMap.prototype.get.bind(this),this.has=Xt.YAMLMap.prototype.has.bind(this),this.set=Xt.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(kc.isPair(n)?(a=pa.toJS(n.key,"",i),o=pa.toJS(n.value,a,i)):a=pa.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=Sc.createPairs(e,i,r),a=new this;return a.items=n.items,a}};Ue.tag="tag:yaml.org,2002:omap";var ep={collection:"seq",identify:t=>t instanceof Map,nodeClass:Ue,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=Sc.resolvePairs(t,e),r=[];for(let{key:n}of i.items)kc.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ue,i)},createNode:(t,e,i)=>Ue.from(t,e,i)};ma.YAMLOMap=Ue;ma.omap=ep});var Rc=g(ga=>{"use strict";var Ec=I();function Pc({value:t,source:e},i){return e&&(t?xc:Cc).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var xc={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 Ec.Scalar(!0),stringify:Pc},Cc={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 Ec.Scalar(!1),stringify:Pc};ga.falseTag=Cc;ga.trueTag=xc});var Ac=g(wr=>{"use strict";var tp=I(),wa=ht(),ip={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:wa.stringifyNumber},rp={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():wa.stringifyNumber(t)}},np={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 tp.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:wa.stringifyNumber};wr.float=np;wr.floatExp=rp;wr.floatNaN=ip});var Tc=g(Zt=>{"use strict";var _c=ht(),Qt=t=>typeof t=="bigint"||Number.isInteger(t);function yr(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 ya(t,e,i){let{value:r}=t;if(Qt(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return _c.stringifyNumber(t)}var ap={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>yr(t,2,2,i),stringify:t=>ya(t,2,"0b")},op={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>yr(t,1,8,i),stringify:t=>ya(t,8,"0")},sp={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>yr(t,0,10,i),stringify:_c.stringifyNumber},cp={identify:Qt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>yr(t,2,16,i),stringify:t=>ya(t,16,"0x")};Zt.int=sp;Zt.intBin=ap;Zt.intHex=cp;Zt.intOct=op});var ba=g(Na=>{"use strict";var kr=P(),Nr=He(),br=Be(),Ke=class t extends br.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;kr.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new Nr.Pair(e.key,null):i=new Nr.Pair(e,null),br.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=br.findPair(this.items,e);return!i&&kr.isPair(r)?kr.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=br.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Nr.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(Nr.createPair(o,null,r));return a}};Ke.tag="tag:yaml.org,2002:set";var lp={collection:"map",identify:t=>t instanceof Set,nodeClass:Ke,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>Ke.from(t,e,i),resolve(t,e){if(kr.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Ke,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Na.YAMLSet=Ke;Na.set=lp});var Sa=g(Sr=>{"use strict";var up=ht();function ka(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 Ic(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return up.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 dp={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})=>ka(t,i),stringify:Ic},fp={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=>ka(t,!1),stringify:Ic},jc={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(jc.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),f=e[8];if(f&&f!=="Z"){let d=ka(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Sr.floatTime=fp;Sr.intTime=dp;Sr.timestamp=jc});var Hc=g(Oc=>{"use strict";var hp=dt(),pp=ur(),mp=ft(),vp=Kt(),gp=fa(),$c=Rc(),Ea=Ac(),Er=Tc(),wp=ir(),yp=va(),Np=gr(),bp=ba(),Pa=Sa(),kp=[hp.map,mp.seq,vp.string,pp.nullTag,$c.trueTag,$c.falseTag,Er.intBin,Er.intOct,Er.int,Er.intHex,Ea.floatNaN,Ea.floatExp,Ea.float,gp.binary,wp.merge,yp.omap,Np.pairs,bp.set,Pa.intTime,Pa.floatTime,Pa.timestamp];Oc.schema=kp});var Jc=g(Ra=>{"use strict";var Mc=dt(),Sp=ur(),Fc=ft(),Ep=Kt(),Pp=na(),xa=oa(),Ca=ca(),xp=mc(),Cp=wc(),Vc=fa(),ei=ir(),qc=va(),Wc=gr(),Dc=Hc(),zc=ba(),Pr=Sa(),Bc=new Map([["core",xp.schema],["failsafe",[Mc.map,Fc.seq,Ep.string]],["json",Cp.schema],["yaml11",Dc.schema],["yaml-1.1",Dc.schema]]),Lc={binary:Vc.binary,bool:Pp.boolTag,float:xa.float,floatExp:xa.floatExp,floatNaN:xa.floatNaN,floatTime:Pr.floatTime,int:Ca.int,intHex:Ca.intHex,intOct:Ca.intOct,intTime:Pr.intTime,map:Mc.map,merge:ei.merge,null:Sp.nullTag,omap:qc.omap,pairs:Wc.pairs,seq:Fc.seq,set:zc.set,timestamp:Pr.timestamp},Rp={"tag:yaml.org,2002:binary":Vc.binary,"tag:yaml.org,2002:merge":ei.merge,"tag:yaml.org,2002:omap":qc.omap,"tag:yaml.org,2002:pairs":Wc.pairs,"tag:yaml.org,2002:set":zc.set,"tag:yaml.org,2002:timestamp":Pr.timestamp};function Ap(t,e,i){let r=Bc.get(e);if(r&&!t)return i&&!r.includes(ei.merge)?r.concat(ei.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(Bc.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(ei.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Lc[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Lc).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Ra.coreKnownTags=Rp;Ra.getTags=Ap});var Ta=g(Gc=>{"use strict";var Aa=P(),_p=dt(),Tp=ft(),Ip=Kt(),xr=Jc(),jp=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,_a=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?xr.getTags(e,"compat"):e?xr.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?xr.coreKnownTags:{},this.tags=xr.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Aa.MAP,{value:_p.map}),Object.defineProperty(this,Aa.SCALAR,{value:Ip.string}),Object.defineProperty(this,Aa.SEQ,{value:Tp.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?jp:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Gc.Schema=_a});var Kc=g(Uc=>{"use strict";var $p=P(),Ia=Jt(),ti=Vt();function Op(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=Ia.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(ti.indentComment(c,""))}let o=!1,s=null;if(t.contents){if($p.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let f=a(t.contents.commentBefore);i.push(ti.indentComment(f,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Ia.stringify(t.contents,n,()=>s=null,c);s&&(l+=ti.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ia.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(ti.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(ti.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
|
+
`}Uc.stringifyDocument=Op});var ii=g(Yc=>{"use strict";var Hp=Mt(),pt=Ji(),Q=P(),Dp=He(),Bp=Ie(),Lp=Ta(),Mp=Kc(),ja=Vi(),Fp=Dn(),Vp=Ft(),$a=Hn(),Oa=class t{constructor(e,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Q.NODE_TYPE,{value:Q.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 $a.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,{[Q.NODE_TYPE]:{value:Q.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=Q.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){mt(this.contents)&&this.contents.add(e)}addIn(e,i){mt(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let r=ja.anchorNames(this);e.anchor=!i||r.has(i)?ja.findNewAnchor(i||"a",r):i}return new Hp.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=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=i.filter(m).map(String);w.length>0&&(i=i.concat(w)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=r??{},{onAnchor:d,setAnchors:u,sourceObjects:p}=ja.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Vp.createNode(e,f,v);return s&&Q.isCollection(h)&&(h.flow=!0),u(),h}createPair(e,i,r={}){let n=this.createNode(e,null,r),a=this.createNode(i,null,r);return new Dp.Pair(n,a)}delete(e){return mt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return pt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):mt(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return Q.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return pt.isEmptyPath(e)?!i&&Q.isScalar(this.contents)?this.contents.value:this.contents:Q.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return Q.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return pt.isEmptyPath(e)?this.contents!==void 0:Q.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=pt.collectionFromPath(this.schema,[e],i):mt(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):mt(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 $a.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 $a.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 Lp.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=Bp.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Fp.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 Mp.stringifyDocument(this,e)}};function mt(t){if(Q.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Yc.Document=Oa});var ai=g(ni=>{"use strict";var ri=class extends Error{constructor(e,i,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=i}},Ha=class extends ri{constructor(e,i,r){super("YAMLParseError",e,i,r)}},Da=class extends ri{constructor(e,i,r){super("YAMLWarning",e,i,r)}},qp=(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
|
-
`+
|
|
69
|
-
`+
|
|
70
|
-
`+
|
|
71
|
-
`+
|
|
72
|
-
`+
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",
|
|
74
|
-
`;for(let h=
|
|
75
|
-
`):
|
|
76
|
-
`:!p&&
|
|
77
|
-
`&&(
|
|
65
|
+
`}};ni.YAMLError=ri;ni.YAMLParseError=Ha;ni.YAMLWarning=Da;ni.prettifyError=qp});var oi=g(Xc=>{"use strict";function Wp(t,{flow:e,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,v=!1,h=null,m=null,w=null,y=null,b=null,k=null,S=null;for(let N of t)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),N.type){case"space":!e&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(h=N),f=!0;break;case"comment":{f||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let j=N.source.substring(1)||" ";d?d+=u+j:d=j,u="",l=!1;break}case"newline":l?d?d+=N.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=N.source,l=!0,p=!0,(m||w)&&(y=N),f=!0;break;case"anchor":m&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=N,S??(S=N.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),w=N,S??(S=N.offset),l=!1,f=!1,v=!0;break}case i:(m||w)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),k=N,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(e){b&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),b=N,l=!1,f=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let E=t[t.length-1],R=E?E.offset+E.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:w,newlineAfterProp:y,end:R,start:S??R}}Xc.resolveProps=Wp});var Cr=g(Qc=>{"use strict";function Ba(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(Ba(e.key)||Ba(e.value))return!0}return!1;default:return!0}}Qc.containsNewline=Ba});var La=g(Zc=>{"use strict";var zp=Cr();function Jp(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&zp.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Zc.flowIndentCheck=Jp});var Ma=g(tl=>{"use strict";var el=P();function Gp(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||el.isScalar(a)&&el.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,i))}tl.mapIncludes=Gp});var sl=g(ol=>{"use strict";var il=He(),Up=Be(),rl=oi(),Kp=Cr(),nl=La(),Yp=Ma(),al="All mapping items must start at the same column";function Xp({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??Up.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let f of r.items){let{start:d,key:u,sep:p,value:v}=f,h=rl.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",al)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Kp.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",al);i.atKey=!0;let w=h.end,y=u?t(i,u,h,n):e(i,w,d,null,h,n);i.schema.compat&&nl.flowIndentCheck(r.indent,u,n),i.atKey=!1,Yp.mapIncludes(i,s.items,y)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let b=rl.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=b.end,b.found){m&&(v?.type==="block-map"&&!b.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<b.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?t(i,v,b,n):e(i,c,p,null,b,n);i.schema.compat&&nl.flowIndentCheck(r.indent,v,n),c=k.range[2];let S=new il.Pair(y,k);i.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(y.comment?y.comment+=`
|
|
68
|
+
`+b.comment:y.comment=b.comment);let k=new il.Pair(y);i.options.keepSourceTokens&&(k.srcToken=f),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}ol.resolveBlockMap=Xp});var ll=g(cl=>{"use strict";var Qp=Le(),Zp=oi(),em=La();function tm({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??Qp.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:f,value:d}of r.items){let u=Zp.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?t(i,d,u,n):e(i,u.end,f,null,u,n);i.schema.compat&&em.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}cl.resolveBlockSeq=tm});var vt=g(ul=>{"use strict";function im(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 f=c.substring(1)||" ";n?n+=o+f:n=f,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}}ul.resolveEnd=im});var pl=g(hl=>{"use strict";var rm=P(),nm=He(),dl=Be(),am=Le(),om=vt(),fl=oi(),sm=Cr(),cm=Ma(),Fa="Block collections are not allowed within flow collections",Va=t=>t&&(t.type==="block-map"||t.type==="block-seq");function lm({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?dl.YAMLMap:am.YAMLSeq),l=new c(i.schema);l.flow=!0;let f=i.atRoot;f&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let w=r.items[m],{start:y,key:b,sep:k,value:S}=w,E=fl.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:b??k?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!S){m===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+E.comment:l.comment=E.comment),d=E.end;continue}!o&&i.options.strict&&sm.containsNewline(b)&&n(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let R="";e:for(let N of y)switch(N.type){case"comma":case"space":break;case"comment":R=N.source.substring(1);break e;default:break e}if(R){let N=l.items[l.items.length-1];rm.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
|
|
70
|
+
`+R:N.comment=R,E.comment=E.comment.substring(R.length+1)}}if(!o&&!k&&!E.found){let R=S?t(i,S,E,n):e(i,E.end,k,null,E,n);l.items.push(R),d=R.range[2],Va(S)&&n(R.range,"BLOCK_IN_FLOW",Fa)}else{i.atKey=!0;let R=E.end,N=b?t(i,b,E,n):e(i,R,y,null,E,n);Va(b)&&n(N.range,"BLOCK_IN_FLOW",Fa),i.atKey=!1;let j=fl.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(j.found){if(!o&&!E.found&&i.options.strict){if(k)for(let $ of k){if($===j.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<j.found.offset-1024&&n(j.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(j.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let _e=S?t(i,S,j,n):j.found?e(i,j.end,k,null,j,n):null;_e?Va(S)&&n(_e.range,"BLOCK_IN_FLOW",Fa):j.comment&&(N.comment?N.comment+=`
|
|
71
|
+
`+j.comment:N.comment=j.comment);let ot=new nm.Pair(N,_e);if(i.options.keepSourceTokens&&(ot.srcToken=w),o){let $=l;cm.mapIncludes(i,$.items,N)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(ot)}else{let $=new dl.YAMLMap(i.schema);$.flow=!0,$.items.push(ot);let ls=(_e??N).range;$.range=[N.range[0],ls[1],ls[2]],l.items.push($)}d=_e?_e.range[2]:j.end}}let u=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===u)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),w=f?`${m} must end with a ${u}`:`${m} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=om.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}hl.resolveFlowCollection=lm});var vl=g(ml=>{"use strict";var um=P(),dm=I(),fm=Be(),hm=Le(),pm=sl(),mm=ll(),vm=pl();function qa(t,e,i,r,n,a){let o=i.type==="block-map"?pm.resolveBlockMap(t,e,i,r,a):i.type==="block-seq"?mm.resolveBlockSeq(t,e,i,r,a):vm.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 gm(t,e,i,r,n){let a=r.tag,o=a?e.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===fm.YAMLMap.tagName&&s==="map"||o===hm.YAMLSeq.tagName&&s==="seq")return qa(t,e,i,n,o);let c=e.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=e.schema.knownTags[o];if(u?.collection===s)e.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),qa(t,e,i,n,o)}let l=qa(t,e,i,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),e.options)??l,d=um.isNode(f)?f:new dm.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ml.composeCollection=gm});var za=g(gl=>{"use strict";var Wa=I();function wm(t,e,i){let r=e.offset,n=ym(e,t.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Wa.Scalar.BLOCK_FOLDED:Wa.Scalar.BLOCK_LITERAL,o=e.source?Nm(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,f=0;for(let h=0;h<s;++h){let[m,w]=o[h];if(w===""||w==="\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),f=h,c===0&&!t.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",u="",p=!1;for(let h=0;h<f;++h)d+=o[h][0].slice(c)+`
|
|
74
|
+
`;for(let h=f;h<s;++h){let[m,w]=o[h];l+=m.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-w.length-(y?2:1),"BAD_INDENT",k),m=""}a===Wa.Scalar.BLOCK_LITERAL?(d+=u+m.slice(c)+w,u=`
|
|
75
|
+
`):m.length>c||w[0]===" "?(u===" "?u=`
|
|
76
|
+
`:!p&&u===`
|
|
77
|
+
`&&(u=`
|
|
78
78
|
|
|
79
|
-
`),d+=
|
|
80
|
-
`,p=!0):
|
|
79
|
+
`),d+=u+m.slice(c)+w,u=`
|
|
80
|
+
`,p=!0):w===""?u===`
|
|
81
81
|
`?d+=`
|
|
82
|
-
`:
|
|
83
|
-
`:(d+=
|
|
82
|
+
`:u=`
|
|
83
|
+
`:(d+=u+w,u=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
|
|
84
84
|
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let
|
|
87
|
+
`}let v=r+n.length+e.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function ym({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 u=1;u<n.length;++u){let p=n[u];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=t+u)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",d=n.length;for(let u=1;u<e.length;++u){let p=e[u];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,f=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:d}}function Nm(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}gl.resolveBlockScalar=wm});var Ga=g(yl=>{"use strict";var Ja=I(),bm=vt();function km(t,e,i){let{offset:r,type:n,source:a,end:o}=t,s,c,l=(u,p,v)=>i(r+u,p,v);switch(n){case"scalar":s=Ja.Scalar.PLAIN,c=Sm(a,l);break;case"single-quoted-scalar":s=Ja.Scalar.QUOTE_SINGLE,c=Em(a,l);break;case"double-quoted-scalar":s=Ja.Scalar.QUOTE_DOUBLE,c=Pm(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 f=r+a.length,d=bm.resolveEnd(o,f,e,i);return{value:c,type:s,comment:d.comment,range:[r,f,d.offset]}}function Sm(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}`),wl(t)}function Em(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),wl(t.slice(1,-1)).replace(/''/g,"'")}function wl(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 Pm(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}=xm(t,r);i+=a,r=o}else if(n==="\\"){let a=t[++r],o=Cm[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+=Rm(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 xm(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 Cm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Rm(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}}yl.resolveFlowScalar=km});var kl=g(bl=>{"use strict";var Ye=P(),Nl=I(),Am=za(),_m=Ga();function Tm(t,e,i,r){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?Am.resolveBlockScalar(t,e,r):_m.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[Ye.SCALAR]:c?l=Im(t.schema,n,c,i,r):e.type==="scalar"?l=jm(t,n,e,r):l=t.schema[Ye.SCALAR];let f;try{let d=l.resolve(n,u=>r(i??e,"TAG_RESOLVE_FAILED",u),t.options);f=Ye.isScalar(d)?d:new Nl.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);r(i??e,"TAG_RESOLVE_FAILED",u),f=new Nl.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Im(t,e,i,r,n){if(i==="!")return t[Ye.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[Ye.SCALAR])}function jm({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[Ye.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Ye.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}bl.composeScalar=Tm});var El=g(Sl=>{"use strict";function $m(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}Sl.emptyScalarPosition=$m});var Cl=g(Ka=>{"use strict";var Om=Mt(),Hm=P(),Dm=vl(),Pl=kl(),Bm=vt(),Lm=El(),Mm={composeNode:xl,composeEmptyNode:Ua};function xl(t,e,i,r){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(e.type){case"alias":l=Fm(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=Pl.composeScalar(t,e,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Dm.composeCollection(Mm,t,e,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",u)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=Ua(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&&(!Hm.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&&f&&(l.srcToken=e),l}function Ua(t,e,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Lm.emptyScalarPosition(e,i,r),indent:-1,source:""},d=Pl.composeScalar(t,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Fm({options:t},{offset:e,source:i,end:r},n){let a=new Om.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=Bm.resolveEnd(r,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Ka.composeEmptyNode=Ua;Ka.composeNode=xl});var _l=g(Al=>{"use strict";var Vm=ii(),Rl=Cl(),qm=vt(),Wm=oi();function zm(t,e,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new Vm.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Wm.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Rl.composeNode(l,n,f,o):Rl.composeEmptyNode(l,f.end,r,null,f,o);let d=c.contents.range[2],u=qm.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,d,u.offset],c}Al.composeDoc=zm});var Xa=g(jl=>{"use strict";var Jm=$i("process"),Gm=Hn(),Um=ii(),si=ai(),Tl=P(),Km=_l(),Ym=vt();function ci(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 Il(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 Ya=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ci(i);a?this.warnings.push(new si.YAMLWarning(o,r,n)):this.errors.push(new si.YAMLParseError(o,r,n))},this.directives=new Gm.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:r,afterEmptyLine:n}=Il(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(Tl.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Tl.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:Il(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(Jm.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(i,r,n)=>{let a=ci(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=Km.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 si.YAMLParseError(ci(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 si.YAMLParseError(ci(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Ym.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 si.YAMLParseError(ci(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 Um.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}}};jl.Composer=Ya});var Hl=g(Rr=>{"use strict";var Xm=za(),Qm=Ga(),Zm=ai(),$l=zt();function ev(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 Zm.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Qm.resolveFlowScalar(t,e,r);case"block-scalar":return Xm.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function tv(t,e){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=$l.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
|
-
`,
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:
|
|
114
|
-
`),
|
|
115
|
-
`;if(
|
|
116
|
-
`});for(let c of Object.keys(
|
|
117
|
-
`};delete
|
|
111
|
+
`),f=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
+
`,u=[{type:"block-scalar-header",offset:a,indent:r,source:f}];return Ol(u,c)||u.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:r,props:u,source:d}}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 iv(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=$l.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">":rv(t,c);break;case'"':Qa(t,c,"double-quoted-scalar");break;case"'":Qa(t,c,"single-quoted-scalar");break;default:Qa(t,c,"scalar")}}function rv(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}];Ol(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 Ol(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 Qa(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})}}}Rr.createScalarToken=tv;Rr.resolveAsScalar=ev;Rr.setScalarValue=iv});var Bl=g(Dl=>{"use strict";var nv=t=>"type"in t?_r(t):Ar(t);function _r(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=_r(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Ar(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Ar(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Ar(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 Ar({start:t,key:e,sep:i,value:r}){let n="";for(let a of t)n+=a.source;if(e&&(n+=_r(e)),i)for(let a of i)n+=a.source;return r&&(n+=_r(r)),n}Dl.stringify=nv});var Vl=g(Fl=>{"use strict";var Za=Symbol("break visit"),av=Symbol("skip children"),Ll=Symbol("remove item");function Xe(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Ml(Object.freeze([]),t,e)}Xe.BREAK=Za;Xe.SKIP=av;Xe.REMOVE=Ll;Xe.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};Xe.parentCollection=(t,e)=>{let i=Xe.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 Ml(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=Ml(Object.freeze(t.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Za)return Za;s===Ll&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}Fl.visit=Xe});var Tr=g(W=>{"use strict";var eo=Hl(),ov=Bl(),sv=Vl(),to="\uFEFF",io="",ro="",no="",cv=t=>!!t&&"items"in t,lv=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function uv(t){switch(t){case to:return"<BOM>";case io:return"<DOC>";case ro:return"<FLOW_END>";case no:return"<SCALAR>";default:return JSON.stringify(t)}}function dv(t){switch(t){case to:return"byte-order-mark";case io:return"doc-mode";case ro:return"flow-error-end";case no: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=eo.createScalarToken;W.resolveAsScalar=eo.resolveAsScalar;W.setScalarValue=eo.setScalarValue;W.stringify=ov.stringify;W.visit=sv.visit;W.BOM=to;W.DOCUMENT=io;W.FLOW_END=ro;W.SCALAR=no;W.isCollection=cv;W.isScalar=lv;W.prettyToken=uv;W.tokenType=dv});var so=g(Wl=>{"use strict";var li=Tr();function ae(t){switch(t){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var ql=new Set("0123456789ABCDEFabcdef"),fv=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ir=new Set(",[]{}"),hv=new Set(` ,[]{}
|
|
121
|
+
\r `),ao=t=>!t||hv.has(t),oo=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==="...")&&ae(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]===li.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 li.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==="...")&&ae(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&&!ae(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===":")&&ae(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(ao),"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("..."))&&ae(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield li.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(ao),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ae(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=>ae(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 li.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(ae(a)||e&&Ir.has(a))break;i=r}else if(ae(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&&Ir.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&&Ir.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield li.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(ao),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(ae(r)||i&&Ir.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(;!ae(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(fv.has(i))i=this.buffer[++e];else if(i==="%"&&ql.has(this.buffer[e+1])&&ql.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)}};Wl.Lexer=oo});var lo=g(zl=>{"use strict";var co=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}}}};zl.LineCounter=co});var fo=g(Yl=>{"use strict";var pv=$i("process"),Jl=Tr(),mv=so();function Me(t,e){for(let i=0;i<t.length;++i)if(t[i].type===e)return!0;return!1}function Gl(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 Kl(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 jr(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 gt(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 $r(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 Ul(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Me(e.start,"explicit-key-ind")&&!Me(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Kl(e.value)?e.value.end?$r(e.value.end,e.sep):e.value.end=e.sep:$r(e.start,e.sep),delete e.sep)}var uo=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 mv.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,pv.env.LOG_TOKENS&&console.log("|",Jl.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let i=Jl.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"&&Ul(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&&Gl(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":{Gl(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=jr(this.peek(2)),r=gt(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)){$r(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(Me(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(Kl(i.key)&&!Me(i.sep,"newline")){let o=gt(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(Me(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=gt(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]}):Me(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&&!Me(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)){$r(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||Me(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=jr(r),a=gt(n);Ul(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=xa(t),n=Ii(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=xa(t),n=Ii(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())}}};yh.Parser=Cc});var Eh=R(On=>{"use strict";var Nh=fc(),qb=Cn(),jn=An(),Vb=us(),Wb=M(),zb=Ec(),bh=Rc();function kh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new zb.LineCounter||null,prettyErrors:t}}function Jb(e,t={}){let{lineCounter:i,prettyErrors:n}=kh(t),r=new bh.Parser(i?.addNewLine),a=new Nh.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(jn.prettifyError(e,i)),s.warnings.forEach(jn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Sh(e,t={}){let{lineCounter:i,prettyErrors:n}=kh(t),r=new bh.Parser(i?.addNewLine),a=new Nh.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 jn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(jn.prettifyError(e,i)),o.warnings.forEach(jn.prettifyError(e,i))),o}function Gb(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=Sh(e,i);if(!r)return null;if(r.warnings.forEach(a=>Vb.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 Ub(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 Wb.isDocument(e)&&!n?e.toString(i):new qb.Document(e,n,i).toString(i)}On.parse=Gb;On.parseAllDocuments=Jb;On.parseDocument=Sh;On.stringify=Ub});var _a=R(V=>{"use strict";var Kb=fc(),Yb=Cn(),Xb=Js(),Pc=An(),Qb=ln(),Tt=M(),Zb=Ct(),ek=te(),tk=Pt(),ik=At(),nk=Pa(),rk=kc(),ak=Ec(),ok=Rc(),Ia=Eh(),Ch=an();V.Composer=Kb.Composer;V.Document=Yb.Document;V.Schema=Xb.Schema;V.YAMLError=Pc.YAMLError;V.YAMLParseError=Pc.YAMLParseError;V.YAMLWarning=Pc.YAMLWarning;V.Alias=Qb.Alias;V.isAlias=Tt.isAlias;V.isCollection=Tt.isCollection;V.isDocument=Tt.isDocument;V.isMap=Tt.isMap;V.isNode=Tt.isNode;V.isPair=Tt.isPair;V.isScalar=Tt.isScalar;V.isSeq=Tt.isSeq;V.Pair=Zb.Pair;V.Scalar=ek.Scalar;V.YAMLMap=tk.YAMLMap;V.YAMLSeq=ik.YAMLSeq;V.CST=nk;V.Lexer=rk.Lexer;V.LineCounter=ak.LineCounter;V.Parser=ok.Parser;V.parse=Ia.parse;V.parseAllDocuments=Ia.parseAllDocuments;V.parseDocument=Ia.parseDocument;V.stringify=Ia.stringify;V.visit=Ch.visit;V.visitAsync=Ch.visitAsync});import{promises as Rl}from"fs";import em from"path";var bo=Go(_a(),1);import{promises as Gp}from"fs";import ut from"path";import{createHash as uk}from"node:crypto";import{promises as Fe}from"node:fs";import Ae from"node:path";import{TextDecoder as dk}from"node:util";import Ac from"path";var sk=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ck=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function lk(e){return e.toLowerCase().startsWith(".env")}function Ze(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>lk(n))?"environment-file":i.some(n=>ck.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>sk.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function xc(e,t){let i=Ze(t);if(i)return i;let n=Ac.resolve(e.projectRoot,...t.split("/")),r=Ac.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Ac.resolve(e.configFile)?"native-runtime":null}function It(e){return e!==0&&e!==0n&&e!=="0"}function se(e,t){return It(e.dev)&&It(t.dev)&&It(e.ino)&&It(t.ino)}function L(e,t){let i=It(e.dev)&&It(t.dev);if(i&&e.dev!==t.dev)return!1;let n=It(e.ino)&&It(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var $n=1024*1024;function Tc(e,t){let i=Ae.relative(e,t);return i===""||!Ae.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ae.sep}`)}function fk(e){let t=Ae.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})||Ae.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),n=Ze(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 hk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function pk(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ja(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 Rh(e){let t=await Fe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Fe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function mk(e,t){let i=Ae.resolve(e),n=Ae.resolve(t);if(!Tc(i,n))throw new Error("Native artifact path is outside its root");let r=[await Rh(i)],a=i;for(let o of Ae.relative(i,n).split(Ae.sep).filter(Boolean)){a=Ae.join(a,o);let s=await Rh(a);if(!Tc(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Ph(e){for(let t of e){let i=await Fe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!pk(t,i)||await Fe.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ce(e){let t=fk(e.ref),i=hk(e.maxBytes??$n),n=Ae.resolve(e.root,...t.split("/")),r=await mk(e.root,Ae.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Fe.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 Fe.realpath(n);if(!Tc(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Fe.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Fe.lstat(n),Fe.realpath(n)]);if(await Ph(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!ja(a,c)||!ja(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(),Fe.lstat(n),Fe.realpath(n)]);if(await Ph(r),!h.isFile()||h.isSymbolicLink()||g!==o||!ja(c,m)||!ja(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),N;try{N=new dk("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:uk("sha256").update(S).digest("hex"),text:N}}finally{await s.close()}}import{randomUUID as vk}from"crypto";import{promises as le}from"fs";import De from"path";function _c(e,t){let i=De.relative(e,t);return i===""||!De.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${De.sep}`)}function gk(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ic(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 Ah(e){let t=await le.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 le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Hn(e){for(let t of e){let i=await le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!gk(t,i)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function wk(e,t){let i=De.resolve(e),n=De.resolve(t);if(!_c(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await Ah(i)],a=De.relative(i,n).split(De.sep).filter(Boolean),o=i;for(let s of a){await Hn(r),o=De.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ah(o);if(!_c(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Hn(r),r}async function yk(e){let t;try{t=await le.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 Nk(e,t,i={}){let n=De.dirname(e),r=i.containedRoot?await wk(i.containedRoot,n):null;r||await le.mkdir(n,{recursive:!0});let a=De.join(n,`.${De.basename(e)}.${vk()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Hn(r),!c.isFile()||c.isSymbolicLink()||!Ic(s,c)||!_c(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(),!Ic(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),r){await Hn(r);let c=await le.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Ic(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await le.link(a,e),await le.unlink(a)):await le.rename(a,e),await yk(n)}catch(c){if(await o?.close(),!r)await le.rm(a,{force:!0});else try{await Hn(r),await le.rm(a,{force:!0})}catch{}throw c}}async function ei(e,t,i={}){await Nk(e,t,i)}async function Le(e,t,i={}){await ei(e,JSON.stringify(t,null,2)+`
|
|
143
|
-
`,i)}var Oc=Go(_a(),1);import Oa from"path";var Dn=64*1024,$a=1024,Ha=64,$c=5,bk=[".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/**"],we={include:["**/*"],exclude:[...bk],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function kk(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Oa.posix.isAbsolute(i)||Oa.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 ti(e){let t=kk(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Th(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 Hc(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||Oa.posix.isAbsolute(n)||Oa.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 Fn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ih(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 Fa(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>$a)throw new Error(`${t} exceeds ${$a} 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>Ha)throw new Error(`${t} contains more than ${Ha} wildcard tokens`);return e}function xh(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=>Fa(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function jc(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 Sk(e){if(e===void 0)return{...we,include:[...we.include],exclude:[...we.exclude]};let t=Fn(e,"native.snapshot");return{include:xh(t.include,"native.snapshot.include",we.include),exclude:xh(t.exclude,"native.snapshot.exclude",we.exclude),max_files:jc(t.max_files,we.max_files,"native.snapshot.max_files"),max_total_bytes:jc(t.max_total_bytes,we.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:jc(t.max_duration_ms,we.max_duration_ms,"native.snapshot.max_duration_ms")}}function Ek(e){if(e===void 0)return;let t=Fn(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=Fn(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:ti(n),toArtifactRoot:ti(r),stage:a,...o?{cleanup:o}:{}}}function Ck(e,t={}){let i=Fn(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??$c;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Ek(i.pending_root_move);return{artifact_root:ti(n),language:Ih(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:Sk(i.snapshot),...s?{pending_root_move:s}:{}}}function Rk(e){let t=Fn(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:Th(t.artifact_layout),language:Ih(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function Pk(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Ak(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 Ln(e,t={}){let i=(0,Oc.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=Pk(r.ambient_resume),o=r.native===void 0?void 0:Ck(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:Rk(r.classic),c=Ak(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Da(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:ti(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:$c,snapshot:{...we,include:[...we.include],exclude:[...we.exclude]}}}}import{createHash as Tk}from"crypto";import{promises as Ba}from"fs";import _t from"path";import{constants as La,promises as ii}from"fs";var Me=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function Fc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function _h(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Mn(e){return{dev:e.dev,ino:e.ino,birthtime:Fc(e)}}function Ma(e,t){let i=Mn(e),n=Mn(t);return se(i,n)?L(i,n):L(i,n)&&Fc(e)===Fc(t)&&_h(e)===_h(t)&&e.size===t.size}async function ni(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 ii.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new Me("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Me("too-large",`${n} exceeds ${t} bytes`);let o=await ii.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Mn(a)});let s=process.platform==="win32"?La.O_RDONLY:La.O_RDONLY|La.O_NOFOLLOW|La.O_NONBLOCK,c;try{c=await ii.open(e,s)}catch(l){throw l.code==="ELOOP"?new Me("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),ii.lstat(e,{bigint:r}),ii.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ma(a,l)||!Ma(a,u))throw new Me("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Mn(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 Me("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}),ii.lstat(e,{bigint:r}),ii.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||S!==o||!Ma(a,h)||!Ma(a,g))throw new Me("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:Mn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function xk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Dc(e,t){let i=_t.relative(e,t);return i===""||!_t.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_t.sep}`)}async function jh(e,t){let i=_t.resolve(e),n=await Ba.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ba.realpath(i)}async function Oh(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 Ba.lstat(r)}catch(u){if(xk(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 Ba.realpath(r);if(!Dc(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 Bn(e,t,i){let n=Hc(t,i.label),r=_t.resolve(e),a=await jh(r,i.label),o=n.split("/"),s=_t.resolve(r,...o);if(!Dc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Oh(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ri(e,t,i,n){let r=await Bn(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 jh(r.projectRoot,n.label);return ni(r.target,i,{...n,verify:async(o,s)=>{if(!Dc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Oh(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var qn=".comet/config.yaml";function Ik(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Lc(e,t={}){return(await qa(e,t)).document}async function _k(e){try{return(await ri(e,qn,Dn,{label:qn})).bytes}catch(t){if(Ik(t))return null;throw t}}function jk(e){return e?{exists:!0,sha256:Tk("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function qa(e,t={}){let i=await _k(e);return{document:i?Ln(i.toString("utf8"),t):null,identity:jk(i)}}var sI=16*1024;import{promises as _i}from"fs";import G from"path";import Dk from"os";var Wa=".comet/config.yaml";async function qc(e){try{return await _i.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Lk(e){try{let t=await _i.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Vn(e,t){let i=G.relative(e,t);return i===""||!G.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${G.sep}`)}async function Wn(e){let t=[],i=e;for(;!await qc(i);){let r=G.dirname(i);if(r===i)break;t.push(G.basename(i)),i=r}let n=await _i.realpath(i);return G.resolve(n,...t.reverse())}async function Hh(e){try{return(await _i.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function za(e){let t=G.resolve(e);try{(await _i.stat(t)).isDirectory()||(t=G.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=G.resolve(Dk.homedir());for(;;){if(!(t===n&&i!==n)){let o=G.join(t,...Wa.split("/")),s=t===i||await Lk(o);if(await qc(o)&&s)return t}if(await qc(G.join(t,".git")))return t;let a=G.dirname(t);if(a===t)return i;t=a}}function Ja(e){return ti(e)}async function Mk(e,t){let i=Ja(t),n=G.resolve(e,...i.split("/")),r=await _i.realpath(e),a=await Wn(n);if(!Vn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Vc(e,t){let i=Ja(t),n=await Mk(e,i),r=G.join(n,"comet");if(await Hh(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Wn(n),Wn(r)]);if(!Vn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:G.resolve(e),configFile:G.join(e,...Wa.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:G.join(r,"specs"),changesDir:G.join(r,"changes"),archiveDir:G.join(r,"archive"),runtimeDir:G.join(r,"runtime"),locksDir:G.join(r,"runtime","locks"),transactionsDir:G.join(r,"runtime","transactions")}}function z(e,t){return Vn(G.resolve(e),G.resolve(t))}async function $(e,t){let i=G.resolve(e),n=G.resolve(t);if(!Vn(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Hh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([Wn(i),Wn(n)]);if(!Vn(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Wc=we;var Ga=Fa;function qk(e="docs",t="en"){return Da(e,t)}async function jt(e){let t=(await Lc(e))?.config??null;return t?.native?t:null}async function zn(e){let t=await jt(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 Fh(e){let t=await za(e.startPath),i=await jt(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Wa} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?Ja(e.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??qk(n??"docs"),a=await Vc(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as vS}from"fs";import gS from"path";import{AsyncLocalStorage as Vk}from"async_hooks";import{randomUUID as Mh}from"crypto";import{promises as xe}from"fs";import Bh from"os";import fe from"path";var Dh=16*1024,qh=".coordinator",Wk=5e3,Lh=new Vk,Ua=new Map;function zk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Jk(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 Vh(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 zc(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 Jc(e,t){return zc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function ct(e){let t,i;try{let n=await ni(e,Dh,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Me?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Dh} 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:Jk(JSON.parse(t.toString("utf8")),e),identity:Vh(i)}}async function Gk(e){return(await ct(e))?.owner??null}function Wh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Bh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Zk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Uk(e,t){try{await xe.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xe.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Gc(e,t){let i=await ct(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Jc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xe.mkdir(t,{recursive:!0});let n=fe.join(t,`${fe.basename(e.file)}.${e.owner.id}.${Mh()}.removed`);try{await xe.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await ct(n);if(!r||r.owner.id!==e.owner.id||!zc(r.identity,e.identity))throw await Uk(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xe.rm(n,{force:!0}),"removed"}function zh(e){return{id:Mh(),pid:process.pid,hostname:Bh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Jh(e,t){let i;try{i=await xe.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await Gk(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
144
|
-
`,"utf8"),await i.sync(),Vh(await i.stat({bigint:!0}))}finally{await i.close()}}async function Kk(e,t){let i=await $(e.nativeRoot,e.locksDir);await xe.mkdir(i,{recursive:!0});let n=await $(e.nativeRoot,fe.join(i,qh));await xe.mkdir(n,{recursive:!0});let r=zh(t),a=fe.join(n,`.${r.id}.tmp`),o=fe.join(n,`${r.id}.claim`);try{let s=await Jh(a,r);await xe.rename(a,o);let c=await ct(o);if(!c||!zc(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 xe.rm(a,{force:!0})}}async function Yk(e){let t=fe.dirname(e.file),i=!1,n=fe.basename(e.file);for(let r of await xe.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 ct(a),s=Wh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Gc(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function Gh(e){let t=await ct(e.file);if(t){if(t.owner.id!==e.owner.id||!Jc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Gc(t,fe.dirname(e.file))}}async function Xk(e,t){let i=Date.now()+Wk;for(;;){let n=await Kk(e,t);if(!await Yk(n))return n;if(await Gh(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 Qk(e){let t=Ua.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Ua.set(e,r),await t,()=>{i(),Ua.get(e)===r&&Ua.delete(e)}}async function Uh(e,t,i){let n=fe.resolve(e.locksDir),r=Lh.getStore();if(r?.has(n))return i();let a=await Qk(n);try{let o=await Xk(e,t),s=new Map(r??[]);return s.set(n,o),await Lh.run(s,async()=>{try{return await i()}finally{await Gh(o)}})}finally{a()}}async function Jn(e,t,i){return Uh(e,`acquire ${t}`,async()=>{let n=await $(e.nativeRoot,e.locksDir);await xe.mkdir(n,{recursive:!0});let r=await $(e.nativeRoot,fe.join(n,zk(t))),a=zh(i),o=await Jh(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function Gn(e){await ct(e.file)&&await Uh(e,`release ${fe.basename(e.file)}`,async()=>{let t=await ct(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Jc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=fe.join(e.locksDir,qh);await Gc(t,i)})}function Zk(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Kh(e){return Wh(await ct(e))}import lt from"path";import{TextDecoder as oS}from"util";import{createHash as eS}from"node:crypto";import{constants as Ka,promises as Se}from"node:fs";import Be from"node:path";import{TextDecoder as tS}from"node:util";function Xa(e,t){let i=Be.relative(e,t);return i===""||!Be.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Be.sep}`)}function Yh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function iS(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nS(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ya(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 Uc(e,t){let i=await Se.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Se.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Kc(e,t,i){let n=Be.resolve(e),r=Be.resolve(t);if(!Xa(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Uc(n,i)],o=n;for(let s of Be.relative(n,r).split(Be.sep).filter(Boolean)){await et(a,i),o=Be.join(o,s);let c=await Uc(o,i);if(!Xa(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await et(a,i),a}async function et(e,t){for(let i of e){let n=await Se.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!iS(i,n)||await Se.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function rS(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 tt(e){let t=Yh(e.maxBytes),i=Be.resolve(e.file),n=await Kc(e.root,Be.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>Uc(Be.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await et(n,e.label);let a=await Se.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=nS(a),s=await Se.realpath(i);if(!Xa(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Xa(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ka.O_RDONLY:Ka.O_RDONLY|Ka.O_NOFOLLOW|Ka.O_NONBLOCK,l=await Se.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Se.lstat(i),Se.realpath(i)]);if(await et(n,e.label),await et(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Ya(o,u)||!Ya(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await rS(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),Se.lstat(i),Se.realpath(i)]);if(await et(n,e.label),await et(r,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!Ya(o,m)||!Ya(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:eS("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Xh(e){let t=await tt(e),i;try{i=new tS("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 Un(e){let t=await Kc(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Se.readdir(e.directory,{withFileTypes:!0});else{let n=Yh(e.maxEntries);i=[];let r=await Se.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 et(t,e.label),{entries:i,verify:()=>et(t,e.label)}}async function Qa(e){let t=await Kc(e.root,e.directory,e.label);return{verify:()=>et(t,e.label)}}var sS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),cS=new Set(["id","type","source","target","staged","backup"]),lS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),uS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var ep=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var dS=256*1024,XI=1024*1024,QI=16*1024;var ZI=64*1024*1024;var fS=new oS("utf-8",{fatal:!0});function eo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function to(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 tp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Yc(e,t){if(typeof e!="string"||e.length===0||lt.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 Qh(e,t){if(Yc(e,t),e.includes("\\")||e!==lt.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 hS(e,t){let i=eo(e,`transaction operations[${t}]`);if(to(i,cS,`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`);Yc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Yc(i[n],`transaction operation ${i.id} ${n}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function ip(e){let t=eo(e,"Native Archive transaction journal");if(to(t,lS,"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"||!ep.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(!tp(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=eo(s,`Archive transaction operations[${c}]`);if(to(l,uS,`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`);Qh(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Qh(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 pS(e){let t=eo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return ip(t);if(to(t,sS,"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"||!ep.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!lt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!lt.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(!tp(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(hS),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 mS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return lt.join(e.transactionsDir,t)}function np(e,t){let i=mS(e,t);return{directory:i,journal:lt.join(i,"transaction.json"),events:lt.join(i,"events.jsonl"),staged:lt.join(i,"staged"),backups:lt.join(i,"backups")}}async function Xc(e,t){let i=np(e,t);return await Promise.all(Object.values(i).map(n=>$(e.nativeRoot,n))),i}async function Qc(e,t,i={}){let n=await Xc(e,t),r=await tt({root:e.nativeRoot,file:n.journal,maxBytes:dS,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(fS.decode(r.bytes)),o=pS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function wS(e,t){let i;try{i=await vS.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 yS(e,t){let i=Date.now()+5e3,n=gS.join(e.locksDir,"root-move.lock");for(;;)try{return await Jn(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await Kh(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 qe(e,t,i,n){let r=await yS(e,t);try{if(await zn(e.projectRoot),await wS(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Gn(r)}}function rp(e){return Number.isSafeInteger(e)&&e>=1}async function ap(e){if(!rp(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!rp(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as oo}from"crypto";import{spawn as mp}from"node:child_process";import{promises as X}from"fs";import F from"path";import{createHash as op}from"crypto";import{createReadStream as NS}from"fs";async function Kn(e){let t=op("sha256");for await(let i of NS(e))t.update(i);return t.digest("hex")}function W(e){return op("sha256").update(e).digest("hex")}var io={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},rl=1e3,bS=8*1024*1024,kS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SS=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),ES=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),CS=new Set(["schema","include","exclude","hash"]),RS=new Set(["provider","gitSelection","physicalSelection","projection"]),PS=new Set(["provider","selection"]),AS=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),xS=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),TS=new Set(["schema","status","before","after"]),IS=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),_S=new Set(["path","hash","size","type","gitObjectId"]),jS=new Set(["path","size","type","reason"]),OS=new Set(["ref","hash","count"]),$S=new Set(["change-created","legacy-migration","explicit"]),HS=new Set(["file","directory","other"]),FS=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"]),so=/^[a-f0-9]{64}$/u,vp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,DS=new Set(["EACCES","EPERM"]),Fi=64*1024,il=64*1024,LS=6e4,MS=1e3,BS=2,al={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},qS={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function gp(e){let t=e.deadlineMs??LS;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 Ve(e){return Math.max(0,e.deadlineAt-Date.now())}function _(e){return Ve(e)>=1}function Zc(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 $i(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function VS(e){let t={...qS,...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 WS(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&&F.win32.isAbsolute(n)?F.win32.resolve(n):"C:\\Windows",a=F.win32.join(r,"System32","taskkill.exe");if(!F.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=mp(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),MS),u.unref()}catch{d(!1)}});for(let s=0;s<BS;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 ol(e,t,i,n){let r=Ve(e);if(r<1)throw Zc();let a=e.gitProcess,o=mp(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=WS(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?Zc(m.error):Zc()}return{code:p,spawnError:s}});return{child:o,completion:f}}function wp(e){let t={...al,...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 no(e,t,i,n=il){let{child:r,completion:a}=ol(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>=Fi)return;let m=Fi-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 el(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Xn(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}=ol(e,t,i,n.stdin!==void 0),c=[],l=oo("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>=Fi)return;let C=Fi-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 ro(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 zS(e,t,i){if(i.length===0)return new Set;let n=await Xn(e,t,["check-ignore","--no-index","-z","--stdin"],{...al,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=ro(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function JS(e,t,i){let{child:n,completion:r}=ol(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>=Fi)return;let d=Fi-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 Hi(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function GS(e,t){return e.map(i=>{let n=Hi(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function US(e){let t=F.resolve(e);for(;;){try{return await X.lstat(F.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=F.dirname(t);if(i===t)return!1;t=i}}async function yp(e,t,i,n={}){let r=F.resolve(t.projectRoot),a=F.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(f=>{let p=F.relative(r,F.resolve(f)).replaceAll("\\","/"),m=Hi(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 Xn(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await Xn(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await Xn(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Np(e){return{stageBefore:el(e.stagedBefore),combined:el(e.combined),stageAfter:el(e.stagedAfter)}}async function bp(e,t,i=al,n={}){let r=F.resolve(t.projectRoot);if(!await US(r))return null;let a;try{a=await no(e,r,["rev-parse","--is-inside-work-tree"])}catch(N){throw $i(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 yp(e,t,i,n)}catch(N){throw $i(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=ro(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=Hi(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(ro),h=GS(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:Np(o)}}function $t(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function sp(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function KS(e,t){return!$t(e.stageBefore,e.stageAfter)||!$t(e.stageAfter,t.stageBefore)||!$t(e.combined,t.combined)||!$t(t.stageBefore,t.stageAfter)}async function kp(e,t,i,n,r){let a;try{a=await yp(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw $i(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=Np(a),c=sp(o)||sp(s),l=KS(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:W(`comet.native.git-selection-overflow.v2
|
|
145
|
-
${
|
|
146
|
-
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):W(`comet.native.physical-selection.v1
|
|
147
|
-
${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:d,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:N,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:p}}}function Sp(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function QS(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!Sp(e,t),r=[];return i&&r.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),n&&r.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:r,evidence:i||n?{schema:"comet.native.physical-selection.v1",status:i&&n?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Ep(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function lp(e,t){let n=(await no(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!vp.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return W(`gitlink:${n}`)}async function up(e,t){let i=await lp(e,t),n=await JS(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await lp(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function Yn(e,t){if(Ze(t)!==null)return!1;let i=F.resolve(e.projectRoot,...t.split("/"));return!Ht(F.resolve(e.nativeRoot),i)}function ZS(e,t){return F.relative(e,t).split(F.sep).join("/")}function eE(e,t){return t.map(i=>F.resolve(e,...i.split(/[\\/]/u)))}function Ht(e,t){let i=F.resolve(e),n=F.resolve(t);return n===i||z(i,n)}function ne(e){return DS.has(e.code??"")}function ie(e){return e.code==="ENOENT"}function sl(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
148
|
-
`)}function tE(e,t){return W(`comet.native.snapshot-policy.v1
|
|
149
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function tl(e,t,i){let n=new Set(t),r=[...t];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function iE(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function dp(e){let t=Ga(e,"Native snapshot pattern"),i=[];for(let n=0;n<t.length;n+=1){let r=t[n];r==="*"&&t[n+1]==="*"?(n+=1,t[n+1]==="/"?(n+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):r==="*"?i.push({kind:"star"}):r==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:r})}return(n,r)=>{let a=r?iE(r):void 0;if(a&&!a())return!1;let o=tl(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=tl(i,c,a),o===null||o.size===0)return!1}return tl(i,o,a)?.has(i.length)??!1}}function Cp(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>Ga(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>Ga(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=tE(t,i);if("hash"in e&&e.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:n},includeMatchers:t.map(dp),excludeMatchers:i.map(dp),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function nE(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function fp(e,t,i){if(!e)return!0;let n=()=>_(i),r=!1;for(let a of e.includeMatchers){if(!n())return!1;if(a(t,n)){r=!0;break}}if(!r)return!1;for(let a of e.excludeMatchers)if(!n()||a(t,n))return!1;return!0}function Qn(e,t,i){let n=JSON.stringify(i);return W(`${e}
|
|
150
|
-
${Buffer.byteLength(t)}:${t}
|
|
151
|
-
${Buffer.byteLength(n)}:${n}`)}function nl(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ao(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!nl(i))return e.splice(t,1),i}return null}function Ot(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 rE(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=oo("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()||!Ot(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()||!Ot(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 Te(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ie(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Oi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function it(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Rp(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=F.posix.normalize(e);if(i!==e||F.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function aE(e,t){let i=Te(e,`Native snapshot entry ${t}`);Ie(i,_S,`Native snapshot entry ${t}`);let n=Rp(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!so.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:it(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!vp.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function oE(e,t){let i=Te(e,`Native snapshot omission ${t}`);if(Ie(i,jS,`Native snapshot omission ${t}`),!HS.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!FS.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Rp(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:it(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function sE(e){let t=Te(e,"Native snapshot omission overflow");if(Ie(t,OS,"Native snapshot omission overflow"),typeof t.hash!="string"||!so.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:Oi(t.count,"Native snapshot omission overflow count")}}function ji(e,t){let i=Te(e,t);if(Ie(i,xS,t),typeof i.hash!="string"||!so.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=it(i.recordCount,`${t} recordCount`),r=it(i.storedRecordCount,`${t} storedRecordCount`),a=it(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 hp(e){let t=Te(e,"Native Git selection evidence");if(Ie(t,AS,"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=ji(t.stageBefore,"Native Git selection stageBefore"),n=ji(t.combined,"Native Git selection combined"),r=ji(t.stageAfter,"Native Git selection stageAfter"),a=ji(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ji(t.finalCombined,"Native Git selection finalCombined"),s=ji(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!$t(i,r)||!$t(r,a)||!$t(n,o)||!$t(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 pp(e,t){let i=Te(e,t);if(Ie(i,IS,t),typeof i.hash!="string"||!so.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=it(i.visitedNodeCount,`${t} visitedNodeCount`),r=it(i.recordCount,`${t} recordCount`),a=it(i.storedRecordCount,`${t} storedRecordCount`),o=it(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 cE(e){let t=Te(e,"Native physical selection evidence");if(Ie(t,TS,"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=pp(t.before,"Native physical selection before"),n=pp(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Sp(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 ai(e){let t=Te(e,"Native content snapshot manifest");if(Ie(t,SS,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!$S.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=Te(t.capture,"Native content snapshot capture");if(Ie(y,RS,"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:hp(y.gitSelection),v=y.physicalSelection===void 0?void 0:cE(y.physicalSelection),E=null;if(y.projection!==void 0){let I=Te(y.projection,"Native content snapshot projection");if(Ie(I,PS,"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:hp(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=Te(t.limits,"Native content snapshot limits");Ie(n,ES,"Native content snapshot limits");let r={maxFiles:Oi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Oi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Oi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Oi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Oi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=Te(t.policy,"Native snapshot policy");if(Ie(y,CS,"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=Cp({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(aE),s=t.omitted.map(oE),c=it(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:sE(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>rl||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(sl(C)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return C}async function Pp(e,t,i={}){let n=ai(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=F.resolve(e.projectRoot),a=gp(i),o=wp(i.gitSelectionLimits),s=await bp(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(Ep(s).filter(v=>Yn(e,v))),l=[...s.gitlinks].filter(v=>c.has(v)),u=[...s.nestedRepositories].filter(v=>Yn(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 zS(a,r,m),g=n.entries.filter(v=>!f(v.path)&&!p(v.path)&&Yn(e,v.path)&&(c.has(v.path)||!h.has(v.path)));await kp(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)||!Yn(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??W("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,b=Qn(b,"git-selection",{source:"git-selection",...s.overflow}));let C=v=>{k+=1,b=Qn(b,"omission",v)};for(;N.length>rl;){let v=ao(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(;sl(w)>n.limits.maxManifestBytes;){let v=ao(N);if(v===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");C(v),w=y()}return ai(w)}function lE(e,t){if(!kS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=F.join(e.changesDir,t);if(!z(e.changesDir,i))throw new Error("Native change path escaped");return F.join(i,"runtime","baseline-manifest.json")}async function Ap(e,t={}){let i={maxFiles:t.limits?.maxFiles??io.maxFiles,maxFileBytes:t.limits?.maxFileBytes??io.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??io.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??io.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=Cp(t.policy),r=gp({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=wp(t.gitSelectionLimits),o=VS(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=F.resolve(e.projectRoot),c=await X.realpath(s),l=F.resolve(e.nativeRoot),u=await X.realpath(l),d=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),p=eE(s,t.denylist??[]),m=[],h=[],g=new Map,S=new Map,N=0,k=0,b=W("comet.native.snapshot-omission-overflow.v1"),C=0,y=!1,w=null,v=x=>{k+=1,b=Qn(b,"omission",x)},E=x=>{if(N+=1,h.length<rl){h.push(x);return}if(nl(x)){let A=ao(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=Qn(b,"git-selection",{source:"git-selection",...x})},U=x=>{k+=1,b=Qn(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))},J=(x,A)=>{let T=m.findIndex(Y=>Y.path===x);if(T<0)return;let[H]=m.splice(T,1);C-=H.size,g.delete(x),E(A)},K=async(x,A,T,H)=>{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)||!z(c,Y)||Ht(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 rE(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||!Ot(T,B.finalStat)||!Ot(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",...H===void 0?{}:{gitObjectId:H}},{kind:"file",target:x,realTarget:Y,stat:j})}},Ke=async(x,A,T)=>{if(!_(r))return;let H,Y,B;try{if(H=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()||!Ot(T,B)||B.mtimeMs!==T.mtimeMs||B.ctimeMs!==T.ctimeMs||!H.equals(Y)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=H.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=oo("sha256").update("symlink\0").update(H).digest("hex");_(r)&&await q({path:A,hash:Q,size:j,type:"file"},{kind:"symlink",target:x,rawTarget:H,stat:B})},Ye=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;J(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()||!Ot(A.stat,Q)||Q.size!==A.stat.size||Q.mtimeMs!==A.stat.mtimeMs||Q.ctimeMs!==A.stat.ctimeMs)&&J(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;J(x,{path:x,size:null,type:"other",reason:ne(P)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!j.isSymbolicLink()||!Ot(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Q))&&J(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,H;try{if(T=await X.realpath(A.target),!_(r))return;H=await X.lstat(A.target)}catch{if(!_(r))return;J(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&H.isDirectory()&&!H.isSymbolicLink()&&Ot(A.stat,H)&&z(c,T)&&!Ht(u,T))){J(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let B;try{if(!_(r))return;B=await up(r,T)}catch(j){if($i(j))throw j;J(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;B.dirty?J(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):B.hash!==A.hash&&J(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"})}}},be=await bp(r,e,a,t.gitSelectionHooks);if(be===null){let x=await cp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let H of x.records){if(H.type!=="file"&&H.type!=="symlink"||g.has(H.path))continue;if(Ve(r)<1)break;if(!fp(n,H.path,r))continue;if(Ve(r)<1)break;let Y=F.resolve(s,...H.path.split("/")),B;try{B=await X.lstat(Y)}catch(j){if(!_(r))break;if(!ne(j)&&!ie(j))throw j;E({path:H.path,size:null,type:"file",reason:ie(j)?"changed-during-read":"unreadable"});continue}if(Ve(r)<1)break;if(H.type==="symlink"&&B.isSymbolicLink()){if(await Ke(Y,H.path,B),Ve(r)<1)break;continue}if(H.type!=="file"||!B.isFile()||B.isSymbolicLink()){E({path:H.path,size:B.isFile()?B.size:null,type:B.isDirectory()?"directory":B.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await K(Y,H.path,B),Ve(r)<1)break}Ve(r)>=1&&await Ye();let A=await cp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=QS(x.evidence,A.evidence);w=T.evidence;for(let H of[...x.omissions,...A.omissions,...T.omissions])h.some(Y=>Y.path===H.path&&Y.reason===H.reason)||E(H)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let x=t.incrementalBaseline,A=new Map,T=!1;if(x){let P=ai(x);for(let Z of P.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);T=A.size>0}let H=new Set,Y=!0;try{let P=await Xn(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=ro(Z),de=ee.indexOf(" "),oe=de<0?null:Hi(ee.slice(de+1));if(de!==1||oe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&H.add(oe)}}catch(P){if($i(P))throw P;T=!1,Y=!1,A.clear()}let B=new Set;try{let P=await no(r,s,["ls-files","--modified","-z"],il);for(let Z of P.toString("utf8").split("\0")){let ee=Hi(Z);ee!==null&&B.add(ee)}}catch{T=!1,Y=!1,A.clear()}let j=new Set,Q=new Set;for(let P of Ep(be)){if(g.has(P)||!Yn(e,P))continue;if(Ve(r)<1)break;if(!fp(n,P,r))continue;if(Ve(r)<1)break;let Z=F.resolve(s,...P.split("/"));if(Z===d||Z===f||p.some(ke=>Ht(ke,Z)))continue;if(be.gitlinks.has(P)){if(m.length>=i.maxFiles){E({path:P,size:0,type:"file",reason:"file-count"});continue}let ke,_r;try{[ke,_r]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(_r.isSymbolicLink()||!_r.isDirectory()||!z(c,ke)||Ht(u,ke)){E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ni=await up(r,ke);if(Ni.dirty){E({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await q({path:P,hash:Ni.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:ke,stat:_r,hash:Ni.hash})}catch(Ni){if($i(Ni))throw Ni;E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await X.lstat(Z)}catch(ke){if(ie(ke)&&be.tracked.has(P)){S.set(P,Z);continue}if(!ne(ke)&&!ie(ke))throw ke;E({path:P,size:null,type:"file",reason:ie(ke)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await Ke(Z,P,ee);continue}if(!ee.isFile()){be.nestedRepositories.has(P)||E({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let de=be.trackedObjectIds.get(P),oe=de?A.get(P):void 0;if(T&&oe?.gitObjectId!==void 0&&oe.gitObjectId===de&&!H.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 $u=Y&&!H.has(P)&&!B.has(P)?de:void 0;await K(Z,P,ee,$u),$u!==void 0&&Q.add(P)}if(await Ye(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await kp(r,e,a,be,t.gitSelectionHooks?.outputChunkBytes),j.size>0||T&&Q.size>0){let P=await no(r,s,["ls-files","--modified","-z"],il),Z=new Set;for(let ee of P.toString("utf8").split("\0")){let de=Hi(ee);de!==null&&Z.add(de)}for(let ee of j){if(!Z.has(ee))continue;let de=m.find(oe=>oe.path===ee);J(ee,{path:ee,size:de?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Q){if(!Z.has(ee))continue;let de=m.find(oe=>oe.path===ee);de&&delete de.gitObjectId}}for(let P of be.omissions)E(P);be.overflow&&I(be.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let Pg=be===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...be.evidence?{gitSelection:be.evidence}:{}},Ou=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Pg,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}}:{}}),Jo=Ou();for(;sl(Jo)>i.maxManifestBytes;){if(h.filter(A=>!nl(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let H=ao(h);if(H===null)break;v(H)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))N+=1,U(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Jo=Ou()}return Jo}async function cl(e,t,i={}){let r=(await jt(e.projectRoot))?.native.snapshot??Wc;return Ap(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 co(e,t){let i=lE(e,t);await $(e.nativeRoot,i);try{let n=await Xh({root:e.nativeRoot,file:i,maxBytes:bS,label:"Native baseline snapshot manifest"});return ai(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as RE}from"crypto";import pl from"path";var _e=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 uo,promises as he}from"node:fs";import Ee from"node:path";import{TextDecoder as bE}from"node:util";import gE from"path";var mE=Go(_a(),1);var xp=(e,t)=>{let i=e[t];return i==null?null:String(i)};function er(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 Zn(e,t){let i=er(e,t);if(gE.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 wE(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 Tp(e){if(!e.run_id)return null;let t=er(e,"run_id"),i=er(e,"skill"),n=er(e,"skill_version"),r=er(e,"skill_hash"),a=Zn(e,"pending_ref"),o=Zn(e,"trajectory_ref"),s=Zn(e,"context_ref"),c=Zn(e,"artifacts_ref"),l=Zn(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:xp(e,"current_step"),iteration:u,pending:xp(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:wE(e)}}var Cj=256*1024;var yE=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function NE(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=Tp(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function lo(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=>!yE.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 NE(t)}var ye={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function ir(e,t){let i=Ee.relative(e,t);return i===""||!Ee.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ee.sep}`)}function _p(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function tr(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 kE(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function oi(e,t,i){let n=_e[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Ee.resolve(e),a=Ee.resolve(r,...n.split("/"));if(!ir(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Ip(e){let t=await he.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await he.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ll(e,t){let i=Ee.resolve(e),n=Ee.resolve(t);if(!ir(i,n))throw new Error("Native Run path is outside its change");let r=[await Ip(i)],a=i;for(let o of Ee.relative(i,n).split(Ee.sep).filter(Boolean)){a=Ee.join(a,o);let s;try{s=await Ip(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!ir(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function fo(e){for(let t of e){let i=await he.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!kE(t,i)||await he.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function SE(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 Di(e,t,i,n,r){let a=await ll(e,Ee.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await he.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=_p(o),c=await he.realpath(t);if(!ir(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?uo.O_RDONLY:uo.O_RDONLY|uo.O_NOFOLLOW|uo.O_NONBLOCK,u;try{u=await he.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),he.lstat(t),he.realpath(t)]);if(await fo(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!tr(s,d)||!tr(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await SE(u,i,n);await r?.beforeFinalCheck?.();let[h,g,S]=await Promise.all([u.stat(),he.lstat(t),he.realpath(t)]);if(await fo(a),!g.isFile()||g.isSymbolicLink()||S!==c||!tr(s,h)||!tr(s,g))throw new Error(`${n} changed while reading`);let N;try{N=new bE("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()}}async function EE(e,t,i){let n=await ll(e,Ee.dirname(t));if(!n)return{exists:!1};let r;try{r=await he.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await he.realpath(t);if(!ir(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await fo(n),{exists:!0,identity:_p(r),realPath:a}}async function CE(e,t,i,n){let r=await ll(e,Ee.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await he.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!tr(i.identity,a)||await he.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await fo(r)}async function ul(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await EE(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ei(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await CE(e.changeDir,e.file,i,e.label)}});let n=await Di(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function jp(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Op(e){return`${JSON.stringify(e,null,2)}
|
|
152
|
-
`}function dl(e){return lo(e)}async function We(e,t){let i=oi(e,"stateRef"),n=await Di(e,i,ye.runStateBytes,"Native Run state",t);return n?lo(jp(n.text,"Native Run state")):null}async function fl(e,t,i){let n=lo(t);await ul({changeDir:e,file:oi(e,"stateRef"),content:Op(n),maxBytes:ye.runStateBytes,label:"Native Run state",hooks:i})}async function nt(e,t,i){let n=oi(e,"trajectoryRef",t),r=await Di(e,n,ye.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>ye.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ye.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 $p(e,t,i){return(await Di(e,oi(e,"trajectoryRef",t),ye.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Hp(e,t,i,n){let r=oi(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
|
|
153
|
-
`;if(Buffer.byteLength(a,"utf8")>ye.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${ye.trajectoryEventBytes} bytes`);let o=await Di(e,r,ye.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=ye.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ye.trajectoryEvents} events`);await ul({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:ye.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function ho(e,t,i){let n=await Di(e,oi(e,"checkpointRef",t),ye.checkpointBytes,"Native Run checkpoint",i);return n?jp(n.text,"Native Run checkpoint"):null}async function Fp(e,t,i,n){await ul({changeDir:e,file:oi(e,"checkpointRef",t),content:Op(i),maxBytes:ye.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var PE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ml=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function hl(e){return RE("sha256").update(e).digest("hex")}function AE(e,t){if(!PE.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=pl.join(e.changesDir,t);if(!z(e.changesDir,i))throw new Error("Native change path escaped");return pl.join(i,"runtime","trajectory.jsonl")}function xE(e){let t=e.split(/\n/u),i=0;for(let n=0;n<t.length;n+=1){let r=t[n].endsWith("\r")?t[n].slice(0,-1):t[n];if(r.length!==0){i=n+1;try{JSON.parse(r)}catch(a){return{status:"invalid",line:n+1,message:a.message}}}}return{status:"valid",count:i}}function TE(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 IE(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=xE(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:e,line:r.line,message:r.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=r.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
154
|
-
`)])}catch(d){if(!TE(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:hl(t),targetHash:hl(l),tailHash:hl(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function _E(e,t){let i=AE(e,t);await $(e.nativeRoot,i);let n=pl.join(e.changesDir,t),r=await $p(n,_e.trajectoryRef);return r===null?{status:"clean",file:i}:IE(i,Buffer.from(r))}async function vl(e,t){let i=await _E(e,t);return"inspection"in i?i.inspection:i}async function nr(e,t){let i=await vl(e,t);if(i.status!=="clean")throw new ml(i)}import{createHash as $E}from"node:crypto";import{promises as mo}from"node:fs";import Ft from"node:path";import{execFileSync as jE}from"child_process";import po from"path";function gl(e,t){return jE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function OE(e,t){let i=po.normalize(e),n=po.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Dp(e){try{let t=po.resolve(gl(e,["rev-parse","--show-toplevel"])),n=gl(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?po.resolve(n.slice(9)):t,a=null;try{a=gl(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!OE(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var rr=/^[a-f0-9]{64}$/u,HE=16*1024,wl=process.platform,FE=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Li(e){return FE.has(e)}function qp(e,t){let i=Ft.relative(e,t);return Ft.isAbsolute(i)||i===".."||i.startsWith(`..${Ft.sep}`)?null:i.replaceAll("\\","/")||"."}function Vp(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Wp(e,t){if(e.length===0||Vp(e)||e.includes("\\")||Ft.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Ft.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function yl(e,t){return $E("sha256").update(`${e}
|
|
155
|
-
${t}`).digest("hex")}async function Lp(e,t){let i=await mo.realpath(t),n=await mo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=wl==="win32"?Ft.normalize(i).toLowerCase():i;return yl(e,`${r}
|
|
156
|
-
${n.dev}
|
|
157
|
-
${n.ino}
|
|
158
|
-
${n.birthtimeMs}`)}async function Mp(e,t){let i=await mo.realpath(t),n=await mo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=wl==="win32"?Ft.normalize(i).toLowerCase():i;return yl(e,r)}function DE(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Bp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Vp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function zp(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Bp(e.changeBranch,"Native workspace change branch"),Bp(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function vo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(t).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!rr.test(String(t.projectRootId))||!rr.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");DE(t.capturedAt),Wp(t.nativeRootRef,"Native workspace root ref");let r=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!rr.test(String(t.projectRootPathId))||a&&!rr.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!rr.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(zp(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function LE(e,t){return Ft.join(e.changesDir,t,"runtime","workspace.json")}function ME(e,t){let i=qp(e.nativeRoot,LE(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Wp(i,"Native workspace file ref")}async function BE(e,t){try{let i=await ce({root:e.nativeRoot,ref:ME(e,t),maxBytes:HE});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function qE(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=qp(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([Lp("comet.native.workspace-project-root.v2",e.paths.projectRoot),Lp("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Mp("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Mp("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),o=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&zp(e.binding);let s={capturedAt:o,capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:yl("comet.native.workspace-session.v2",`${i}
|
|
159
|
-
${n}
|
|
160
|
-
${e.sessionId}`)}:{}},c=e.binding?{schema:"comet.native.workspace.v3",...s,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...s};return vo(c),c}async function Dt(e,t){let i=await BE(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(vo(i),i)}async function go(e){vo(e.identity);let t=await qE({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),wl==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}async function wo(e){if(vo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await go(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Dp(e.paths.projectRoot);return e.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!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.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 Jp(e,t){let i=await Dt(e,t);if(i===null)return null;let n=await wo({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var Lt="comet.native.v3",si="comet.native.v2",ci="comet.native.v1",li="comet.native.transition.v3",Mi="comet.native.transition.v2",ar="comet.native.transition.v1";var Up=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],VE=new Set(Up),Kp=new Set([...Up,"minimum_runtime_version","revision"]),WE=new Set([...Kp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),zE=new Set(["capability","operation","source","base_hash"]),JE=new Set(["shape","build","verify","archive"]),GE=new Set(["implicit","confirmed"]),UE=new Set(["pending","pass","fail"]),Mt="comet-state.yaml",kl=/^[a-f0-9]{64}$/u,Yp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,KE=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,or=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},ui=class extends Error{constructor(i,n){super(i!==Lt||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},sr=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},yo=class extends Error{constructor(i,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},No=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},RO=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
161
|
-
`);function lr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xp(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 dt(e){if(!Yp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function YE(e){if(!Yp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Qp(e,t){if(e.length===0||ut.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function XE(e,t){let i=lr(e,`spec_changes[${t}]`);if(Xp(i,zE,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(YE(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"&&Qp(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"||!kl.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"||!kl.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 QE(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Sl(e,t){if(Xp(e,t,Mt),typeof e.name!="string")throw new Error("Native change name is required");if(dt(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"||!JE.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&&!GE.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(XE),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"||!UE.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"&&Qp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!QE(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 ur(e){let t=lr(e,Mt);if(t.schema!==ci)throw new Error(`Expected ${ci}`);return{schema:ci,...Sl(t,VE)}}function cr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Nl(e,t,i){if(e===null)return null;let n=typeof e=="string"?KE.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 ZE(e){if(e==null)return null;if(typeof e!="string"||!kl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function eC(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 dr(e){let t=lr(e,Mt);if(t.schema!==si)throw new Error(`Expected ${si}`);if(cr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${si} minimum_runtime_version must be 2`);return{schema:si,minimum_runtime_version:2,revision:cr(t.revision,"Native v2 revision"),...Sl(t,Kp)}}function ft(e){let t=lr(e,Mt);if(t.schema!==Lt){if(t.schema===ci||t.schema===si){let o=t.schema===ci?ur(t):dr(t);throw new or(o.name,o.schema)}throw new ui(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=cr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ui(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=cr(t.revision,"Native revision"),r=Sl(t,WE),a=ZE(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Lt,minimum_runtime_version:3,revision:n,verification_protocol:eC(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Nl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Nl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Nl(t.partial_allowance,"Native partial_allowance","allowances")}}function tC(e){let t=lr(e,Mt);if(t.schema===ci){let r=ur(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Lt}`}}if(t.schema===si){let r=dr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Lt}`}}if(t.schema!==Lt){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 ui(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=cr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ui(t.schema,i).message};let n=ft(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function bl(e){let t=ft(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 O(e,t){dt(t);let i=ut.join(e.changesDir,t);if(!z(e.changesDir,i))throw new Error("Native change path escaped");return i}async function di(e,t){let i=ut.join(O(e,t),"runtime","schema-migration.json");await $(e.nativeRoot,i);try{return await Gp.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function El(e,t){let i=ut.join(O(e,t),"runtime","checkpoint-journal.json");await $(e.nativeRoot,i);try{return await Gp.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var iC=256*1024;async function Zp(e,t=ut.dirname(e)){let i=ut.relative(t,e).split(ut.sep).join("/"),n=await ce({root:t,ref:i,maxBytes:iC}),r=(0,bo.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 Cl(e,t){let i=ut.join(O(e,t),Mt);await $(e.nativeRoot,i);let n=tC(await Zp(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await di(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 nC(e,n.state),n)}async function nC(e,t){if(await co(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function me(e,t){let i=await Cl(e,t);if(i.status==="migration-required")throw new or(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new ui(i.schema,i.minimumRuntimeVersion);return await Jp(e,t),i.state}async function rC(e,t,i){let n={...t,schema:Lt,minimum_runtime_version:3,revision:i+1},r=await ap({expectedRevision:i,next:n,read:async()=>{let a=ft(await Zp(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ei(e,(0,bo.stringify)(bl(a))),equals:(a,o)=>JSON.stringify(bl(a))===JSON.stringify(bl(o)),conflict:a=>new sr(t.name,i,a)});return Object.assign(t,r),r}async function Bi(e,t,i,n){if(await zn(e.projectRoot),await di(e,t.name))throw new or(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await El(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await me(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await nr(e,t.name);let a=ut.join(O(e,t.name),Mt);return await $(e.nativeRoot,a),rC(a,t,i)}var tm=["Outcome","Scope","Non-goals","Acceptance examples"],aC=[...tm,"Constraints and invariants","Decisions","Open questions","Verification expectations"],oC=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],im={maxFileBytes:$n};function nm(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
|
|
162
|
-
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(r(),i=o[1].trim(),n=[]):i!==null&&n.push(a)}return r(),t}async function sC(e,t){let i=em.resolve(e,...t.split(/[\\/]/u));if(!z(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Rl.realpath(e),r=await Rl.realpath(i);if(!z(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Rl.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function fr(e){return{valid:e.length===0,findings:e}}async function Pl(e,t){let i=[],n;try{n=(await ce({root:e,ref:t,maxBytes:im.maxFileBytes})).text}catch(o){return fr([{code:"brief-missing",message:o.message,path:t}])}let r=nm(n);for(let o of aC)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of tm)(r.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=r.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),fr(i)}async function Al(e,t){let i=[],n;try{n=(await ce({root:e,ref:t,maxBytes:im.maxFileBytes})).text}catch(a){return fr([{code:"verification-missing",message:a.message,path:t}])}let r=nm(n);for(let a of oC)r.has(a)?(r.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return fr(i)}function Bt(e,t){return em.join(e.specsDir,t,"spec.md")}async function rm(e,t){let i=[],n=O(e,t.name);for(let r of t.spec_changes){let a=Bt(e,r.capability),o=null;try{await $(e.nativeRoot,a),o=await Kn(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(r.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${r.capability}`,path:a}),r.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${r.capability}`,path:a}),r.operation!=="create"&&o!==null&&o!==r.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${r.capability}: expected ${r.base_hash}, actual ${o}`,path:a}),r.source)try{await sC(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return fr(i)}import am from"node:path";import{createHash as cC}from"crypto";function ze(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function lC(e,t){t.has(e)&&ze("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||ze("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&ze("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ze("symbol properties are not supported"),`[${e.map(n=>xl(n,t)).join(",")}]`}finally{t.delete(e)}}function uC(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ze("only plain objects are supported"),t.has(e)&&ze("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ze("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&ze("accessor properties are not supported"),`${JSON.stringify(o)}:${xl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function xl(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||ze("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?lC(e,t):uC(e,t);case"bigint":case"function":case"symbol":case"undefined":return ze(`${typeof e} values are not supported`)}return ze("unsupported value type")}function hr(e){return xl(e,new Set)}function D(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return cC("sha256").update(`${e}
|
|
163
|
-
${hr(t)}`).digest("hex")}var dC="comet.native.acceptance.v1",fC=/^acceptance-[a-f0-9]{64}$/u,hC=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),pC=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,mC=/^[a-f0-9]{64}$/u,vC=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function gC(e,t){return e<t?-1:e>t?1:0}var ht=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),pr=Object.freeze({maxCriteria:1024}),om="<!-- comet-native:acceptance-evidence:start -->",sm="<!-- comet-native:acceptance-evidence:end -->";function cm(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",n=0;for(let r of e){let a=Buffer.byteLength(r,"utf8");if(n+a>t)break;i+=r,n+=a}return{value:i,truncated:!0}}function lm(e,t){let i=t.toString(36),n=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function wC(e){if(!mC.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=vC.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function yC(e,t){let i=cm(e.text,ht.maxTextBytes),n=e.context.slice(0,ht.maxContextItems).map(r=>cm(r,ht.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:n.map(r=>r.value),text:i.value,contextTruncated:e.context.length>n.length||n.some(r=>r.truncated),textTruncated:i.truncated,verificationStatus:t}}function dm(e){let t=wC({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(gC),r=n.slice(0,ht.maxFailedCheckIds),a=e.criteria.slice(t,t+ht.maxItems);for(let c of a){let l=[...i,yC(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:u<e.criteria.length?lm(e.acceptanceHash,u):null,limits:{...ht}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ht.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:o<e.criteria.length?lm(e.acceptanceHash,o):null,limits:{...ht}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>ht.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function _l(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Tl(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let n=i[1][0];return t===null?{marker:n,length:i[1].length}:n===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function um(e){return e.includes("-->")||e.includes("--!>")}function*qi(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
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=jr(e),r=gt(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=jr(e),r=gt(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())}}};Yl.Parser=uo});var tu=g(di=>{"use strict";var Xl=Xa(),vv=ii(),ui=ai(),gv=Kn(),wv=P(),yv=lo(),Ql=fo();function Zl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new yv.LineCounter||null,prettyErrors:e}}function Nv(t,e={}){let{lineCounter:i,prettyErrors:r}=Zl(e),n=new Ql.Parser(i?.addNewLine),a=new Xl.Composer(e),o=Array.from(a.compose(n.parse(t)));if(r&&i)for(let s of o)s.errors.forEach(ui.prettifyError(t,i)),s.warnings.forEach(ui.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function eu(t,e={}){let{lineCounter:i,prettyErrors:r}=Zl(e),n=new Ql.Parser(i?.addNewLine),a=new Xl.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 ui.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(ui.prettifyError(t,i)),o.warnings.forEach(ui.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=eu(t,i);if(!n)return null;if(n.warnings.forEach(a=>gv.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 kv(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 wv.isDocument(t)&&!r?t.toString(i):new vv.Document(t,r,i).toString(i)}di.parse=bv;di.parseAllDocuments=Nv;di.parseDocument=eu;di.stringify=kv});var wt=g(x=>{"use strict";var Sv=Xa(),Ev=ii(),Pv=Ta(),ho=ai(),xv=Mt(),Fe=P(),Cv=He(),Rv=I(),Av=Be(),_v=Le(),Tv=Tr(),Iv=so(),jv=lo(),$v=fo(),Or=tu(),iu=Ht();x.Composer=Sv.Composer;x.Document=Ev.Document;x.Schema=Pv.Schema;x.YAMLError=ho.YAMLError;x.YAMLParseError=ho.YAMLParseError;x.YAMLWarning=ho.YAMLWarning;x.Alias=xv.Alias;x.isAlias=Fe.isAlias;x.isCollection=Fe.isCollection;x.isDocument=Fe.isDocument;x.isMap=Fe.isMap;x.isNode=Fe.isNode;x.isPair=Fe.isPair;x.isScalar=Fe.isScalar;x.isSeq=Fe.isSeq;x.Pair=Cv.Pair;x.Scalar=Rv.Scalar;x.YAMLMap=Av.YAMLMap;x.YAMLSeq=_v.YAMLSeq;x.CST=Tv;x.Lexer=Iv.Lexer;x.LineCounter=jv.LineCounter;x.Parser=$v.Parser;x.parse=Or.parse;x.parseAllDocuments=Or.parseAllDocuments;x.parseDocument=Or.parseDocument;x.stringify=Or.stringify;x.visit=iu.visit;x.visitAsync=iu.visitAsync});function ds(t,e){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(t.status==="await-user")return t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...i,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:r("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...i,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:r("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...i,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:r("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...i,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:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(t.status==="blocked"){let n=t.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?["comet","native","next",t.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(t.phase==="shape")return{...i,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:r("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(e.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=e.children.some(({status:o})=>o==="blocked"),a=e.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action: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:r("builder-handoff")}}if(t.phase==="verify"){let n=t.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration: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:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as Ly}from"node:crypto";import{promises as Ii}from"node:fs";import My from"node:path";import{execFileSync as zd}from"child_process";import Oi from"path";function An(t,e){return zd("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Jd(t,e){let i=Oi.normalize(t),r=Oi.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ke(t){try{let e=Oi.resolve(An(t,["rev-parse","--show-toplevel"])),r=An(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Oi.resolve(r.slice(9)):e,a=null;try{a=An(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Jd(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}import{randomUUID as Gd}from"crypto";import{promises as L}from"fs";import ie from"path";function Te(t){return t!==0&&t!==0n&&t!=="0"}function G(t,e){return Te(t.dev)&&Te(e.dev)&&Te(t.ino)&&Te(e.ino)}function A(t,e){let i=Te(t.dev)&&Te(e.dev);if(i&&t.dev!==e.dev)return!1;let r=Te(t.ino)&&Te(e.ino);return r&&t.ino!==e.ino?!1:i&&r?!0:t.birthtime===e.birthtime}function Tn(t,e){let i=ie.relative(t,e);return i===""||!ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ie.sep}`)}function Ud(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function _n(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return G(i,r)?A(i,r):A(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function fs(t){let e=await L.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 L.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function $t(t){for(let e of t){let i=await L.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ud(e,i)||await L.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function Kd(t,e){let i=ie.resolve(t),r=ie.resolve(e);if(!Tn(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await fs(i)],a=ie.relative(i,r).split(ie.sep).filter(Boolean),o=i;for(let s of a){await $t(n),o=ie.join(o,s);try{await L.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await fs(o);if(!Tn(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await $t(n),n}async function Yd(t){let e;try{e=await L.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 Xd(t,e,i={}){let r=ie.dirname(t),n=i.containedRoot?await Kd(i.containedRoot,r):null;n||await L.mkdir(r,{recursive:!0});let a=ie.join(r,`.${ie.basename(t)}.${Gd()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await L.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([L.lstat(a),L.realpath(a)]);if(await $t(n),!c.isFile()||c.isSymbolicLink()||!_n(s,c)||!Tn(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(),!_n(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 $t(n);let c=await L.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!_n(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await L.link(a,t),await L.unlink(a)):await L.rename(a,t),await Yd(r)}catch(c){if(await o?.close(),!n)await L.rm(a,{force:!0});else try{await $t(n),await L.rm(a,{force:!0})}catch{}throw c}}async function de(t,e,i={}){await Xd(t,e,i)}async function Y(t,e,i={}){await de(t,JSON.stringify(e,null,2)+`
|
|
143
|
+
`,i)}import{createHash as tf}from"node:crypto";import{promises as re}from"node:fs";import X from"node:path";import{TextDecoder as rf}from"node:util";var Qd=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Zd=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function ef(t){return t.toLowerCase().startsWith(".env")}function Ot(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>ef(r))?"environment-file":i.some(r=>Zd.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Qd.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var Di=1024*1024;function In(t,e){let i=X.relative(t,e);return i===""||!X.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${X.sep}`)}function nf(t){let e=X.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})||X.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=Ot(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 af(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function of(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Hi(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return G(i,r)?A(i,r):A(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function hs(t){let e=await re.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await re.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function sf(t,e){let i=X.resolve(t),r=X.resolve(e);if(!In(i,r))throw new Error("Native artifact path is outside its root");let n=[await hs(i)],a=i;for(let o of X.relative(i,r).split(X.sep).filter(Boolean)){a=X.join(a,o);let s=await hs(a);if(!In(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ps(t){for(let e of t){let i=await re.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!of(e,i)||await re.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=nf(t.ref),i=t.maxBytes===null?null:af(t.maxBytes??Di),r=X.resolve(t.root,...e.split("/")),n=await sf(t.root,X.dirname(r));await t.hooks?.afterParentChainCaptured?.();let a=await re.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 re.realpath(r);if(!In(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await re.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),re.lstat(r),re.realpath(r)]);if(await ps(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Hi(a,c)||!Hi(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let b=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,b),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),re.lstat(r),re.realpath(r)]);if(await ps(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Hi(c,v)||!Hi(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,u),y;try{y=new rf("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:b})}return{ref:e,size:u,hash:t.includeHash===!1?null:tf("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var es=jt(wt(),1);import _t from"path";var mo=jt(wt(),1);import Hr from"path";var fi=64*1024,Dr=1024,Br=64,vo=5,Ov=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Hv=["**/.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"],Dv=[...Ov,...Hv].sort((t,e)=>t.localeCompare(e,"en"));var U={include:["**/*"],exclude:[...Dv],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Bv(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Hr.posix.isAbsolute(i)||Hr.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 Qe(t){let e=Bv(t,"native.artifact_root");return e.length===0?".":e.join("/")}function nu(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 Lr(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||Hr.posix.isAbsolute(r)||Hr.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 yt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function au(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 go(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>Dr)throw new Error(`${e} exceeds ${Dr} 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>Br)throw new Error(`${e} contains more than ${Br} wildcard tokens`);return t}function ru(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=>go(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function po(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 Lv(t){if(t===void 0)return{...U,include:[...U.include],exclude:[...U.exclude]};let e=yt(t,"native.snapshot");return{include:ru(e.include,"native.snapshot.include",U.include),exclude:ru(e.exclude,"native.snapshot.exclude",U.exclude),max_files:po(e.max_files,U.max_files,"native.snapshot.max_files"),max_total_bytes:po(e.max_total_bytes,U.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:po(e.max_duration_ms,U.max_duration_ms,"native.snapshot.max_duration_ms")}}function Mv(t){if(t===void 0)return;let e=yt(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=yt(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:Qe(r),toArtifactRoot:Qe(n),stage:a,...o?{cleanup:o}:{}}}function Fv(t,e={}){let i=yt(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??vo;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Mv(i.pending_root_move);return{artifact_root:Qe(r),language:au(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Lv(i.snapshot),...s?{pending_root_move:s}:{}}}function Vv(t){let e=yt(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:nu(e.artifact_layout),language:au(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function qv(t){let i=yt(t,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Lr(r,`hook.allow_paths[${n}]`)))]}}function Wv(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function zv(t,e,i,r,n,a){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.allowPartialProject&&!o)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 c=t.workflows??[t.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:l,ambient_resume:n,...e?{hook:e}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function hi(t,e={}){let i=(0,mo.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=Wv(n.ambient_resume),o=n.hook===void 0?void 0:qv(n.hook),s=n.native===void 0?void 0:Fv(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),c=n.classic===void 0?void 0:Vv(n.classic),l=zv(n,o,s,c,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function Mr(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Qe(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:vo,snapshot:{...U,include:[...U.include],exclude:[...U.exclude]}}}}import{createHash as Gv}from"crypto";import{promises as qr}from"fs";import Ve from"path";import{constants as Fr,promises as Ze}from"fs";var oe=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}};function wo(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function ou(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function pi(t){return{dev:t.dev,ino:t.ino,birthtime:wo(t)}}function Vr(t,e){let i=pi(t),r=pi(e);return G(i,r)?A(i,r):A(i,r)&&wo(t)===wo(e)&&ou(t)===ou(e)&&t.size===e.size}async function Nt(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 Ze.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new oe("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new oe("too-large",`${r} exceeds ${e} bytes`);let o=await Ze.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:pi(a)});let s=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,c;try{c=await Ze.open(t,s)}catch(l){throw l.code==="ELOOP"?new oe("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Ze.lstat(t,{bigint:n}),Ze.realpath(t)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!Vr(a,l)||!Vr(a,f))throw new oe("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:pi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-p,{bytesRead:b}=await c.read(v,0,Math.min(v.length,y),null);if(b===0)break;if(p+=b,p>e)throw new oe("too-large",`${r} exceeds ${e} bytes`);u.push(Buffer.from(v.subarray(0,b)))}await i.hooks?.beforeFinalCheck?.();let[h,m,w]=await Promise.all([c.stat({bigint:n}),Ze.lstat(t,{bigint:n}),Ze.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Vr(a,h)||!Vr(a,m))throw new oe("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:pi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:w}}finally{await c.close()}}function Jv(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function yo(t,e){let i=Ve.relative(t,e);return i===""||!Ve.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ve.sep}`)}async function su(t,e){let i=Ve.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 cu(t,e,i,r){let n=t;for(let a=0;a<i.length;a++){n=Ve.join(n,i[a]);let o;try{o=await qr.lstat(n)}catch(f){if(Jv(f))return{exists:!1,kind:"missing"};throw f}let s=Ve.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(!yo(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 bt(t,e,i){let r=Lr(e,i.label),n=Ve.resolve(t),a=await su(n,i.label),o=r.split("/"),s=Ve.resolve(n,...o);if(!yo(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await cu(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function qe(t,e,i,r){let n=await bt(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 su(n.projectRoot,r.label);return Nt(n.target,i,{...r,verify:async(o,s)=>{if(!yo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await cu(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var mi=".comet/config.yaml";function Uv(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Wr(t,e={}){return(await zr(t,e)).document}async function Kv(t){try{return(await qe(t,mi,fi,{label:mi})).bytes}catch(e){if(Uv(e))return null;throw e}}function Yv(t){return t?{exists:!0,sha256:Gv("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function zr(t,e={}){let i=await Kv(t);return{document:i?hi(i.toString("utf8"),e):null,identity:Yv(i)}}async function No(t){return(await Wr(t))?.config??null}var $k=16*1024;import{existsSync as uu,promises as et}from"fs";import C from"path";import tg from"os";var Jr=".comet/config.yaml",ig=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function So(t){try{return await et.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function rg(t){try{let e=await et.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function St(t,e){let i=C.relative(t,e);return i===""||!C.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${C.sep}`)}async function kt(t){let e=[],i=t;for(;!await So(i);){let n=C.dirname(i);if(n===i)break;e.push(C.basename(i)),i=n}let r=await et.realpath(i);return C.resolve(r,...e.reverse())}async function Eo(t){try{return(await et.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Gr(t){let e=C.resolve(t);try{(await et.stat(e)).isDirectory()||(e=C.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=C.resolve(tg.homedir());for(;;){if(!(e===r&&i!==r)){let o=C.join(e,...Jr.split("/")),s=e===i||await rg(o);if(await So(o)&&s)return e}if(await So(C.join(e,".git")))return e;let a=C.dirname(e);if(a===e)return i;e=a}}function Ur(t){return Qe(t)}async function ng(t,e){let i=Ur(e),r=C.resolve(t,...i.split("/")),n=await et.realpath(t),a=await kt(r);if(!St(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Et(t,e){let i=Ur(e),r=await ng(t,i),n=C.join(r,"comet");if(await Eo(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([kt(r),kt(n)]);if(!St(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=C.resolve(t),c=C.join(s,".comet","runtime","native");if(await Eo(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([et.realpath(s),kt(c)]);if(!St(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:C.join(t,...Jr.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:C.join(n,"specs"),changesDir:C.join(n,"changes"),archiveDir:C.join(n,"archive"),runtimeDir:c,changesRuntimeDir:C.join(c,"changes"),locksDir:C.join(c,"locks"),transactionsDir:C.join(c,"transactions")}}function du(t){if(!ig.test(t))throw new Error(`Invalid Native change name: ${t}`)}function tt(t,e){du(e);let i=C.join(t.changesRuntimeDir,e);if(!F(t.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Po(t,e){du(e);let i=C.join(t.changesDir,e,"runtime");if(!F(t.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function pe(t,e){let i=tt(t,e);if(uu(i))return i;let r=Po(t,e);return uu(r)?r:i}function me(t,e){let i=C.resolve(e);if(F(t.runtimeDir,i))return t.runtimeDir;if(F(t.nativeRoot,i))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function F(t,e){return St(C.resolve(t),C.resolve(e))}async function T(t,e){let i=C.resolve(t),r=C.resolve(e);if(!St(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await Eo(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([kt(i),kt(r)]);if(!St(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return r}function og(t="docs",e="en"){return Mr(t,e)}async function Pe(t){let e=(await Wr(t))?.config??null;return e?.native?e:null}async function Kr(t){let e=await Pe(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 fu(t){let e=await Gr(t.startPath),i=await Pe(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Jr} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=t.explicitArtifactRoot?Ur(t.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??og(r??"docs"),a=await Et(e,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Dw}from"fs";import Bw from"path";import{AsyncLocalStorage as sg}from"async_hooks";import{randomUUID as mu}from"crypto";import{promises as Z}from"fs";import vu from"os";import V from"path";var hu=16*1024,gu=".coordinator",cg=5e3,pu=new sg,Yr=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 ug(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 wu(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 xo(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return G(i,r)?A(i,r):A(i,r)&&t.size===e.size}function Co(t,e){return xo(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function xe(t){let e,i;try{let r=await Nt(t,hu,{bigint:!0,label:"Native lock"});e=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof oe?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${hu} 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:ug(JSON.parse(e.toString("utf8")),t),identity:wu(i)}}async function dg(t){return(await xe(t))?.owner??null}function yu(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==vu.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 fg(t,e){try{await Z.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Z.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function Ro(t,e){let i=await xe(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Co(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await Z.mkdir(e,{recursive:!0});let r=V.join(e,`${V.basename(t.file)}.${t.owner.id}.${mu()}.removed`);try{await Z.rename(t.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await xe(r);if(!n||n.owner.id!==t.owner.id||!xo(n.identity,t.identity))throw await fg(r,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await Z.rm(r,{force:!0}),"removed"}function Nu(t){return{id:mu(),pid:process.pid,hostname:vu.hostname(),createdAt:new Date().toISOString(),operation:t}}async function bu(t,e){let i;try{i=await Z.open(t,"wx")}catch(r){if(r.code==="EEXIST"){let n=await dg(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)+`
|
|
144
|
+
`,"utf8"),await i.sync(),wu(await i.stat({bigint:!0}))}finally{await i.close()}}async function hg(t,e){let i=await T(t.runtimeDir,t.locksDir);await Z.mkdir(i,{recursive:!0});let r=await T(t.runtimeDir,V.join(i,gu));await Z.mkdir(r,{recursive:!0});let n=Nu(e),a=V.join(r,`.${n.id}.tmp`),o=V.join(r,`${n.id}.claim`);try{let s=await bu(a,n);await Z.rename(a,o);let c=await xe(o);if(!c||!xo(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 Z.rm(a,{force:!0})}}async function pg(t){let e=V.dirname(t.file),i=!1,r=V.basename(t.file);for(let n of await Z.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=V.join(e,n.name);if(V.resolve(a)!==V.resolve(t.file))try{let o=await xe(a),s=yu(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ro(o,e);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function ku(t){let e=await xe(t.file);if(e){if(e.owner.id!==t.owner.id||!Co(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Ro(e,V.dirname(t.file))}}async function mg(t,e){let i=Date.now()+cg;for(;;){let r=await hg(t,e);if(!await pg(r))return r;if(await ku(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 vg(t){let e=Yr.get(t)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=e.then(()=>r);return Yr.set(t,n),await e,()=>{i(),Yr.get(t)===n&&Yr.delete(t)}}async function Su(t,e,i){let r=V.resolve(t.locksDir),n=pu.getStore();if(n?.has(r))return i();let a=await vg(r);try{let o=await mg(t,e),s=new Map(n??[]);return s.set(r,o),await pu.run(s,async()=>{try{return await i()}finally{await ku(o)}})}finally{a()}}async function Xr(t,e,i){return Su(t,`acquire ${e}`,async()=>{let r=await T(t.runtimeDir,t.locksDir);await Z.mkdir(r,{recursive:!0});let n=await T(t.runtimeDir,V.join(r,lg(e))),a=Nu(i),o=await bu(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Qr(t){await xe(t.file)&&await Su({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${V.basename(t.file)}`,async()=>{let e=await xe(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Co(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=V.join(t.locksDir,gu);await Ro(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 Eu(t){return yu(await xe(t))}import qo from"node:path";import Yg from"node:path";import xu from"node:path";import{createHash as wg}from"crypto";function se(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function yg(t,e){e.has(t)&&se("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)||se("sparse arrays are not supported");return(i.length!==t.length||i.some((r,n)=>r!==String(n)))&&se("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&se("symbol properties are not supported"),`[${t.map(r=>Ao(r,e)).join(",")}]`}finally{e.delete(t)}}function Ng(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&se("only plain objects are supported"),e.has(t)&&se("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&se("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))&&se("accessor properties are not supported"),`${JSON.stringify(o)}:${Ao(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Ao(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)||se("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?yg(t,e):Ng(t,e);case"bigint":case"function":case"symbol":case"undefined":return se(`${typeof t} values are not supported`)}return se("unsupported value type")}function _o(t){return Ao(t,new Set)}function K(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 wg("sha256").update(`${t}
|
|
145
|
+
${_o(e)}`).digest("hex")}var bg="comet.native.acceptance.v1";var hS=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),yi=Object.freeze({maxCriteria:1024});function Io(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function To(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let r=i[1][0];return e===null?{marker:r,length:i[1].length}:r===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function Pu(t){return t.includes("-->")||t.includes("--!>")}function*gi(t){let e=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
|
|
164
146
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
165
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:
|
|
166
|
-
`))),"Brief")}function
|
|
167
|
-
`),a.context)),a=null}};for(let{line:s,body:c}of qi(e)){let l=c?_l(s):null,u=l?/^Scenario\s*:\s*(.*)$/iu.exec(l.text):null;if(u){for(o();r.at(-1)&&r.at(-1).level>=l.level;)r.pop();let d=Il(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:d,body:[],context:r.map(f=>f.text)}}else if(l){for(a!==null&&l.level<=a.level?o():a!==null&&a.body.push(s);r.at(-1)&&r.at(-1).level>=l.level;)r.pop();r.push(l)}else a!==null&&c&&a.body.push(s)}return o(),Ol(n,"Specification")}function pm(e,t="spec.md",i=pr.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],r=[],a=null,o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(jl("spec-must",t,o.parts.join(" "),o.context)),o=null}},c=()=>r.some(l=>/^(?:non-?goals?|非目标)$/iu.test(l.text.trim()));for(let{line:l,body:u}of qi(e)){let d=u?_l(l):null;if(d){for(s(),a!==null&&d.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=d.level;)r.pop();r.push(d),/^Scenario\s*:/iu.test(d.text)&&(a=d.level);continue}let f=l.trim();if(!u||a!==null||c()){s();continue}if(f.length===0||Tl(l,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){s();continue}let p=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(p){s(),o={parts:[p[1]],context:r.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(f)){s(),o={parts:[f],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[f],context:r.map(m=>m.text)}:o.parts.push(f)}return s(),Ol(n,"Specification mandatory requirements")}function SC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||bC(i)||am.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let n=am.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!pC.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function EC(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,n=Object.keys(i).filter(r=>!hC.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function mm(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,n)=>{let r=EC(i,n),a=r.acceptance_id;if(typeof a!="string"||!fC.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return SC(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=r.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(r,"skipped_reason")){if(typeof r.skipped_reason!="string"||r.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=r.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function vm(e){let t=NC(e);if(t.some(({line:l,body:u})=>!u&&(l===om||l===sm)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===om?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===sm?[d]:[]);if(n.length!==1||r.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(n[0]>=r[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(n[0]+1,r[0]).map(({line:l})=>l).join(`
|
|
168
|
-
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=mm(o),c=CC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function CC(e){let t=mm([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,n)=>i.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(t,null,2)}import gm from"node:path";var RC="comet.native.contract.v1",PC="comet.native.acceptance-set.v1",wm=/^[a-f0-9]{64}$/u,mr={maxAcceptanceCriteria:pr.maxCriteria};function ym(e,t){let i=gm.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})||gm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Nm(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
169
|
-
`))}function AC(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(wm))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(wm))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=ym(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Nm(e.markdown)},markdown:e.markdown}}function xC(e,t){return bm(e.id,t.id)}function bm(e,t){return e<t?-1:e>t?1:0}function km(e){let t=ym(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(AC).sort((d,f)=>bm(d.snapshot.capability,f.snapshot.capability)),n=i.map(({snapshot:d})=>d.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=fm(e.briefMarkdown,t,mr.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...hm(f,d.source,mr.maxAcceptanceCriteria-a.length)),a.push(...pm(f,d.source,mr.maxAcceptanceCriteria-a.length)));if(a.sort(xC),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>mr.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${mr.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Nm(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(PC,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(RC,u)}}var fi={maxSpecs:64,maxFileBytes:$n,maxTotalBytes:4*1024*1024};async function Vi(e){if(e.specChanges.length>fi.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ce({root:e.changeDir,ref:e.briefRef,maxBytes:fi.maxFileBytes}),i=t.size,n=[];for(let r of e.specChanges){if(r.operation==="remove"){n.push({capability:r.capability,operation:"remove",source:null,baseHash:r.base_hash,markdown:null});continue}if(!r.source)throw new Error(`Native contract ${r.capability} has no proposed spec source`);let a=await ce({root:e.changeDir,ref:r.source,maxBytes:fi.maxFileBytes});if(i+=a.size,i>fi.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");n.push({capability:r.capability,operation:r.operation,source:a.ref,baseHash:r.base_hash,markdown:a.text})}return{contract:km({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import TC from"path";var $l="comet.selection.v2",IC=16*1024;function Em(e){return TC.join(e,".comet","current-change.json")}function _C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Sm(e){return e===null||typeof e=="string"}function jC(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!_C(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Sm(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:$l,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==$l)throw new Error(`current change selection schema must be ${$l}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Sm(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Cm(e){let t;try{let n=Em(e),{bytes:r}=await ni(n,IC,{label:"current change selection"});t=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...jC(t)}}var n0=16*1024;async function Rm(e){let t=await Cm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(dt(t.selection.change),t.selection)}import OC from"path";function Hl(e,t){return OC.resolve(e,...t.split(/[\\/]/u))}async function Pm(e,t){let i=[],n=O(e,t.name),r=Hl(n,_e.stateRef),a;try{a=await We(n)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:r}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:r}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:r}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:r}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:r}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:r});let o=Hl(n,a.trajectoryRef),s=await vl(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await nt(n,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Hl(n,a.checkpointRef);try{let u=await ho(n,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import{randomUUID as TR}from"crypto";import{promises as IR}from"fs";import _R from"path";import{isDeepStrictEqual as nu}from"util";var $C=/\b(Bearer|Basic)\s+[^\s"']+/giu,HC=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,FC=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,DC=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,LC=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,MC=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,BC=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Ce(e){return e.replace($C,"$1 [REDACTED]").replace(HC,"[REDACTED PRIVATE KEY]").replace(FC,"$1[REDACTED]@").replace(DC,"[REDACTED TOKEN]").replace(LC,'$1"[REDACTED]"').replace(MC,"$1$2$1$3$4[REDACTED]$4").replace(BC,"$1$2[REDACTED]")}var Wi={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var qC=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function VC(e,t){return e<t?-1:e>t?1:0}function WC(e,t,i,n){if(!Array.isArray(e)||e.length>i||!n&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let r=e.map(a=>{if(typeof a!="string"||!qC.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(VC)}function Fl(e=[]){return WC(e,"Native repair failed check IDs",Wi.maxFailedCheckIds,!0)}function Am(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function zC(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Am(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Am(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Dl(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(zC(n,a))break;i+=1,n=a}return i}import Wm from"node:path";import{createHash as $m}from"node:crypto";import xm from"path";var Ll="comet.native.implementation-scope.v2",Hm="comet.native.content-snapshot-projection.v1",vr="comet.native.content-snapshot-projection.v1",Fm="comet.native.implementation-scope.v2",JC="comet.native.unresolved-scope-id.v1",GC="comet.native.scope-detail-overflow.v1",UC="comet.native.snapshot-projection-overflow.v2",Vl=/^[a-f0-9]{64}$/u,pi=1024*1024,KC=128,YC=128;function ue(e,t){return e<t?-1:e>t?1:0}function Ml(e){if(!Vl.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function XC(e,t){return e===t?0:e===null?-1:t===null?1:ue(e,t)}function Vt(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=xm.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||xm.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Dm(e,t){return e==="."?e:Vt(e,t)}function zi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function QC(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Vt(e.path,`${t} path`),hash:e.hash,size:zi(e.size,`${t} size`),type:"file"}}function ZC(e,t){return{path:Dm(e.path,`${t} path`),size:e.size===null?null:zi(e.size,`${t} size`),type:e.type,reason:e.reason}}function eR(e,t){return ue(e.path,t.path)||ue(e.hash,t.hash)||e.size-t.size}function tR(e,t){return ue(e.path,t.path)||ue(e.reason,t.reason)||ue(e.type,t.type)||(e.size??-1)-(t.size??-1)}function gr(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
170
|
-
`,"
|
|
171
|
-
${
|
|
172
|
-
`)
|
|
173
|
-
`);let i=0;Lm(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){qt(t,"change",r);let a=0;for(let o of e.declaredArtifacts)Co(o,r.path)&&(a+=1,qt(t,"change-attribution",o));qt(t,"change-end",{attributionCount:a}),a===0&&qt(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&&qt(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function qm(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=sR(e,t,r,i.gitChangedPaths),s=D(vr,e),c=D(vr,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let v of w.omitted){if(l.length>=YC)break;l.push(pt({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=[...Im("baseline",e),...Im("current",t),...o.totalChanges===0&&a===null?[pt({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(Ye=>Ye.attributedTo.length===0),E=o.totalChanges-w.length,I=o.totalUnattributed-v.length,U=u-y.detailedOmissionCount,q=I+U,J=[...v.map(Ye=>pt({kind:"unattributed-change",source:"implementation-scope",path:Ye.path,evidence:{after:Ye.after,before:Ye.before,changeKind:Ye.kind}},`Changed path is not covered by a declared artifact: ${Ye.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||q>0?[Bm(y.overflowHash,{changes:E,unattributed:I,unresolved:q})]:[]],K=aR(J),Ke=y.includeGitAdvisory?f():void 0;return{schema:Ll,contractHash:n,baselineProjectionRef:Ml(s),baselineProjectionHash:s,currentProjectionRef:Ml(c),currentProjectionHash:c,complete:K.length===0,declaredArtifacts:r,changes:w,unattributed:v,unresolvedScopes:K,noCodeReason:a,...Ke?{gitAdvisory:Ke}:{}}},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(gr({...y,scopeHash:S})<=pi)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?lR({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(Fm,b)};if(gr(C)>pi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return C}function Wl(e){let t=Bl(e.baseline),i=Bl(e.current),n=Mm(e);return{authority:n,baseline:t,current:i,scope:qm(t,i,n)}}var uR=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function mt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vt(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 hi(e,t){if(typeof e!="string"||!Vl.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _m(e,t,i){let n=Ml(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function So(e,t){let i=mt(e,"Native snapshot projection");if(vt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Hm)throw new Error("Native snapshot projection schema is invalid");let n=ai({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=Bl(n);if(D(vr,i)!==D(vr,r))throw new Error("Native snapshot projection is not canonical");let a=D(vr,r);if(t!==void 0&&hi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function zl(e,t){let i=mt(e,`Declared artifact ${t}`);if(vt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Vt(i.path,`Declared artifact ${t} path`),kind:i.kind}}function jm(e,t){if(e===null)return null;let i=mt(e,t);return vt(i,["hash","size"],[],t),{hash:hi(i.hash,`${t} hash`),size:zi(i.size,`${t} size`)}}function Om(e,t){let i=mt(e,`Implementation change ${t}`);if(vt(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(zl),r=Eo(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=jm(i.before,`Implementation change ${t} before`),o=jm(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:Vt(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function dR(e,t){let i=mt(e,`Unresolved scope ${t}`);vt(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"?Dm(i.path,`Unresolved scope ${t} path`):Vt(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function ko(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)=>Vt(r,`${t} ${a}`)),n=[...new Set(i)].sort(ue);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function Ro(e){let t=mt(e,"Native implementation scope"),i=[...uR].filter(w=>w!=="gitAdvisory");if(vt(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==Ll)throw new Error("Native implementation scope schema is invalid");let n=hi(t.contractHash,"Implementation scope contractHash"),r=hi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=_m(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=hi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=_m(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(zl);if(JSON.stringify(c)!==JSON.stringify(Eo(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Om),u=[...l].sort((w,v)=>ue(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=>Co(v,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Om),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(dR),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:cR(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=>pt({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?[pt({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(ql))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(N.sort(ql))||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=mt(t.gitAdvisory,"Implementation scope Git advisory");if(vt(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=ko(w.changedPaths,"Git changed paths"),E=ko(w.pathsPresentInSnapshotChanges,"Git present paths"),I=ko(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),U=[...E,...I].sort(ue),q=new Set(l.map(J=>J.path));if(JSON.stringify(U)!==JSON.stringify(v)||(g?.changes??0)===0&&E.some(J=>!q.has(J))||I.some(J=>q.has(J)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:v,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:I}}let C={schema:Ll,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=hi(t.scopeHash,"Implementation scope scopeHash");if(D(Fm,C)!==y)throw new Error("Implementation scope content hash mismatch");return{...C,scopeHash:y}}function fR(e){let t=mt(e,"Native implementation scope authority");if(vt(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(zl);if(JSON.stringify(i)!==JSON.stringify(Eo(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=ko(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Mm({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 wr(e){let t=mt(e,"Native implementation scope bundle");vt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=fR(t.authority),n=So(t.baseline),r=So(t.current),a=Ro(t.scope),o=qm(n,r,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:n,current:r,scope:o}}function Vm(e){let t=Ro(e.scope);return wr({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 Jm=/^[a-f0-9]{64}$/u;var hR="comet.native.acceptance-trace.v2",pR="comet.native.partial-allowance.v1",mR="comet.native.verification-evidence.v2";function gt(e,t){if(!Jm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Gm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Um(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 Jl(e,t,i=2e3){let n=Ce(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function yr(e,t){let i=Wm.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})||Wm.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 vR(e,t,i){let n=yr(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=Ze(n),a=n.toLowerCase(),o=i?yr(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 Gl(e){let t=yr(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 Ji(e,t){return e<t?-1:e>t?1:0}function Po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ao(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Km(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 zm(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 gR(e){let t=Po(e,"Native acceptance trace");if(Ao(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Jm.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=yr(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=Po(o,`Native acceptance trace entry ${s}`);if(Ao(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(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=>Gl(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ji))||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:yr(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Jl(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>Ji(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=gt(t.traceHash,"Native acceptance trace hash");if(D(hR,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Ym(e){let t=Po(e,"Native partial allowance");if(Ao(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Ji))||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:Um(t.change),scopeHash:gt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Jl(t.reason,"Partial allowance reason"),confirmedSummary:Jl(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Gm(t.sourceRevision),confirmedAt:Km(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=gt(t.allowanceHash,"Native partial allowance hash");if(D(pR,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Ul(e){let t=Po(e,"Native verification evidence");if(Ao(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=gt(t.implementationScopeHash,"Native verification implementation scope hash"),n=gR(t.acceptanceTrace),r=gt(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:gt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Gl(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ji)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(Ji);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=>Gl(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ji)))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:Um(t.change),sourceRevision:Gm(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:gt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:zm(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:vR(t.reportRef,"Native verification report ref"),reportHash:gt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:zm(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Km(t.createdAt,"Native verification timestamp")},d=gt(t.envelopeHash,"Native verification envelope hash");if(D(mR,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Nr(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 Xm="repairStagnation",Re={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},yR=/^[a-f0-9]{64}$/u;var NR=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),bR=["data","runId","sequence","timestamp","type"],Qm=["disposition","overrideSummaryHash","signatureHash"],kR=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Zm=12;function Yl(e,t){return e<t?-1:e>t?1:0}function ev(e,t,i){let n=Object.keys(e).sort(Yl);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function xo(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 br(e,t){if(typeof e!="string"||!yR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function SR(e){if(!Array.isArray(e)||e.length>Wi.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Yl)}function tv(e){if(typeof e!="string"||e.length===0||e.length>Re.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 Kl(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Re.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Re.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>Re.maxTextCharacters&&(!r||e.length>Re.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Re.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>Re.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Kl(s,t+1,i,`${n}[${c}]`));return}let a=xo(e,n),o=Object.keys(a);if(o.length>Re.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Re.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Re.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Kl(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function ER(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 CR(e,t,i){let n=xo(e,`Native repair trajectory event ${t+1}`);if(ev(n,bR,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(ER(n.timestamp),typeof n.type!="string"||!NR.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(tv(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 Kl(n.data,0,r,"Native trajectory event data"),xo(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Xl(e){let t=xo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Yl),n=i.length===Qm.length&&i.every((l,u)=>l===Qm[u]);n||ev(t,kR,"Native repair trajectory projection");let r=br(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:br(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=br(t.contractHash,"Native repair trajectory contract hash"),s=SR(t.failedAcceptanceIds),c=Fl(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 RR(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 PR(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??Zm;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Dl({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<Wi.warningAtConsecutiveFailures?"continue":a<Wi.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function AR(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??Zm;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 iv(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Re.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=tv(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=CR(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Re.maxTotalDataNodes||c>Re.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?br(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?br(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Xm)){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=Xl(f[Xm]);if(RR(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),PR(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");AR(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>Wi.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function nv(e){return iv(e).history}function rv(e){let t=iv(e).latestProjection;return t?{...t}:null}var Gi={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=W("comet-native-runtime:v3:semantic-repair-budget"),xR=[{skillVersion:"2",skillHash:W("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:W("comet-native-runtime:v1")}];function av(e){return e.skillVersion===Gi.definition.metadata.version&&e.skillHash===Ql||xR.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}async function To(e){let i={sequence:(await nt(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Hp(e.changeDir,e.run.trajectoryRef,i),i}async function Zl(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:W(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Fp(e.changeDir,e.run.checkpointRef,t),t}function ov(e){return W(JSON.stringify({summary:e.summary,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var pv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],jR=new Set(pv),mv=new Set([...pv,"minimum_runtime_version","revision"]),OR=new Set([...mv,"operation"]),$R=512*1024,eu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),HR=new Set([...eu,"implementationScopeHash","repairScopeHash","repairStagnation"]),tu=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function kr(e,t){return _R.join(O(e,t),"runtime","transition.json")}function FR(e){return`transition-${e}`}async function DR(e,t,i){let n=FR(t);return Jn(e,n,i)}async function Ki(e,t,i,n){let r=await DR(e,t,i);try{return await n()}finally{await Gn(r)}}function _o(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function ru(e,t){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Io(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rt(e,t){return nu(e,t)}function iu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,n=Object.keys(i),r=n.find(u=>!HR.has(u)),a=[...eu].find(u=>!Object.hasOwn(i,u)),o=eu.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0);if(r||a||n.length!==o)throw new Error(`Native transition journal event data keys are invalid${r?`: ${r}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(Nr(i.summary,"Native transition journal event summary"),Ce(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Nr(i.noCodeReason,"Native transition journal event no-code reason"),Ce(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Xl(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 LR(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,n=Object.keys(i),r=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===r.size&&n.every(a=>r.has(a))&&i.reason==="spec-rebase")return iu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return iu(e,t)}function au(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?LR(e.eventData,e.evidenceHash):iu(e.eventData,e.evidenceHash),r=dl(e.nextRun),a=e.previousRun===null?null:dl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function sv(e,t,i=!1){if(e.skill!==Gi.definition.metadata.name||(i?!av(e):e.skillVersion!==Gi.definition.metadata.version||e.skillHash!==Ql)||e.orchestration!==Gi.definition.orchestration.mode||e.pendingRef!==_e.pendingRef||e.trajectoryRef!==_e.trajectoryRef||e.contextRef!==_e.contextRef||e.artifactsRef!==_e.artifactsRef||e.checkpointRef!==_e.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function cv(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 lv(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function ou(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(sv(a,"next Run",n||r!==null),lv(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(sv(r,"previous Run",!0),lv(r,"previous Run"),e.run_id!==r.runId||r.currentStep!==e.phase||t.run_id!==r.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==r.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!nu(cv(r),cv(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function MR(e,t,i){return W(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function vv(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function uv(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function su(e,t,i,n,r=!1){let a=i.eventData,o=uv(e),s=uv(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&nu(e.spec_changes,t.spec_changes),l=ov({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=MR(e.name,a.summary,t.spec_changes),l=W(`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 gv(e,t){let i=_o(e);if(ru(i,OR),i.schema!==li)throw new Error(`Expected Native transition schema ${li}`);let n=Io(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 ${li} minimum_runtime_version must be ${3}`);let r=Io(i.revision,"Native transition revision");if(r!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat")throw new Error("Native transition journal operation is invalid");let a=au(i,t),o=ft(i.previousState),s=ft(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(su(o,s,a,i.operation),ou(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:li,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 BR(e,t){let i=_o(e);if(ru(i,jR),i.schema!==ar)throw new Error(`Expected Native transition schema ${ar}`);let n=au(i,t,!0),r=ur(i.previousState),a=ur(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return su(r,a,n,vv(r,a,n.eventData),!0),ou(r,a,n,!0),{schema:ar,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 qR(e,t){let i=_o(e);if(ru(i,mv),i.schema!==Mi)throw new Error(`Expected Native transition schema ${Mi}`);if(Io(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Mi} minimum_runtime_version must be 2`);let r=Io(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=au(i,t,!0),o=dr(i.previousState),s=dr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(su(o,s,a,vv(o,s,a.eventData),!0),ou(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Mi,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 VR(e,t){let i=_o(e);if(i.schema===li)return{status:"current",journal:gv(i,t)};if(i.schema===ar)return{status:"migration-required",journal:BR(i,t)};if(i.schema===Mi)return{status:"migration-required",journal:qR(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function WR(e,t){let i=kr(e,t);await $(e.nativeRoot,i);try{let n=await tt({root:e.nativeRoot,file:i,maxBytes:$R,label:`Native transition journal ${t}`});return VR(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ui(e,t){let i=await WR(e,t);if(!i)return null;if(i.status==="migration-required")throw new tu(t);return i.journal}async function wv(e){if(await di(e.paths,e.nextState.name))throw new Error(`Native schema migration is incomplete for ${e.nextState.name}; run doctor --repair`);await nr(e.paths,e.nextState.name);let t={schema:li,minimum_runtime_version:3,revision:1,operation:e.operation??"advance",id:e.transitionId?.()??TR(),change:e.nextState.name,evidenceHash:e.evidenceHash,createdAt:(e.now??new Date).toISOString(),previousState:e.previousState,nextState:e.nextState,previousRun:e.previousRun,nextRun:e.nextRun,eventData:e.eventData},i=gv(t,t.change),n=kr(e.paths,i.change);if(await $(e.paths.nativeRoot,n),await Ui(e.paths,i.change))throw new Error(`Native transition recovery is already pending for ${i.change}`);return await Le(n,i),i}function dv(e,t){if(rt(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(rt(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function fv(e,t){if(rt(e,t.nextState))return"next";if(rt(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function zR(e){let{journal:t}=e;return yv({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function yv(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function hv(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(t.previousRun===null?1:0)||r.length>1||t.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=zR({sequence:a.index+1,journal:t,type:a.event.type});if(!rt(yv(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function Sr(e,t,i){if(await di(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await nr(e,t);let n=await Ui(e,t);if(!n)return null;let r=O(e,t),a=hv(await nt(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([We(r),me(e,t)]),c=dv(o,n),l=fv(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await fl(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!rt(await We(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let g=await Bi(e,n.nextState,n.previousState.revision);if(!rt(g,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!rt(await me(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await Ui(e,t);if(!u||!rt(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=hv(await nt(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await To({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let f=d.transitioned;f||(f=await To({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Zl({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([We(r),me(e,t)]);dv(p,{...n,previousRun:n.nextRun}),fv(m,{...n,previousState:n.nextState});let h=await Ui(e,t);if(!h||!rt(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await IR.rm(kr(e,t),{force:!0}),n.nextState}var JR=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function GR(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 Nv(e){let i=(e.findings??[]).filter(u=>!Li(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||JR.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:GR(e.state)}}import Er from"path";var bv=8,UR={"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 KR(e){let t=UR[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"}:Li(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 YR(e,t,i){if(!i.path)return null;let n;if(Er.isAbsolute(i.path)?n=Er.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=Er.resolve(O(e,t.name),...i.path.split(/[\\/]/u)):n=Er.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!z(e.projectRoot,n))return null;let r=Er.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function XR(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 kv(e){return e.findings.map(t=>{let i=KR(t.code);return{code:t.code,message:t.message,severity:i.severity,path:YR(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:XR(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 Sv(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,bv),truncated:t.length>bv}}import Av from"path";import Yi from"path";var zt={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Xi=/^[a-f0-9]{64}$/u;function jo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Oo(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,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 Ev(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function cu(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||Yi.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Yi.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function lu(e,t){return Yi.join(O(e,t),"runtime","checkpoints","progress.json")}function Qi(e,t){return Yi.join(O(e,t),"runtime","checkpoint-journal.json")}function uu(e,t,i){if(!Xi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Yi.join(O(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function ZR(e){if(!Xi.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function du(e,t,i){let n=await tt({root:e,file:t,maxBytes:zt.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function eP(e,t){let i=jo(e,`checkpoint manifest artifact ${t}`);Oo(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=QR(Wt(i.path,`checkpoint artifact ${t} path`,4096)),r=Ze(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Xi.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:cu(i.size,`checkpoint artifact ${t} size`)}}function $o(e,t){let i=jo(e,"Native checkpoint manifest");if(Oo(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>zt.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(eP),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=cu(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>zt.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 fu(e){return W(JSON.stringify($o(e,e.change)))}function hu(e,t){let i=jo(e,"Native progress checkpoint");if(Oo(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=Ev(i.previousRevision,"Native checkpoint previousRevision"),a=Ev(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Wt(i.manifestHash,"Native checkpoint manifestHash",64);if(!Xi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=ZR(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Wt(i.inputHash,"Native checkpoint inputHash",64);if(!Xi.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Wt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=cu(i.artifactCount,"Native checkpoint artifactCount");if(u>zt.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Wt(i.summary,"Native checkpoint summary"),f=Wt(i.nextAction,"Native checkpoint nextAction");if(Ce(d)!==d||Ce(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Wt(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 tP(e,t){let i=jo(e,"Native checkpoint journal");if(Oo(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=ft(i.previousState),r=ft(i.nextState),a=hu(i.checkpoint,t),o=$o(i.manifest,t),s=Wt(i.inputHash,"Native checkpoint journal inputHash",64),c=W(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Xi.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!==fu(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 iP(e,t,i){let n=Yi.resolve(e.projectRoot,...t.split("/"));if(!z(e.projectRoot,n)||z(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=xc(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await tt({root:e.projectRoot,file:n,maxBytes:zt.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 nP(e,t){let i=lu(e,t);await $(e.nativeRoot,i);try{return hu(await du(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function pu(e,t,i){let n=uu(e,t,i);await $(e.nativeRoot,n);let r=await du(e.nativeRoot,n,"Native checkpoint manifest"),a=$o(r,t);if(mu(e,a),fu(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Ho(e,t){let i=Qi(e,t);await $(e.nativeRoot,i);try{let n=tP(await du(e.nativeRoot,i,"Native checkpoint journal"),t);return mu(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Cv(e,t,i,n){let r=$o(i,t);mu(e,r);let a=fu(r),o=uu(e,t,a);await $(e.nativeRoot,o);try{let s=await pu(e,t,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await Le(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function mu(e,t){for(let i of t.artifacts){let n=xc(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Rv(e,t){let i=hu(t,t.change),n=await pu(e,i.change,i.manifestHash),r=W(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=lu(e,t.change);await $(e.nativeRoot,a),await Le(a,i,{containedRoot:e.nativeRoot})}async function Pv(e){let t;try{t=await nP(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:lu(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 pu(e.paths,e.name,t.manifestHash);let a=W(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 iP(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:uu(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}var xv=240,Tv=8,Fo=50;function Iv(e){let t=Array.from(e);return t.length<=xv?e:`${t.slice(0,xv-1).join("")}…`}function rP(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function aP(e){let t=[...new Set(e.map(rP))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Tv),reasonCount:e.length,codesTruncated:t.length>Tv};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Fo),reasonsTruncated:e.length>Fo}}}async function _v(e){let t=null;try{let s=await Ho(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Qi(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:Qi(e.paths,e.state.name)}}let i=await Pv({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=aP(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:zt.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Iv(i.checkpoint.summary),nextAction:Iv(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:Av.relative(e.paths.projectRoot,Av.join(O(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:zt.maxArtifacts}}import{promises as WA}from"node:fs";import fg from"node:path";import jv from"node:path";var oP="comet.native.archive-preflight.v1",sP="comet.native.archive-preflight.v1",cP="comet.native.archive-operation.v1",lP=/^[a-f0-9]{64}$/u,Ov=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Do(e,t){return e<t?-1:e>t?1:0}function dP(e,t){if(typeof e!="string"||!lP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function wt(e,t){return e===null?null:dP(e,t)}function fP(e,t){let i=jv.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||jv.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 hP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function pP(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 mP(e,t){if(!Ov.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=wt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=wt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=wt(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 vP(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:wt(e.contractHash,"Native archive contract hash"),acceptanceHash:wt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:wt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:wt(e.reportHash,"Native archive report hash"),envelopeHash:wt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:wt(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 gP(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!uP.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(Do);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function wP(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(Do)}function $v(e){if(!Ov.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(mP).sort((l,u)=>Do(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(cP,l)})),n=vP(e.evidence),r=pP(e.workspace),a=[...new Set([...gP(e.findingCodes??[]),...wP({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(Do),o=hP(e.revision),s=fP(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:oP,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(sP,c)}}import{createHash as yP}from"node:crypto";import Hv from"node:path";var NP="comet.native.conflict-radar.v1",Ne=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}),bP="comet.native.conflict-radar.v1",kP="comet.native.conflict-radar-signals.v1",SP=/^[a-f0-9]{64}$/u,Lv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EP=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),CP=new Set(["capability","operation","baseHash"]),RP=new Set(["path","kind"]);function Zi(e,t){return e<t?-1:e>t?1:0}function vu(e){return Buffer.byteLength(e,"utf8")}function gu(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 wu(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(vu(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function PP(e,t){let i=wu(e,t,Ne.maxArtifactPathBytes),n=Hv.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)||Hv.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 Mv(e,t){if(typeof e!="string"||!SP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function AP(e,t){let i=gu(e,CP,t),n=wu(i.capability,`${t} capability`,Ne.maxCapabilityBytes);if(!Lv.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:Mv(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 xP(e,t){let i=gu(e,RP,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:PP(i.path,`${t} path`),kind:i.kind}}function TP(e,t){let i=gu(e,EP,`Conflict radar change ${t}`),n=wu(i.name,`Conflict radar change ${t} name`,Ne.maxNameBytes);if(!Lv.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>Ne.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>Ne.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>AP(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>Zi(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)=>xP(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>Zi(c.path,l.path)||Zi(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:Mv(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function IP(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ne.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(TP).sort((r,a)=>Zi(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)>Ne.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>Ne.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function _P(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 jP(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 OP(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function $P(e,t){let i=[],n=yP("sha256").update(`${kP}
|
|
174
|
-
[`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(hr(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ne.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(_P(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=jP(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:OP(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function Fv(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function HP(e,t){return Fv(e.classification)-Fv(t.classification)||Zi(e.left,t.left)||Zi(e.right,t.right)}function Dv(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:NP,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 Bv(e){let t=IP(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push($P(t[s],t[c]));i.sort(HP);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(bP,{changes:t,relationships:n}),a=i.slice(0,Ne.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Dv(t,i,a,r);for(;a.length>0&&vu(JSON.stringify(o))>Ne.maxSerializedBytes;)a=a.slice(0,-1),o=Dv(t,i,a,r);if(vu(JSON.stringify(o))>Ne.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as pA}from"node:crypto";import{promises as Ge}from"node:fs";import at from"node:path";import qv from"node:path";var Vv="comet.native.check-receipt.v1",FP="comet.native.check-receipt.v1",en="scoped-text-safety",yu=1,je=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),DP=/^[a-f0-9]{64}$/u,LP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MP="comet.native.checker-policy.v1",BP="comet.native.check-input.v1",qP=2048,Wv=D(MP,{policy:en,version:yu,limits:je,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),VP=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),zv=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Gv=["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"],WP=new Set(Gv);function vi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gi(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 yt(e,t){if(typeof e!="string"||!DP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Uv(e,t){let i=mi(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Jv(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 zP(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>qP||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=qv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||qv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function JP(e){let t=vi(e,"Native check receipt checker");gi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=vi(t.limits,"Native check receipt limits");if(gi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==en||t.version!==yu||t.hash!==Wv||i.maxFiles!==je.maxFiles||i.maxFileBytes!==je.maxFileBytes||i.maxTotalBytes!==je.maxTotalBytes||i.maxIssues!==je.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:en,version:yu,hash:Wv,limits:{...je}}}function GP(e){let t=vi(e,"Native check receipt contract");return gi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:yt(t.expectedHash,"Native check expected contract hash"),beforeHash:yt(t.beforeHash,"Native check before contract hash"),afterHash:yt(t.afterHash,"Native check after contract hash")}}function UP(e){let t=vi(e,"Native check receipt implementation");return gi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:yt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:yt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:yt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:yt(t.afterSnapshotHash,"Native check after snapshot hash")}}function KP(e){let t=vi(e,"Native check receipt counts");gi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:mi(t.filesSelected,"Native check filesSelected"),filesScanned:mi(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:mi(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:mi(t.bytesScanned,"Native check bytesScanned"),issueCount:mi(t.issueCount,"Native check issueCount"),recordedIssueCount:mi(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>je.maxFiles||i.bytesScanned>je.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>je.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function YP(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||zv.indexOf(e.kind)-zv.indexOf(t.kind)}function XP(e){if(!Array.isArray(e)||e.length>je.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=vi(n,`Native check issue ${r}`);if(gi(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!VP.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:zP(a.path,`Native check issue ${r} path`),line:Uv(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(YP);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function QP(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!WP.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Gv.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 ZP(e){return D(BP,e)}function Kv(e){let t=vi(e,"Native check receipt");if(gi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Vv)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!LP.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Uv(t.sourceRevision,"Native check source revision"),n=JP(t.checker),r=GP(t.contract),a=UP(t.implementation),o=ZP({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(yt(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=Jv(t.startedAt,"Native check receipt startedAt"),c=Jv(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=KP(t.counts),u=XP(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=QP(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>je.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>je.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:Vv,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=yt(t.receiptHash,"Native check receipt content hash");if(D(FP,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var bu="comet.native.verification-receipt.v3",eA=bu,tA="comet.native.declared-artifacts.v1",iA=/^[a-f0-9]{64}$/u,nA=/^acceptance-[a-f0-9]{64}$/u,rA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,oA=4096,sA=256,cA=1024;function tn(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 Jt(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 Nt(e,t){if(typeof e!="string"||!iA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Je(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Ce(e).trim();if(!i||i.length>oA||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Nu(e,t){let i=Je(e,t),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Cr(e,t,i=Je,n=!1,r=sA){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 lA(e,t){if(typeof e!="string"||!nA.test(e))throw new Error(`${t} is invalid`);return e}function uA(e){let t=tn(e,"Native verification receipt bindings");if(Jt(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!rA.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:Nt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Nt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Nt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Nt(t.artifactHash,"Native verification receipt artifact hash")}}function dA(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=aA.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function fA(e,t,i,n){let r=tn(t,`Native ${e} evidence`);if(e==="automated-check"){if(Jt(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=Nu(r.startedAt,"Native automated-check start time"),o=Nu(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=tn(r.worktree,"Native automated-check worktree");if(Jt(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=tn(r.afterFence,"Native automated-check after fence");if(Jt(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:Je(r.executable,"Native automated-check executable"),args:Cr(r.args,"Native automated-check arguments",Je,!0),cwd:Je(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:Je(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Nt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Nt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Nt(r.outputHash,"Native automated-check output hash"),outputSummary:Je(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){Jt(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=dA(r.checkReceiptRef);if(Nt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Cr(r.subjects,"Native static inspection subjects",Je,n==="required-check"),rule:Je(r.rule,"Native static inspection rule"),resultSummary:Je(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Jt(r,["steps","observations"],"Native manual-evidence evidence"),{steps:Cr(r.steps,"Native manual evidence steps"),observations:Cr(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function hA(e){let t=tn(e,"Native verification receipt");if(Jt(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=Je(t.actor,"Native verification receipt actor"),o=Cr(t.acceptanceIds,"Native receipt acceptance IDs",lA,n==="required-check",cA).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:bu,kind:i,role:n,status:r,bindings:uA(t.bindings),acceptanceIds:o,actor:a,issuedAt:Nu(t.issuedAt,"Native verification receipt issue time"),evidence:fA(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==en||s.actor!==`native-runtime:${en}`))throw new Error("Native required check policy identity is invalid");return s}function Yv(e){let t=tn(e,"Native verification receipt");if(Jt(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==bu)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=hA(n),a=Nt(t.receiptHash,"Native verification receipt hash");if(D(eA,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function ku(e){return D(tA,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var eg=/^[a-f0-9]{64}$/u,nn=pi,tH=3*nn;function Su(e,t){let i=at.relative(e,t);return i===""||!at.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${at.sep}`)}function mA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Lo(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 Xv(e){let t=await Ge.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Ge.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function vA(e,t){let i=at.resolve(e),n=at.resolve(t);if(!Su(i,n))throw new Error("Native evidence path is outside its change");let r=[await Xv(i)],a=i;for(let o of at.relative(i,n).split(at.sep).filter(Boolean)){a=at.join(a,o);let s=await Xv(a);if(!Su(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Qv(e){for(let t of e){let i=await Ge.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!mA(t,i)||await Ge.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function gA(e,t,i={}){let n=await vA(t,at.dirname(e));await i.afterParentChainCaptured?.();let r=await Ge.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Ge.realpath(e);if(!Su(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Ge.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Ge.lstat(e),Ge.realpath(e)]);if(await Qv(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Lo(s,r)||!Lo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>nn)throw new Error(`Native evidence document exceeds ${nn} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let g=nn+1-d,S=await o.read(f,0,Math.min(f.length,g),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>nn)throw new Error(`Native evidence document exceeds ${nn} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Ge.lstat(e),Ge.realpath(e)]);if(await Qv(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Lo(s,p)||!Lo(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 tg(e,t){if(!eg.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function wA(e,t,i,n,r){if(!eg.test(i))throw new Error("Native report evidence hash is invalid");let a=await wi({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"||pA("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 rn(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 yA(e,t,i,n,r){return at.join(r??O(e,t),...tg(i,n).split("/"))}async function wi(e){let t=e.changeDir??O(e.paths,e.name),i=yA(e.paths,e.name,e.kind,e.hash,t);return await $(e.paths.nativeRoot,i),gA(i,t,e.hooks)}function Zv(e,t){return So(e,t)}function NA(e,t){let i=Ro(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function bA(e,t,i){let n=Ym(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function kA(e,t,i){let n=Ul(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function SA(e,t,i,n=!1,r){let a=await Eu(e,t,i.implementationScopeRef,void 0,r);if(n&&await wA(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 ig(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 Rr(e,t,i,n,r){let a=rn(i,"scopes"),o=NA(await wi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=rn(o.baselineProjectionRef,"snapshots"),c=rn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([wi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>Zv(d,s)),wi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>Zv(d,c))]);return Vm({baseline:l,current:u,scope:o})}async function Eu(e,t,i,n,r){return(await Rr(e,t,i,n,r)).scope}async function ig(e,t,i,n,r){let a=rn(i,"allowances");return bA(await wi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function Mo(e,t,i,n,r){let a=rn(i,"receipts"),o=Yv(await wi({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 Pr(e,t,i,n,r){let a=rn(i,"verifications"),o=kA(await wi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await SA(e,t,o,!1,r),o}var EA=4096;async function CA(e,t=Ne.maxChanges){try{let i=await Un({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 ng(e,t){let i=await me(e,t),[n,r]=await Promise.all([i.implementation_scope?Eu(e,t,i.implementation_scope):null,Dt(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 Bo(e,t,i={}){let r=(await CA(e,EA)).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 ng(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await ng(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Bv([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 $A,spawn as OH}from"node:child_process";import{promisify as HA}from"node:util";import{promises as RA}from"fs";async function rg(e,t,i){let n=await Ho(e,t);if(!n)return null;if(await Cv(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Bi(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await Rv(e,n.checkpoint),await i?.afterProgressWritten?.(n),await RA.rm(Qi(e,t),{force:!0}),n}async function Ar(e,t){await Sr(e,t),await rg(e,t)}import{constants as Cu,promises as Oe}from"node:fs";import yi from"node:path";var PA=/^[a-f0-9]{64}$/u,AA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,xr=512*1024;function xA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qo(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 TA(e,t){let i=yi.resolve(e),n=yi.resolve(t);if(!z(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...yi.relative(i,n).split(yi.sep).filter(Boolean)]){o&&(a=yi.join(a,o));let s=await Oe.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Oe.realpath(a);if(r.length>0&&!z(r[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return r}async function ag(e){for(let t of e){let i=await Oe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xA(t,i)||await Oe.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function IA(e){if(!PA.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function _A(e){let t=AA.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function jA(e,t,i){return yi.join(O(e,t),...IA(i).split("/"))}async function OA(e,t,i){let n=await TA(i,yi.dirname(e)),r=await Oe.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>xr)throw new Error(`Native check receipt exceeds ${xr} bytes`);let[a,o]=await Promise.all([Oe.realpath(t),Oe.realpath(e)]);if(!z(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Cu.O_RDONLY|Cu.O_NOFOLLOW|Cu.O_NONBLOCK,c=await Oe.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(),Oe.lstat(e),Oe.realpath(e)]);if(await ag(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!qo(r,l)||!qo(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=xr+1-p,k=await c.read(m,0,Math.min(m.length,N),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>xr)throw new Error(`Native check receipt exceeds ${xr} bytes`);f.push(Buffer.from(m.subarray(0,k.bytesRead)))}let[h,g,S]=await Promise.all([c.stat(),Oe.lstat(e),Oe.realpath(e)]);if(await ag(n),!g.isFile()||g.isSymbolicLink()||S!==o||!z(a,S)||!qo(l,h)||!qo(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 og(e,t,i){let n=_A(i),r=O(e,t),a=jA(e,t,n);await $(e.nativeRoot,a);let o=Kv(await OA(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var Tr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var KH=64*1024;var YH=3600*1e3;var XH=HA($A);var QH=["$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 FA=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function sg(e,t){let i=[];for(let n of FA){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 cg(e){if(e.receipt.kind!=="static-inspection")return null;let t=await og(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 Gt=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 DA(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 LA(e){let t=DA(e.bundle.baseline),i=await cl(e.paths,t,{origin:"explicit",now:e.now});return Wl({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function ug(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Rr(e.paths,e.state.name,e.state.implementation_scope),i=await Vi({changeDir:O(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await LA({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 dg(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await ug(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 MA(e){let t=await ce({root:O(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:vm(t.text)}}function BA(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 qA(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:ku(e.implementationScope.scope.declaredArtifacts)}}async function lg(e){let t=await Mo(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=sg(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 Gt([{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 cg({paths:e.paths,state:e.state,receipt:t});if(r){let a=BA({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 VA(e){let t=qA({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await lg({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Gt)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 lg({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Gt)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 Gt(i)}function Ru(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Pu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Ru(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([ug(e),Pr(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:Ru(e.state.verification_result,"stale"),envelope:null};let n=await MA({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 VA({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:Ru(e.state.verification_result,"invalid"),envelope:null}}}function zA(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function hg(e){try{return await WA.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function JA(e,t){try{return(await ce({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function GA(e,t,i){let n=Bt(e,i.capability);if(!z(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=fg.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await JA(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ce({root:O(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 UA(e,t){return hg(kr(e,t))}async function Au(e){let t=e.now??new Date,i=await me(e.paths,e.name),n=await Dt(e.paths,e.name),r=await jt(e.paths.projectRoot),a=zA(i.name,t),o=fg.resolve(e.paths.nativeRoot,...a.split("/"));if(!z(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=>GA(e.paths,i.name,m))),Pu({paths:e.paths,state:i,now:t}),Bo(e.paths,i.name),di(e.paths,i.name),El(e.paths,i.name),UA(e.paths,i.name),hg(o)]);return $v({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 KA(e,t){let i=O(e,t.name),n=await We(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 ho(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 nt(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function YA(e,t){let i=await KA(e,t);return{committed:i,latest:rv(i),history:nv(i)}}async function pg(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await YA(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 aF=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function XA(e){return(await Rm(e))?.change??null}function QA(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 ZA(e,t){let i=O(e,t.name),n=[...(await Pl(i,t.brief)).findings,...(await rm(e,t)).findings,...await Pm(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await co(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 Pp(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 Vi({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 Ui(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 Al(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 xu(e,t,i){let n=await XA(e)===t,r;try{let w=await Cl(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 _v({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await pg(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 Vi({changeDir:O(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 Pr(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=dm({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 Bo(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 Dt(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let v=await wo({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 go({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 dg({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 Au({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 ZA(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=kv({paths:e,state:r,findings:h}),S=g.filter(w=>!Li(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:QA(r,N,k,i?.clarificationMode),archiveReady:N,inspection:a.inspection,findingSummary:Sv(g),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:Nv({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:Fo,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{promises as mg}from"fs";import vg from"path";var gg=fi.maxSpecs*4;async function Tu(e){try{return await Kn(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function wg(e,t){let i=vg.join(O(e,t),"specs"),n;try{n=await Qa({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await mg.opendir(i);try{for await(let s of o){if(a+=1,a>gg)throw new Error(`Native proposed specs directory exceeds ${gg} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;dt(s.name);let c=vg.join(i,s.name,"spec.md");await $(e.nativeRoot,c);let l;try{l=await mg.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>fi.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function ex(e,t){let i=await wg(e,t.name),n=[];for(let r of i){if(t.spec_changes.find(c=>c.capability===r)?.operation==="remove")throw new Error(`Capability ${r} has both a proposed spec and a remove intent`);let o=Bt(e,r);await $(e.nativeRoot,o);let s=await Tu(o);n.push({capability:r,operation:s===null?"create":"replace",source:`specs/${r}/spec.md`,base_hash:s})}for(let r of t.spec_changes){if(r.operation!=="remove"||i.includes(r.capability))continue;let a=Bt(e,r.capability);await $(e.nativeRoot,a);let o=await Tu(a);o!==null&&n.push({...r,base_hash:o})}return n.sort((r,a)=>r.capability.localeCompare(a.capability))}async function yg(e){dt(e.name);let t=Ce(e.summary);return Nr(t,"Spec rebase summary"),qe(e.paths,`rebase specs for ${e.name}`,()=>Ki(e.paths,e.name,`rebase specs for ${e.name}`,async()=>{await Ar(e.paths,e.name);let i=await me(e.paths,e.name);if(i.phase==="shape")throw new Error("Shape spec metadata is refreshed by the next command");if(i.archived)throw new Error(`Native change ${i.name} is already archived`);let n=O(e.paths,e.name),r=await We(n);if(!r||r.runId!==i.run_id||r.currentStep!==i.phase||r.pending)throw new Error(`Native Run state is missing or inconsistent for ${i.name}`);let a=await ex(e.paths,i),o={...i,revision:i.revision+1,phase:"build",spec_changes:a,verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},s={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},c=W(JSON.stringify({operation:"spec-rebase",change:i.name,summary:t,specChanges:a}));await wv({paths:e.paths,previousState:i,nextState:o,previousRun:r,nextRun:s,evidenceHash:c,eventData:{previousPhase:i.phase,nextPhase:"build",evidenceHash:c,summary:t,artifacts:[],noCodeReason:null,verificationResult:null},operation:"spec-rebase",now:e.now,transitionId:e.transitionId});let l=await Sr(e.paths,e.name);if(!l)throw new Error("Native spec rebase journal disappeared before completion");return l}))}async function Ng(e,t,i){return dt(t),dt(i),qe(e,`remove spec ${i} from ${t}`,()=>Ki(e,t,`remove spec ${i} from ${t}`,async()=>(await Ar(e,t),tx(e,t,i))))}async function tx(e,t,i){let n=await me(e,t);if(n.phase==="archive"||n.archived)throw new Error(`Native change ${t} no longer accepts spec changes`);if((await wg(e,t)).includes(i))throw new Error(`Capability ${i} has both a proposed spec and a remove intent`);if(n.spec_changes.find(l=>l.capability===i)?.operation==="remove")return n;let o=Bt(e,i);await $(e.nativeRoot,o);let s=await Tu(o);if(s===null)throw new Error(`Canonical spec is missing: ${i}`);let c={...n,spec_changes:[...n.spec_changes.filter(l=>l.capability!==i),{capability:i,operation:"remove",base_hash:s}].sort((l,u)=>l.capability.localeCompare(u.capability))};return await Bi(e,c,n.revision),c}import rx from"path";var OF={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var VF=16*1024*1024,WF=256*1024,zF=16*1024;var xD=16*1024*1024,Vo=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"},Wo=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 LD=10*1024*1024,Ue=class extends Error{};function bg(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new Ue(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function zo(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Ue(`${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 Ue(`${t} requires a value`);return e.splice(n,2),r}function Iu(e){if(e.length>0)throw new Ue(`Unexpected argument: ${e[0]}`)}function Ir(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new Ue(`${t} is required`);return i}async function kg(e){return e?rx.resolve(e):za(process.cwd())}async function _u(e){let t=await Fh({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ju(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
175
|
-
`}}function
|
|
176
|
-
`}:e.
|
|
177
|
-
`)
|
|
178
|
-
`)}
|
|
179
|
-
`}}async function
|
|
147
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&r===null,index:s},s+=1,e!==null)e=To(l,e);else if(i)Pu(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=To(l,null);if(d!==null)e=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!Pu(u))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);p&&n.has(p[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(u)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function wi(t){return t.normalize("NFC").replace(/\s+/gu," ").trim()}function jo(t,e,i,r=[],n="content-hash"){let a=wi(i),o=e.replaceAll("\\","/").trim(),s=r.map(wi);if(a.length===0)throw new Error(`${t} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${t} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${K(bg,{kind:t,source:o,context:s,text:a})}`:"",kind:t,source:o,context:s,text:a}}function $o(t,e,i="content-hash"){let r=new Set;for(let n of t){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${e} contains duplicate acceptance criteria`);r.add(a)}return t}function kg(t){let e=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of gi(t)){n=s+1;let c=o?Io(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(e=s+1)):e!==null&&i===null&&(i=s))}if(r===0||e===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:e,end:i??n}}function Oo(t,e="brief.md",i=yi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=kg(t);if(n===null)return[];let a=null;for(let{line:l,body:f,index:d}of gi(t)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let p=u[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:d}of gi(t)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),$o(o.map(l=>jo("brief-example",e,l.join(`
|
|
148
|
+
`),[],r)),"Brief",r)}function Ho(t,e="spec.md",i=yi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(jo("spec-scenario",e,[o.title,...o.body].join(`
|
|
149
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of gi(t)){let f=l?Io(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=wi(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),$o(n,"Specification",r)}function Do(t,e="spec.md",i=yi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(jo("spec-must",e,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(f=>/^(?:non-?goals?|非目标)$/iu.test(f.text.trim()));for(let{line:f,body:d}of gi(t)){let u=d?Io(f):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=f.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||To(f,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(f);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),$o(n,"Specification mandatory requirements",r)}var Sg=/^A[1-9]\d*$/u;function Cu(t,e){if(t.length===0||t!==t.trim()||t.includes("\\")||xu.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||xu.posix.normalize(t)!==t||t==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized change-relative ref`);return t}function Eg(t,e){return t.localeCompare(e,"en")}function Bo(t){let e=Cu(t.briefSource??"brief.md","Native brief source"),i=[...t.specs??[]].sort((a,o)=>Eg(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=Oo(t.briefMarkdown,e,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Cu(a.source,`Native spec source for ${a.capability}`);r.push(...Ho(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Do(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=wi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Ru(t){let e=t.map(({id:i})=>i);if(new Set(e).size!==e.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<e.length;i+=1)if(!Sg.test(e[i])||e[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}var tn=jt(wt(),1);import{promises as Pg}from"node:fs";var Pt="comet.native.v4",Ni="comet.native.local-execution.v4";function Lo(){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 xg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Cg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Rg=/^A[1-9][0-9]*$/u,Ag=/^[a-f0-9]{64}$/u,_g=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),en=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function z(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 B(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 Mo(t,e){return t===null?null:B(t,e)}function Tg(t,e){let i=B(t,e);if(!Ag.test(i))throw new Error(`${e} must be a SHA-256 hash`);return i}function xt(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function _(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 Ig(t,e){return t===null?null:_(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 ve(t,e,i){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((r,n)=>i(r,n))}function rn(t,e){return ve(t,e,(i,r)=>B(i,`${e}[${r}]`))}function it(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Ct(t,e){let i=B(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO date or timestamp`);return i}function Fo(t,e,i=!1){let r=B(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 ce(t,e){let i=z(t,e);return J(i,new Set(["text","truncated"]),e),{text:B(i.text,`${e}.text`,{empty:!0}),truncated:xt(i.truncated,`${e}.truncated`)}}function jg(t,e){let i=`Native spec_changes[${e}]`,r=z(t,i);J(r,new Set(["capability","operation","source"]),i);let n=B(r.capability,`${i}.capability`);if(!Cg.test(n))throw new Error(`${i}.capability is invalid`);let a=D(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Fo(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 $g(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=Mo(i.change_branch,`${e}.change_branch`),a=Mo(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 Og(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=rn(i.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return it(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.goal_cycle,`${e}.goal_cycle`,1),iteration:_(i.iteration,`${e}.iteration`),attempt:_(i.attempt,`${e}.attempt`),retry_epoch:_(i.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${e}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:r,next_action:Mo(i.next_action,`${e}.next_action`)}}function Hg(t,e){let i=`Native acceptance[${e}]`,r=z(t,i);J(r,new Set(["id","source","text","result","reason"]),i);let n=B(r.id,`${i}.id`);if(!Rg.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Fo(r.source,`${i}.source`),text:B(r.text,`${i}.text`),result:D(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:ce(r.reason,`${i}.reason`)}}function Dg(t,e){let i=`Native builder_handoff.checks[${e}]`,r=z(t,i);return J(r,new Set(["name","result","note"]),i),{name:ce(r.name,`${i}.name`),result:D(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:ce(r.note,`${i}.note`)}}function Bg(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=rn(i.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return it(r,`${e}.addressed_acceptance_ids`),{candidate_id:B(i.candidate_id,`${e}.candidate_id`),identity_provider:B(i.identity_provider,`${e}.identity_provider`),builder_execution_ref:B(i.builder_execution_ref,`${e}.builder_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),summary:ce(i.summary,`${e}.summary`),addressed_acceptance_ids:r,checks:ve(i.checks,`${e}.checks`,Dg),checks_truncated:xt(i.checks_truncated,`${e}.checks_truncated`),known_limits:ve(i.known_limits,`${e}.known_limits`,(n,a)=>ce(n,`${e}.known_limits[${a}]`)),known_limits_truncated:xt(i.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:Ct(i.submitted_at,`${e}.submitted_at`)}}function Lg(t,e){let i=`Native blockers[${e}]`,r=z(t,i);J(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=rn(r.acceptance_ids,`${i}.acceptance_ids`);return it(n,`${i}.acceptance_ids`),{owner:D(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:ce(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 Mg(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:B(r.id,`${i}.id`),name:ce(r.name,`${i}.name`),argv_display:ve(r.argv_display,`${i}.argv_display`,(n,a)=>ce(n,`${i}.argv_display[${a}]`)),argv_truncated:xt(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Fo(r.cwd_ref,`${i}.cwd_ref`,!0),status:D(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Ig(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Fg(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=ve(i.checks,`${e}.checks`,Mg);it(r.map(a=>a.id),`${e}.checks IDs`);let n=B(i.identity_provider,`${e}.identity_provider`);return{candidate_id:B(i.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:B(i.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:_(i.iteration,`${e}.iteration`,1),attempt:_(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:ce(i.summary,`${e}.summary`),risks:ve(i.risks,`${e}.risks`,(a,o)=>ce(a,`${e}.risks[${o}]`)),risks_truncated:xt(i.risks_truncated,`${e}.risks_truncated`),completed_at:Ct(i.completed_at,`${e}.completed_at`)}}function Vg(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=rn(r.unresolved_ids,`${i}.unresolved_ids`);return it(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:D(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:ce(r.summary,`${i}.summary`),completed_at:Ct(r.completed_at,`${i}.completed_at`)}}function qg(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.pass,`${e}.pass`),fail:_(i.fail,`${e}.fail`),blocked:_(i.blocked,`${e}.blocked`),"execution-error":_(i["execution-error"],`${e}.execution-error`),recovery:_(i.recovery,`${e}.recovery`)}}function Wg(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.dropped_entries,`${e}.dropped_entries`),n=i.first_dropped_at===null?null:Ct(i.first_dropped_at,`${e}.first_dropped_at`),a=i.last_dropped_at===null?null:Ct(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=qg(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 zg(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 Jg(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 rt(t){let e=z(t,"Native portable state");if(J(e,_g,"Native portable state"),e.schema!==Pt)throw new Error(`Native portable state schema must be ${Pt}`);let i=B(e.name,"Native state name");if(!xg.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=ve(e.spec_changes,"Native spec_changes",jg);it(r.map(s=>s.capability),"Native spec change capabilities");let n=ve(e.acceptance,"Native acceptance",Hg);it(n.map(s=>s.id),"Native acceptance IDs");let a=ve(e.history,"Native history",Vg);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Pt,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:_(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:Tg(e.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:$g(e.workspace),loop:Og(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:Bg(e.builder_handoff),blockers:ve(e.blockers,"Native blockers",Lg),verification:e.verification===null?null:Fg(e.verification),history:a,history_overflow:Wg(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:xt(e.archived,"Native archived"),created_at:Ct(e.created_at,"Native created_at")};return zg(o),Jg(o),o}function Gg(t,e){let i=(0,tn.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 Ce(t){let e=await Pg.readFile(t,"utf8");return rt(Gg(e,"Native portable state"))}async function nn(t,e,i={}){let r=rt(e);await de(t,(0,tn.stringify)(r),i)}var Zr=new Map;async function Ug(t,e){let i=Zr.get(t)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Zr.set(t,a),await i;try{return await e()}finally{r(),Zr.get(t)===a&&Zr.delete(t)}}async function _u(t){return Ug(t.file,async()=>{let e=_(t.expectedStateVersion,"Native expected state version",1),i=rt(t.next);if(i.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ce(t.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==e)throw new en(e,r.state_version);return await nn(t.file,i,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Ce(t.file);if(n.state_version!==e)throw new en(e,n.state_version)}}),i})}function Kg(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function an(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(Kg(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let i="",r=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(r+a>e)break;i+=n,r+=a}return{text:i,truncated:!0}}var Re="comet.native.v3",ge="comet.native.v2",we="comet.native.v1";var on="comet.native.portable-migration.v1",Xg=new Set(["schema","id","change","fromSchema","status","createdAt"]),Qg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Zg=/^[a-z0-9][a-z0-9-]{7,127}$/u,ew=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),tw=new Set([we,ge,Re]);function iw(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function rw(t,e){let i=t instanceof Date?new Date(t.valueOf()):new Date(t);if(Number.isNaN(i.valueOf()))throw new Error(`${e} must be a valid timestamp`);return i.toISOString()}function nw(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 aw(t){return t.schema===we?bi(t):t.schema===ge?ki(t):Si(t)}function ow(t){return Yg.posix.normalize(t.replaceAll("\\","/"))}function sw(t){return t.spec_changes.map(e=>e.operation==="remove"?{capability:e.capability,operation:"remove",source:null}:{capability:e.capability,operation:e.operation==="replace"?"modify":"create",source:ow(e.source)})}function cw(t){return t==="shape"?"shape":"build"}function lw(t,e){return t==="zh-CN"?e==="shape"?"继续澄清并确认验收项":"重新提交候选实现":e==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function uw(t,e,i){return t==="zh-CN"?`从旧版 ${e} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${e} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Tu(t){let e=aw(t.state);Ru(t.acceptance);let i=cw(e.phase),r=i==="shape"?0:1,n=rw(t.migratedAt??`${e.created_at}T00:00:00.000Z`,"Native portable migration time"),a=t.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return rt({schema:Pt,name:e.name,language:e.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:sw(e),workspace:t.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:lw(e.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:an(uw(e.language,e.schema,e.phase)),completed_at:n}],history_overflow:Lo(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${e.created_at}T00:00:00.000Z`})}function Vo(t){let e=iw(t,"Native portable migration transaction"),i=Object.keys(e).filter(r=>!Xg.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(e.schema!==on)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!Zg.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!Qg.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!tw.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:on,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:nw(e.createdAt,"Native portable migration transaction createdAt")}}function Iu(t){switch(Vo(t).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var ju="comet.native.archive-transaction.v4",$u="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",dw=new RegExp(`^portable-archive-(${$u})\\.json$`,"u"),fw=new RegExp(`^portable-migration-(${$u})\\.json$`,"u"),hw=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pw=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mw=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),vw=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),gw=new Set(["capability","operation","source","content"]),Ou=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Hu(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Du(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 ww(t,e){let i=`Native portable Archive spec_changes[${e}]`,r=Hu(t,i);if(Du(r,gw,i),typeof r.capability!="string"||!Ou.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 yw(t){let e=Hu(t,"Native portable Archive transaction");if(Du(e,vw,"Native portable Archive transaction"),e.schema!==ju)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!hw.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Ou.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"||!pw.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"||!mw.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(ww);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 sn(t){let e=dw.exec(t);if(e)return{kind:"archive",change:e[1]};let i=fw.exec(t);return i?{kind:"migration",change:i[1]}:null}function cn(t,e){let i=`${e.kind==="archive"?"portable-archive":"portable-migration"}-${e.change}.json`,r=sn(i);if(!r||r.kind!==e.kind||r.change!==e.change)throw new Error(`Invalid Native portable transaction change: ${e.change}`);return qo.join(t.transactionsDir,i)}async function Wo(t,e){let i=sn(e);if(!i)return null;let r=await M({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=qo.join(t.transactionsDir,e);if(i.kind==="archive"){let s=yw(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=Vo(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function Bu(t,e){let i=cn(t,e);try{return await Wo(t,qo.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function Lu(t){return t.kind==="archive"||t.journal.status!=="committed"}import Ae from"path";import{TextDecoder as Cw}from"util";import{createHash as Nw}from"node:crypto";import{constants as ln,promises as le}from"node:fs";import ue from"node:path";function dn(t,e){let i=ue.relative(t,e);return i===""||!ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ue.sep}`)}function bw(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function kw(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Sw(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function un(t,e){return A({...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 zo(t,e){let i=await le.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await le.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ew(t,e,i){let r=ue.resolve(t),n=ue.resolve(e);if(!dn(r,n))throw new Error(`${i} is outside its managed root`);let a=[await zo(r,i)],o=r;for(let s of ue.relative(r,n).split(ue.sep).filter(Boolean)){await nt(a,i),o=ue.join(o,s);let c=await zo(o,i);if(!dn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await nt(a,i),a}async function nt(t,e){for(let i of t){let r=await le.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!kw(i,r)||await le.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Pw(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 Rt(t){let e=bw(t.maxBytes),i=ue.resolve(t.file),r=await Ew(t.root,ue.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(f=>zo(ue.resolve(f),t.label)));await t.hooks?.afterParentChainCaptured?.(),await nt(r,t.label);let a=await le.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=Sw(a),s=await le.realpath(i);if(!dn(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(f=>dn(f.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ln.O_RDONLY:ln.O_RDONLY|ln.O_NOFOLLOW|ln.O_NONBLOCK,l=await le.open(i,c);try{let f=await l.stat();await t.hooks?.afterOpen?.();let[d,u]=await Promise.all([le.lstat(i),le.realpath(i)]);if(await nt(r,t.label),await nt(n,t.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!un(o,f)||!un(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await Pw(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),le.lstat(i),le.realpath(i)]);if(await nt(r,t.label),await nt(n,t.label),!h.isFile()||h.isSymbolicLink()||m!==s||!un(o,v)||!un(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:Nw("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Rw=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Aw=new Set(["id","type","source","target","staged","backup"]),_w=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Tw=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Vu=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Iw=256*1024,XS=1024*1024,QS=16*1024;var ZS=64*1024*1024;var jw=new Cw("utf-8",{fatal:!0});function hn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function pn(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 qu(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Jo(t,e){if(typeof t!="string"||t.length===0||Ae.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function fn(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Mu(t,e){if(Jo(t,e),t.includes("\\")||t!==Ae.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 $w(t,e){let i=hn(t,`transaction operations[${e}]`);if(pn(i,Aw,`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`);Jo(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Jo(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 Wu(t){let e=hn(t,"Native Archive transaction journal");if(pn(e,_w,"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"||!Vu.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(!qu(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(fn(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=hn(s,`Archive transaction operations[${c}]`);if(pn(l,Tw,`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`);Mu(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Mu(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&fn(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(fn(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);fn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${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 Ow(t){let e=hn(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Wu(e);if(pn(e,Rw,"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"||!Vu.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Ae.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Ae.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(!qu(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($w),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 Hw(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Ae.join(t.transactionsDir,e)}function zu(t,e){let i=Hw(t,e);return{directory:i,journal:Ae.join(i,"transaction.json"),events:Ae.join(i,"events.jsonl"),staged:Ae.join(i,"staged"),backups:Ae.join(i,"backups")}}async function Uo(t,e){let i=zu(t,e);return await Promise.all(Object.values(i).map(r=>T(t.runtimeDir,r))),i}async function Ko(t,e,i={}){let r=await Uo(t,e),n=await Rt({root:t.runtimeDir,file:r.journal,maxBytes:Iw,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(jw.decode(n.bytes)),o=Ow(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Lw(t,e,i){let r;try{r=await Dw.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 Ko(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(sn(n.name))try{let a=await Wo(t,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Lu(a))return!0}catch{return!0}return!1}async function Mw(t,e){let i=Date.now()+5e3,r=Bw.join(t.locksDir,"root-move.lock");for(;;)try{return await Xr(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Eu(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 ee(t,e,i,r){let n=await Mw(t,e);try{if(await Kr(t.projectRoot),await Lw(t,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Qr(n)}}import{createHash as Fw}from"crypto";function te(t){return Fw("sha256").update(t).digest("hex")}var NE={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var bE=8*1024*1024;var kE=64*1024,SE=64*1024;var EE={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},PE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var xE=(1n<<256n)-1n;var Uw=jt(wt(),1);var VE=4*1024*1024;var Kw=null;function Yw(t,e){let i=t;for(let r of e)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Ju(t,e){return(...i)=>{let r=Kw;if(r===null)return e(...i);let n=Yw(`async:${t}`,i),a=r.entries.get(n);if(a)return a.value;let o=e(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var GE=Ju("hookWritePolicy",async t=>(await No(t))?.hook??{allow_paths:[]});var VP=256*1024;var tx={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 At from"node:path";var Ei=/^[a-f0-9]{64}$/u,Uu=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Zw=16*1024,gx=process.platform;function ey(t,e){let i=At.relative(t,e);return At.isAbsolute(i)||i===".."||i.startsWith(`..${At.sep}`)?null:i.replaceAll("\\","/")||"."}function Ku(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function Yu(t,e){if(t.length===0||Ku(t)||t.includes("\\")||At.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=At.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function ty(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 Yo(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Ku(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function iy(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Yo(t.changeBranch,"Native workspace change branch"),Yo(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 ry(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"||!Uu.test(e.baseCommit)||typeof e.targetCommit!="string"||!Uu.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");Yo(e.targetBranch,"Native workspace Git target branch")}function ny(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"||!Ei.test(String(e.projectRootId))||!Ei.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");ty(e.capturedAt),Yu(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&&!Ei.test(String(e.projectRootPathId))||a&&!Ei.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Ei.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&ry(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(iy(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 ay(t,e){return At.join(pe(t,e),"workspace.json")}function oy(t,e){let i=ay(t,e),r=me(t,i),n=ey(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Yu(n,"Native workspace file ref")}}async function sy(t,e){try{let i=oy(t,e),r=await M({root:i.root,ref:i.ref,maxBytes:Zw});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Pi(t,e){let i=await sy(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ny(i),i)}var Zu=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],ly=new Set(Zu),ed=new Set([...Zu,"minimum_runtime_version","revision"]),uy=new Set([...ed,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),dy=new Set(["capability","operation","source","base_hash"]),fy=new Set(["shape","build","verify","archive"]),hy=new Set(["implicit","confirmed"]),py=new Set(["pending","pass","fail"]),at="comet-state.yaml",Qo=/^[a-f0-9]{64}$/u,td=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,my=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Zo=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"},Tt=class extends Error{constructor(i,r){super(i!==Re||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"},mn=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},xi=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},vn=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"},Vx=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
150
|
+
`);function Ri(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function id(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 ts(t){if(!td.test(t))throw new Error(`Invalid Native change name: ${t}`)}function vy(t){if(!td.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function rd(t,e){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function gy(t,e){let i=Ri(t,`spec_changes[${e}]`);if(id(i,dy,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(vy(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"&&rd(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"||!Qo.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"||!Qo.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 wy(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 is(t,e){if(id(t,e,at),typeof t.name!="string")throw new Error("Native change name is required");if(ts(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"||!fy.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&&!hy.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(gy),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"||!py.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"&&rd(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!wy(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 bi(t){let e=Ri(t,at);if(e.schema!==we)throw new Error(`Expected ${we}`);return{schema:we,...is(e,ly)}}function Ci(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Xo(t,e,i){if(t===null)return null;let r=typeof t=="string"?my.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 yy(t){if(t==null)return null;if(typeof t!="string"||!Qo.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function Ny(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 ki(t){let e=Ri(t,at);if(e.schema!==ge)throw new Error(`Expected ${ge}`);if(Ci(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ge} minimum_runtime_version must be 2`);return{schema:ge,minimum_runtime_version:2,revision:Ci(e.revision,"Native v2 revision"),...is(e,ed)}}function Si(t){let e=Ri(t,at);if(e.schema!==Re){if(e.schema===we||e.schema===ge){let o=e.schema===we?bi(e):ki(e);throw new Zo(o.name,o.schema)}throw new Tt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Ci(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Tt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=Ci(e.revision,"Native revision"),n=is(e,uy),a=yy(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Re,minimum_runtime_version:3,revision:r,verification_protocol:Ny(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xo(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xo(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xo(e.partial_allowance,"Native partial_allowance","allowances")}}function by(t){let e=Ri(t,at);if(e.schema===we){let n=bi(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Re}`}}if(e.schema===ge){let n=ki(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Re}`}}if(e.schema!==Re){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 Tt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=Ci(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Tt(e.schema,i).message};let r=Si(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function ye(t,e){ts(e);let i=_t.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}var ky=256*1024;async function Sy(t,e=_t.dirname(t)){let i=_t.relative(e,t).split(_t.sep).join("/"),r=await M({root:e,ref:i,maxBytes:ky}),n=(0,es.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 nd(t,e){let i=_t.join(ye(t,e),at);await T(t.nativeRoot,i);let r=by(await Sy(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return r}import{promises as sd}from"node:fs";import Sn from"node:path";var Py=jt(wt(),1);var Wx=8*1024*1024;var eC=["$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 Ty}from"node:fs";import _i from"node:path";function gn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function wn(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 Ne(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 ad(t,e){return t===null?null:Ne(t,e)}function Nn(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 Iy(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 jy(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function yn(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function rs(t,e){if(t===null)return null;let i=Ne(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO timestamp`);return i}function ns(t,e){let i=Ne(t,e);if(!_i.isAbsolute(i))throw new Error(`${e} must be absolute`);return _i.resolve(i)}function $y(t,e){let i=`Native local checks[${e}]`,r=gn(t,i);if(wn(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,f)=>Ne(l,`${i}.argv[${f}]`,!0)),a=yn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=rs(r.startedAt,`${i}.startedAt`),s=rs(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=Nn(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ne(r.id,`${i}.id`),name:Ne(r.name,`${i}.name`),operationId:Ne(r.operationId,`${i}.operationId`),status:a,repeatable:jy(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Nn(r.executionCount,`${i}.executionCount`),argv:n,cwd:ns(r.cwd,`${i}.cwd`),exitCode:Iy(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ne(r.log,`${i}.log`)}}function od(t){let e="Native local execution state",i=gn(t,e);if(wn(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),i.schema!==Ni)throw new Error(`Native local execution schema must be ${Ni}`);let r=gn(i.workspace,"Native local workspace");wn(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=gn(i.execution,"Native local execution");wn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=rs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ne(o.operationId,"Native local execution.operationId"),stage:yn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:yn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ad(o.executionId,"Native local execution.executionId"),status:yn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Nn(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($y);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:Ni,change:Ne(i.change,"Native local change"),basedOnStateVersion:Nn(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:ns(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ns(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ad(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function bn(t){return od({schema:Ni,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:_i.resolve(t.projectRoot),worktreeRoot:_i.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function kn(t,e,i={}){let r=od(e);await Ty.mkdir(_i.dirname(t),{recursive:!0}),await Y(t,r,i)}var cd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Oy="comet-state.yaml",Hy="state.json";function ld(t,e){if(!cd.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=Sn.join(t.changesDir,e);if(!F(t.changesDir,i))throw new Error("Native change path escaped");return i}function ze(t,e){return Sn.join(ld(t,e),Oy)}function as(t,e){return Sn.join(tt(t,e),Hy)}async function Ti(t,e){try{let i=await sd.readFile(ze(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function Dy(t){return ke(t).currentBranch}async function ud(t,e){return Ce(ze(t,e))}async function By(t){let e=await _u({file:ze(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let i=Sn.join(ld(t.paths,e.name),"verification.md");await T(t.paths.nativeRoot,i),await sd.rm(i,{force:!0})}return e}async function dd(t){if(!cd.test(t.capability))throw new Error(`Invalid Native capability: ${t.capability}`);return ee(t.paths,`remove portable spec ${t.capability}`,async()=>{let e=await ud(t.paths,t.name);if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let i=e.spec_changes.filter(({capability:a})=>a!==t.capability),r={...e,phase:"shape",status:"active",state_version:e.state_version+1,spec_changes:[...i,{capability:t.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+(e.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await By({paths:t.paths,previous:e,next:r});return await kn(as(t.paths,e.name),bn({portableState:n,projectRoot:t.paths.projectRoot,branch:Dy(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n})}var Fy=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function Vy(t,e){let i=await Bu(t,{kind:"migration",change:e});return i?.kind==="migration"?i.journal:null}async function fd(t,e){await Ii.mkdir(t.transactionsDir,{recursive:!0}),await Y(cn(t,{kind:"migration",change:e.change}),e,{containedRoot:t.runtimeDir})}async function hd(t,e){await Promise.all([Ii.rm(tt(t,e),{recursive:!0,force:!0}),Ii.rm(Po(t,e),{recursive:!0,force:!0}),...Fy.map(i=>Ii.rm(My.join(ye(t,e),i),{force:!0}))])}async function pd(t,e){await kn(as(t,e.name),bn({portableState:e,projectRoot:t.projectRoot}),{containedRoot:t.runtimeDir})}async function md(t,e){try{let i=await Pi(t,e);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function vd(t,e){if(e.isolation==="current"&&e.change_branch===null)return;let i=ke(t.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==e.change_branch)throw new Error(`Native legacy migration expected branch ${e.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function qy(t){let e=ye(t.paths,t.state.name),i=await M({root:e,ref:t.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of t.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await M({root:e,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Bo({briefMarkdown:i.text,specs:r})}catch(n){if(t.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function gd(t,e){let i=await nd(t,e);if(!i.state)throw new Error(`Native legacy change ${e} is unreadable`);return i.state}async function wd(t){return ee(t.paths,`migrate ${t.name} to portable Native`,async()=>{let e=await Vy(t.paths,t.name),i=await Ti(t.paths,t.name)?await Ce(ze(t.paths,t.name)):null;if(!e&&i)return await hd(t.paths,t.name),await pd(t.paths,i),i;let r=null,n=null;for(e||(r=await gd(t.paths,t.name),n=await md(t.paths,t.name),vd(t.paths,n),e={schema:on,id:Ly(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(t.now??new Date).toISOString()},await fd(t.paths,e));;){let a=Iu(e);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await gd(t.paths,t.name),n??=await md(t.paths,t.name),vd(t.paths,n),i=Tu({state:r,acceptance:await qy({paths:t.paths,state:r}),workspace:n,migratedAt:t.now}),await nn(ze(t.paths,t.name),i,{containedRoot:t.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await hd(t.paths,t.name):a.action==="commit-transaction"&&(i??=await Ce(ze(t.paths,t.name)),await pd(t.paths,i)),e={...e,status:a.nextStatus},await fd(t.paths,e)}return await Ii.rm(cn(t.paths,{kind:"migration",change:t.name}),{force:!0}),i??Ce(ze(t.paths,t.name))},{allowedPortableTransaction:{kind:"migration",change:t.name}})}import cs from"path";var zy=["Outcome","Scope","Non-goals","Acceptance examples"],QR=[...zy,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var Jy=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 yd=1024*1024;var bd="scoped-text-safety",Gy=1,Uy=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Ky="comet.native.checker-policy.v1";var pA=K(Ky,{policy:bd,version:Gy,limits:Uy,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Yy=["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"],mA=new Set(Yy);var Zy=yd,IA=3*Zy;var kd={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:[]},tN=te("comet-native-runtime:v3:scope-reopen"),a_=[{skillVersion:"3",skillHash:te("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:te("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:te("comet-native-runtime:v1")}];var Ed=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],L_=new Set(Ed),cN=new Set([...Ed,"minimum_runtime_version","revision"]),M_=new Set([...cN,"operation"]),F_=512*1024,lN=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),V_=new Set([...lN,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var J_={maxAcceptanceCriteria:yi.maxCriteria};var X_={maxSpecs:64,maxFileBytes:Di,maxTotalBytes:4*1024*1024};import{execFile as wN}from"node:child_process";import{promisify as yN}from"node:util";var sT={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var RT=512*1024;var ji=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var XT=64*1024;var QT=3600*1e3;var ZT=yN(wN);var En=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 BI={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var UI=16*1024*1024,KI=256*1024,YI=16*1024;var tj=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var nj=16*1024;var vj=16*1024;var o$=16*1024*1024,Pn=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"},xn=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 Cn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Cd=["--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."],ss=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:Cd,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
|
|
151
|
+
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Implementation changed" --return-to-build','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
152
|
+
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 os(t,e){return`${t}:
|
|
153
|
+
${e.map(i=>` ${i}`).join(`
|
|
154
|
+
`)}`}function PN(t){let e=t.filter(r=>r!=="--help");if(e.length===0)return"";let i=e.slice(0,2).join(" ");return ss[i]||e.length>1&&ss[e[0]]?.subcommands?i:e[0]}function xN(t=[]){let e=PN(t),i=ss[e];if(!i)throw new Error(`Unknown Native help topic: ${e}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",os("Commands",i.subcommands));let n=e===""?i.options:[...i.options??[],...Cd];return n&&n.length>0&&r.push("",os("Options",n)),r.push("",`Output:
|
|
155
|
+
${i.output}`),i.examples&&r.push("",os("Examples",i.examples)),e===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${r.join(`
|
|
156
|
+
`)}
|
|
157
|
+
`}}var CN=xN().usage;var A$=10*1024*1024,be=class extends Error{};function Ad(t,e){let i=t.flatMap((r,n)=>r===e?[n]:[]);if(i.length>1)throw new be(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function _d(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new be(`${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 be(`${e} requires a value`);return t.splice(r,2),n}function Td(t){if(t.length>0)throw new be(`Unexpected argument: ${t[0]}`)}function Rn(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new be(`${e} is required`);return i}function Rd(t,e){let i=cs.normalize(t),r=cs.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function RN(t){let e=cs.resolve(t),i=ke(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return e;let r=ke(e);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Rd(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Rd(i.currentWorktreeRoot,r.currentWorktreeRoot)?e:i.currentWorktreeRoot}async function Id(t){return t?RN(t):Gr(process.cwd())}async function jd(t){let e=await fu({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function $d(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+`
|
|
158
|
+
`}}function Od(t,e){if(e instanceof be)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Pn)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 xn)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof mn)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 xi)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 Cn)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof vn)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 En)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof ji)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 Hd(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}})+`
|
|
159
|
+
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Dd(t,e){let i=Rn(t,"spec subcommand");if(i!=="remove")throw new be(`Unknown spec command: ${i}`);let r=Rn(t,"change name"),n=Rn(t,"capability");Td(t);let{paths:a}=await jd(e);await Ti(a,r)||await wd({paths:a,name:r});let o=await dd({paths:a,name:r,capability:n});return $d("spec remove",{...o,continuation:ds(o)},`Marked Native capability ${n} for removal in ${r}
|
|
160
|
+
`)}function AN(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}})+`
|
|
161
|
+
`}}async function Bd(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{Ad(n,"--json"),s=_d(n,"--project-root");let f=[...n,...a],d=await Id(s);c=await e(f,d)}catch(f){c=Od(t,f)}let l=o?AN(c):Hd(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
180
162
|
`)?"":`
|
|
181
|
-
`)),l.exitCode}process.exitCode=await
|
|
163
|
+
`)),l.exitCode}process.exitCode=await Bd("spec",Dd);
|