@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,182 +1,213 @@
|
|
|
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 Qh=Object.create;var Ic=Object.defineProperty;var Zh=Object.getOwnPropertyDescriptor;var ep=Object.getOwnPropertyNames;var tp=Object.getPrototypeOf,ip=Object.prototype.hasOwnProperty;var Pr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var y=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var rp=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ep(t))!ip.call(e,n)&&n!==i&&Ic(e,n,{get:()=>t[n],enumerable:!(r=Zh(t,n))||r.enumerable});return e};var di=(e,t,i)=>(i=e!=null?Qh(tp(e)):{},rp(t||!e||!e.__esModule?Ic(i,"default",{value:e,enumerable:!0}):i,e));var x=y(z=>{"use strict";var Aa=Symbol.for("yaml.alias"),jc=Symbol.for("yaml.document"),xr=Symbol.for("yaml.map"),$c=Symbol.for("yaml.pair"),_a=Symbol.for("yaml.scalar"),Rr=Symbol.for("yaml.seq"),Je=Symbol.for("yaml.node.type"),np=e=>!!e&&typeof e=="object"&&e[Je]===Aa,ap=e=>!!e&&typeof e=="object"&&e[Je]===jc,op=e=>!!e&&typeof e=="object"&&e[Je]===xr,sp=e=>!!e&&typeof e=="object"&&e[Je]===$c,Oc=e=>!!e&&typeof e=="object"&&e[Je]===_a,cp=e=>!!e&&typeof e=="object"&&e[Je]===Rr;function Hc(e){if(e&&typeof e=="object")switch(e[Je]){case xr:case Rr:return!0}return!1}function lp(e){if(e&&typeof e=="object")switch(e[Je]){case Aa:case xr:case _a:case Rr:return!0}return!1}var up=e=>(Oc(e)||Hc(e))&&!!e.anchor;z.ALIAS=Aa;z.DOC=jc;z.MAP=xr;z.NODE_TYPE=Je;z.PAIR=$c;z.SCALAR=_a;z.SEQ=Rr;z.hasAnchor=up;z.isAlias=np;z.isCollection=Hc;z.isDocument=ap;z.isMap=op;z.isNode=lp;z.isPair=sp;z.isScalar=Oc;z.isSeq=cp});var fi=y(Ta=>{"use strict";var F=x(),Z=Symbol("break visit"),Dc=Symbol("skip children"),je=Symbol("remove node");function Cr(e,t){let i=Bc(t);F.isDocument(e)?Ht(null,e.contents,i,Object.freeze([e]))===je&&(e.contents=null):Ht(null,e,i,Object.freeze([]))}Cr.BREAK=Z;Cr.SKIP=Dc;Cr.REMOVE=je;function Ht(e,t,i,r){let n=Lc(e,t,i,r);if(F.isNode(n)||F.isPair(n))return Mc(e,r,n),Ht(e,n,i,r);if(typeof n!="symbol"){if(F.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Ht(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===Z)return Z;o===je&&(t.items.splice(a,1),a-=1)}}}else if(F.isPair(t)){r=Object.freeze(r.concat(t));let a=Ht("key",t.key,i,r);if(a===Z)return Z;a===je&&(t.key=null);let o=Ht("value",t.value,i,r);if(o===Z)return Z;o===je&&(t.value=null)}}return n}async function Ar(e,t){let i=Bc(t);F.isDocument(e)?await Dt(null,e.contents,i,Object.freeze([e]))===je&&(e.contents=null):await Dt(null,e,i,Object.freeze([]))}Ar.BREAK=Z;Ar.SKIP=Dc;Ar.REMOVE=je;async function Dt(e,t,i,r){let n=await Lc(e,t,i,r);if(F.isNode(n)||F.isPair(n))return Mc(e,r,n),Dt(e,n,i,r);if(typeof n!="symbol"){if(F.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Dt(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===Z)return Z;o===je&&(t.items.splice(a,1),a-=1)}}}else if(F.isPair(t)){r=Object.freeze(r.concat(t));let a=await Dt("key",t.key,i,r);if(a===Z)return Z;a===je&&(t.key=null);let o=await Dt("value",t.value,i,r);if(o===Z)return Z;o===je&&(t.value=null)}}return n}function Bc(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Lc(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(F.isMap(t))return i.Map?.(e,t,r);if(F.isSeq(t))return i.Seq?.(e,t,r);if(F.isPair(t))return i.Pair?.(e,t,r);if(F.isScalar(t))return i.Scalar?.(e,t,r);if(F.isAlias(t))return i.Alias?.(e,t,r)}function Mc(e,t,i){let r=t[t.length-1];if(F.isCollection(r))r.items[e]=i;else if(F.isPair(r))e==="key"?r.key=i:r.value=i;else if(F.isDocument(r))r.contents=i;else{let n=F.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ta.visit=Cr;Ta.visitAsync=Ar});var Ia=y(Vc=>{"use strict";var Fc=x(),dp=fi(),fp={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},hp=e=>e.replace(/[!,[\]{}]/g,t=>fp[t]),hi=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.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(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} 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==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+hp(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&Fc.isNode(t.contents)){let a={};dp.visit(t.contents,(o,s)=>{Fc.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:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};hi.defaultYaml={explicit:!1,version:"1.2"};hi.defaultTags={"!!":"tag:yaml.org,2002:"};Vc.Directives=hi});var _r=y(pi=>{"use strict";var qc=x(),pp=fi();function mp(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function Wc(e){let t=new Set;return pp.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function zc(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function vp(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Wc(e));let o=zc(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(qc.isScalar(o.node)||qc.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}}pi.anchorIsValid=mp;pi.anchorNames=Wc;pi.createNodeAnchors=vp;pi.findNewAnchor=zc});var ja=y(Jc=>{"use strict";function mi(e,t,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=mi(e,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=mi(e,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=mi(e,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=mi(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}Jc.applyReviver=mi});var tt=y(Uc=>{"use strict";var gp=x();function Gc(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Gc(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!gp.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}Uc.toJS=Gc});var Tr=y(Yc=>{"use strict";var wp=ja(),Kc=x(),yp=tt(),$a=class{constructor(t){Object.defineProperty(this,Kc.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Kc.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=yp.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?wp.applyReviver(a,{"":s},"",s):s}};Yc.NodeBase=$a});var vi=y(Xc=>{"use strict";var Np=_r(),bp=fi(),Bt=x(),kp=Tr(),Sp=tt(),Oa=class extends kp.NodeBase{constructor(t){super(Bt.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],bp.visit(t,{Node:(a,o)=>{(Bt.isAlias(o)||Bt.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(t,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||(Sp.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=Ir(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(t,i,r){let n=`*${this.source}`;if(t){if(Np.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Ir(e,t,i){if(Bt.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Bt.isCollection(t)){let r=0;for(let n of t.items){let a=Ir(e,n,i);a>r&&(r=a)}return r}else if(Bt.isPair(t)){let r=Ir(e,t.key,i),n=Ir(e,t.value,i);return Math.max(r,n)}return 1}Xc.Alias=Oa});var L=y(Ha=>{"use strict";var Ep=x(),Pp=Tr(),xp=tt(),Rp=e=>!e||typeof e!="function"&&typeof e!="object",it=class extends Pp.NodeBase{constructor(t){super(Ep.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:xp.toJS(this.value,t,i)}toString(){return String(this.value)}};it.BLOCK_FOLDED="BLOCK_FOLDED";it.BLOCK_LITERAL="BLOCK_LITERAL";it.PLAIN="PLAIN";it.QUOTE_DOUBLE="QUOTE_DOUBLE";it.QUOTE_SINGLE="QUOTE_SINGLE";Ha.Scalar=it;Ha.isScalarValue=Rp});var gi=y(Zc=>{"use strict";var Cp=vi(),gt=x(),Qc=L(),Ap="tag:yaml.org,2002:";function _p(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function Tp(e,t,i){if(gt.isDocument(e)&&(e=e.contents),gt.isNode(e))return e;if(gt.isPair(e)){let d=i.schema[gt.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Cp.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Ap+t.slice(2));let l=_p(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Qc.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[gt.MAP]:Symbol.iterator in Object(e)?o[gt.SEQ]:o[gt.MAP]}a&&(a(l),delete i.onTagObj);let f=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Qc.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Zc.createNode=Tp});var $r=y(jr=>{"use strict";var Ip=gi(),$e=x(),jp=Tr();function Da(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Ip.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var el=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ba=class extends jp.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>$e.isNode(r)||$e.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(el(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if($e.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Da(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if($e.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&$e.isScalar(a)?a.value:a:$e.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!$e.isPair(i))return!1;let r=i.value;return r==null||t&&$e.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return $e.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if($e.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Da(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};jr.Collection=Ba;jr.collectionFromPath=Da;jr.isEmptyPath=el});var wi=y(Or=>{"use strict";var $p=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function La(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Op=(e,t,i)=>e.endsWith(`
|
|
6
|
+
`)?La(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
10
|
-
`&&
|
|
11
|
-
`&&
|
|
12
|
-
${t}${e.slice(0,
|
|
13
|
-
${t}${e.slice(
|
|
14
|
-
`);
|
|
15
|
-
`){if(a-o>
|
|
8
|
+
`+La(i,t):(e.endsWith(" ")?"":" ")+i;Or.indentComment=La;Or.lineComment=Op;Or.stringifyComment=$p});var il=y(yi=>{"use strict";var Hp="flow",Ma="block",Hr="quoted";function Dp(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],f={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let u,p,m=!1,h=-1,v=-1,g=-1;i===Ma&&(h=tl(e,h,t.length),h!==-1&&(d=h+c));for(let N;N=e[h+=1];){if(i===Hr&&N==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(N===`
|
|
9
|
+
`)i===Ma&&(h=tl(e,h,t.length)),d=h+t.length+c,u=void 0;else{if(N===" "&&p&&p!==" "&&p!==`
|
|
10
|
+
`&&p!==" "){let k=e[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===Hr){for(;p===" "||p===" ";)p=N,N=e[h+=1],m=!0;let k=h>g+1?h-2:v-1;if(f[k])return e;l.push(k),f[k]=!0,d=k+c,u=void 0}else m=!0}p=N}if(m&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let N=0;N<l.length;++N){let k=l[N],E=l[N+1]||e.length;k===0?w=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(i===Hr&&f[k]&&(w+=`${e[k]}\\`),w+=`
|
|
13
|
+
${t}${e.slice(k+1,E)}`)}return w}function tl(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}yi.FOLD_BLOCK=Ma;yi.FOLD_FLOW=Hp;yi.FOLD_QUOTED=Hr;yi.foldFlowLines=Dp});var bi=y(rl=>{"use strict";var Ne=L(),rt=il(),Br=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Lr=e=>/^(%|---|\.\.\.)/m.test(e);function Bp(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Ni(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Lr(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let f=i.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(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(e))return
|
|
20
|
-
${i}`)+"'";return t.implicitKey?
|
|
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:rt.foldFlowLines(o,a,rt.FOLD_QUOTED,Br(t,!1))}function Fa(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Ni(e,t);let i=t.indent||(Lr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:rt.foldFlowLines(r,i,rt.FOLD_FLOW,Br(t,!1))}function Lt(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Ni;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Fa:a&&!n?r=Ni:r=i?Fa:Ni}return r(e,t)}var Va;try{Va=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Va=/\n+(?!\n|$)/g}function Dr({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return Lt(i,r);let l=r.indent||(r.forceBlockIndent||Lr(i)?" ":""),f=o==="literal"?!0:o==="folded"||t===Ne.Scalar.BLOCK_FOLDED?!1:t===Ne.Scalar.BLOCK_LITERAL?!0:!Bp(i,c,l.length);if(!i)return f?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let d,
|
|
26
|
-
`&&
|
|
27
|
-
`);m===-1?d="-":i===
|
|
28
|
-
`&&(
|
|
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
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(
|
|
39
|
-
`:"",
|
|
40
|
-
${
|
|
41
|
-
`&&N&&(
|
|
42
|
-
|
|
43
|
-
`):
|
|
44
|
-
${i.indent}`}else if(!
|
|
45
|
-
`),
|
|
46
|
-
${i.indent}`)}}else(
|
|
47
|
-
`)&&(
|
|
48
|
-
${c}${
|
|
49
|
-
`}}return e?(
|
|
50
|
-
`+
|
|
51
|
-
`)),m<e.length-1?
|
|
52
|
-
${a}${
|
|
25
|
+
`;let d,u;for(u=i.length;u>0;--u){let E=i[u-1];if(E!==`
|
|
26
|
+
`&&E!==" "&&E!==" ")break}let p=i.substring(u),m=p.indexOf(`
|
|
27
|
+
`);m===-1?d="-":i===p||m!==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(Va,`$&${l}`));let h=!1,v,g=-1;for(v=0;v<i.length;++v){let E=i[v];if(E===" ")h=!0;else if(E===`
|
|
29
|
+
`)g=v;else break}let w=i.substring(0,g<v?g+1:v);w&&(i=i.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let k=(h?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let E=i.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),S=!1,R=Br(r,!0);o!=="folded"&&t!==Ne.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{S=!0});let b=rt.foldFlowLines(`${w}${E}${p}`,l,rt.FOLD_BLOCK,R);if(!S)return`>${k}
|
|
31
|
+
${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
|
|
32
|
+
${l}${w}${i}${p}`}function Lp(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
|
|
33
|
+
`)||f&&/[[\]{},]/.test(a))return Lt(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
|
|
34
|
+
`)?Lt(a,t):Dr(e,t,i,r);if(!s&&!f&&n!==Ne.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return Dr(e,t,i,r);if(Lr(a)){if(c==="")return t.forceBlockIndent=!0,Dr(e,t,i,r);if(s&&c===l)return Lt(a,t)}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:m}=t.doc.schema;if(m.some(u)||p?.some(u))return Lt(a,t)}return s?d:rt.foldFlowLines(d,c,rt.FOLD_FLOW,Br(t,!1))}function Mp(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;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?Lt(o.value,t):Dr(o,t,i,r);case Ne.Scalar.QUOTE_DOUBLE:return Ni(o.value,t);case Ne.Scalar.QUOTE_SINGLE:return Fa(o.value,t);case Ne.Scalar.PLAIN:return Lp(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}rl.stringifyString=Mp});var ki=y(qa=>{"use strict";var Fp=_r(),nt=x(),Vp=wi(),qp=bi();function Wp(e,t){let i=Object.assign({blockQuote:!0,commentString:Vp.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function zp(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(nt.isScalar(t)){r=t.value;let n=e.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===t.format)??n.find(a=>!a.format)}else r=t,i=e.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 Jp(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(nt.isScalar(e)||nt.isCollection(e))&&e.anchor;a&&Fp.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function Gp(e,t,i,r){if(nt.isPair(e))return e.toString(t,i,r);if(nt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=nt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=zp(t.doc.schema.tags,a));let o=Jp(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):nt.isScalar(a)?qp.stringifyString(a,t,i,r):a.toString(t,i,r);return o?nt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}qa.createStringifyContext=Wp;qa.stringify=Gp});var sl=y(ol=>{"use strict";var Ge=x(),nl=L(),al=ki(),Si=wi();function Up({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=i,u=Ge.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(Ge.isCollection(e)||!Ge.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||u&&t==null&&!i.inFlow||Ge.isCollection(e)||(Ge.isScalar(e)?e.type===nl.Scalar.BLOCK_FOLDED||e.type===nl.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,v=al.stringify(e,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&v.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||t==null)return m&&r&&r(),v===""?"?":p?`? ${v}`:v}else if(a&&!d||t==null&&p)return v=`? ${v}`,u&&!m?v+=Si.lineComment(v,i.indent,l(u)):h&&n&&n(),v;m&&(u=null),p?(u&&(v+=Si.lineComment(v,i.indent,l(u))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,u&&(v+=Si.lineComment(v,i.indent,l(u))));let g,w,N;Ge.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,N=t.comment):(g=!1,w=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!u&&Ge.isScalar(t)&&(i.indentAtStart=v.length+1),h=!1,!f&&c.length>=2&&!i.inFlow&&!p&&Ge.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,E=al.stringify(t,i,()=>k=!0,()=>h=!0),S=" ";if(u||g||w){if(S=g?`
|
|
39
|
+
`:"",w){let R=l(w);S+=`
|
|
40
|
+
${Si.indentComment(R,i.indent)}`}E===""&&!i.inFlow?S===`
|
|
41
|
+
`&&N&&(S=`
|
|
42
|
+
|
|
43
|
+
`):S+=`
|
|
44
|
+
${i.indent}`}else if(!p&&Ge.isCollection(t)){let R=E[0],b=E.indexOf(`
|
|
45
|
+
`),O=b!==-1,Ie=i.inFlow??t.flow??t.items.length===0;if(O||!Ie){let ze=!1;if(O&&(R==="&"||R==="!")){let M=E.indexOf(" ");R==="&"&&M!==-1&&M<b&&E[M+1]==="!"&&(M=E.indexOf(" ",M+1)),(M===-1||b<M)&&(ze=!0)}ze||(S=`
|
|
46
|
+
${i.indent}`)}}else(E===""||E[0]===`
|
|
47
|
+
`)&&(S="");return v+=S+E,i.inFlow?k&&r&&r():N&&!k?v+=Si.lineComment(v,i.indent,l(N)):h&&n&&n(),v}ol.stringifyPair=Up});var za=y(Wa=>{"use strict";var cl=Pr("process");function Kp(e,...t){e==="debug"&&console.log(...t)}function Yp(e,t){(e==="debug"||e==="warn")&&(typeof cl.emitWarning=="function"?cl.emitWarning(t):console.warn(t))}Wa.debug=Kp;Wa.warn=Yp});var Wr=y(qr=>{"use strict";var Vr=x(),ll=L(),Mr="<<",Fr={identify:e=>e===Mr||typeof e=="symbol"&&e.description===Mr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ll.Scalar(Symbol(Mr)),{addToJSMap:ul}),stringify:()=>Mr},Xp=(e,t)=>(Fr.identify(t)||Vr.isScalar(t)&&(!t.type||t.type===ll.Scalar.PLAIN)&&Fr.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Fr.tag&&i.default);function ul(e,t,i){let r=dl(e,i);if(Vr.isSeq(r))for(let n of r.items)Ja(e,t,n);else if(Array.isArray(r))for(let n of r)Ja(e,t,n);else Ja(e,t,r)}function Ja(e,t,i){let r=dl(e,i);if(!Vr.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function dl(e,t){return e&&Vr.isAlias(t)?t.resolve(e.doc,e):t}qr.addMergeToJSMap=ul;qr.isMergeKey=Xp;qr.merge=Fr});var Ua=y(pl=>{"use strict";var Qp=za(),fl=Wr(),Zp=ki(),hl=x(),Ga=tt();function em(e,t,{key:i,value:r}){if(hl.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(fl.isMergeKey(e,i))fl.addMergeToJSMap(e,t,r);else{let n=Ga.toJS(i,"",e);if(t instanceof Map)t.set(n,Ga.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=tm(i,n,e),o=Ga.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function tm(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(hl.isNode(e)&&i?.doc){let r=Zp.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=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),Qp.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(t)}pl.addPairToJSMap=em});var at=y(Ka=>{"use strict";var ml=gi(),im=sl(),rm=Ua(),zr=x();function nm(e,t,i){let r=ml.createNode(e,void 0,i),n=ml.createNode(t,void 0,i);return new Jr(r,n)}var Jr=class e{constructor(t,i=null){Object.defineProperty(this,zr.NODE_TYPE,{value:zr.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return zr.isNode(i)&&(i=i.clone(t)),zr.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return rm.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?im.stringifyPair(this,t,i,r):JSON.stringify(this)}};Ka.Pair=Jr;Ka.createPair=nm});var Ya=y(gl=>{"use strict";var wt=x(),vl=ki(),Gr=wi();function am(e,t,i){return(t.inFlow??e.flow?sm:om)(e,t,i)}function om({comment:e,items:t},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 m=0;m<t.length;++m){let h=t[m],v=null;if(wt.isNode(h))!d&&h.spaceBefore&&u.push(""),Ur(i,u,h.commentBefore,d),h.comment&&(v=h.comment);else if(wt.isPair(h)){let w=wt.isNode(h.key)?h.key:null;w&&(!d&&w.spaceBefore&&u.push(""),Ur(i,u,w.commentBefore,d))}d=!1;let g=vl.stringify(h,f,()=>v=null,()=>d=!0);v&&(g+=Gr.lineComment(g,a,l(v))),d&&v&&(d=!1),u.push(r+g)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let m=1;m<u.length;++m){let h=u[m];p+=h?`
|
|
48
|
+
${c}${h}`:`
|
|
49
|
+
`}}return e?(p+=`
|
|
50
|
+
`+Gr.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function sm({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,f=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(wt.isNode(h))h.spaceBefore&&d.push(""),Ur(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(wt.isPair(h)){let w=wt.isNode(h.key)?h.key:null;w&&(w.spaceBefore&&d.push(""),Ur(t,d,w.commentBefore,!1),w.comment&&(l=!0));let N=wt.isNode(h.value)?h.value:null;N?(N.comment&&(v=N.comment),N.commentBefore&&(l=!0)):h.value==null&&w?.comment&&(v=w.comment)}v&&(l=!0);let g=vl.stringify(h,c,()=>v=null);l||(l=d.length>f||g.includes(`
|
|
51
|
+
`)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((w,N)=>w+N.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=Gr.lineComment(g,r,s(v))),d.push(g),f=d.length}let{start:u,end:p}=i;if(d.length===0)return u+p;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=u;for(let h of d)m+=h?`
|
|
52
|
+
${a}${n}${h}`:`
|
|
53
53
|
`;return`${m}
|
|
54
|
-
${
|
|
55
|
-
`:" ")}return
|
|
56
|
-
${
|
|
57
|
-
${a.comment}`:n.comment}n=r}e.items[i]=Ba.isPair(n)?n:new Sc.Pair(n)}}else t("Expected a sequence for this tag");return e}function Of(e,t,i){let{replacer:n}=i,r=new cb.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(Sc.createPair(s,c,i))}return r}var lb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:jf,createNode:Of};La.createPairs=Of;La.pairs=lb;La.resolvePairs=jf});var Rc=R(Cc=>{"use strict";var Hf=q(),Ec=Ht(),Yn=Lt(),ub=qt(),$f=qa(),pi=class e extends ub.YAMLSeq{constructor(){super(),this.add=Yn.YAMLMap.prototype.add.bind(this),this.delete=Yn.YAMLMap.prototype.delete.bind(this),this.get=Yn.YAMLMap.prototype.get.bind(this),this.has=Yn.YAMLMap.prototype.has.bind(this),this.set=Yn.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(Hf.isPair(r)?(a=Ec.toJS(r.key,"",i),o=Ec.toJS(r.value,a,i)):a=Ec.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=$f.createPairs(t,i,n),a=new this;return a.items=r.items,a}};pi.tag="tag:yaml.org,2002:omap";var db={collection:"seq",identify:e=>e instanceof Map,nodeClass:pi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=$f.resolvePairs(e,t),n=[];for(let{key:r}of i.items)Hf.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new pi,i)},createNode:(e,t,i)=>pi.from(e,t,i)};Cc.YAMLOMap=pi;Cc.omap=db});var Lf=R(Pc=>{"use strict";var Ff=ie();function Df({value:e,source:t},i){return t&&(e?Mf:Bf).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Mf={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 Ff.Scalar(!0),stringify:Df},Bf={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 Ff.Scalar(!1),stringify:Df};Pc.falseTag=Bf;Pc.trueTag=Mf});var qf=R(Va=>{"use strict";var fb=ie(),Ac=Zi(),hb={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:Ac.stringifyNumber},pb={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():Ac.stringifyNumber(e)}},mb={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 fb.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:Ac.stringifyNumber};Va.float=mb;Va.floatExp=pb;Va.floatNaN=hb});var Wf=R(Qn=>{"use strict";var Vf=Zi(),Xn=e=>typeof e=="bigint"||Number.isInteger(e);function Wa(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 xc(e,t,i){let{value:n}=e;if(Xn(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return Vf.stringifyNumber(e)}var vb={identify:Xn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Wa(e,2,2,i),stringify:e=>xc(e,2,"0b")},gb={identify:Xn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Wa(e,1,8,i),stringify:e=>xc(e,8,"0")},wb={identify:Xn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Wa(e,0,10,i),stringify:Vf.stringifyNumber},yb={identify:Xn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Wa(e,2,16,i),stringify:e=>xc(e,16,"0x")};Qn.int=wb;Qn.intBin=vb;Qn.intHex=yb;Qn.intOct=gb});var Tc=R(Ic=>{"use strict";var Ga=q(),za=Mt(),Ja=Lt(),mi=class e extends Ja.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Ga.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new za.Pair(t.key,null):i=new za.Pair(t,null),Ja.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=Ja.findPair(this.items,t);return!i&&Ga.isPair(n)?Ga.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=Ja.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new za.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(za.createPair(o,null,n));return a}};mi.tag="tag:yaml.org,2002:set";var Nb={collection:"map",identify:e=>e instanceof Set,nodeClass:mi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>mi.from(e,t,i),resolve(e,t){if(Ga.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new mi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ic.YAMLSet=mi;Ic.set=Nb});var jc=R(Ua=>{"use strict";var bb=Zi();function _c(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 zf(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return bb.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 kb={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})=>_c(e,i),stringify:zf},Sb={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=>_c(e,!1),stringify:zf},Jf={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(Jf.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=_c(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$/,"")??""};Ua.floatTime=Sb;Ua.intTime=kb;Ua.timestamp=Jf});var Kf=R(Uf=>{"use strict";var Eb=Xi(),Cb=Ha(),Rb=Qi(),Pb=Un(),Ab=kc(),Gf=Lf(),Oc=qf(),Ka=Wf(),xb=Pa(),Ib=Rc(),Tb=qa(),_b=Tc(),Hc=jc(),jb=[Eb.map,Rb.seq,Pb.string,Cb.nullTag,Gf.trueTag,Gf.falseTag,Ka.intBin,Ka.intOct,Ka.int,Ka.intHex,Oc.floatNaN,Oc.floatExp,Oc.float,Ab.binary,xb.merge,Ib.omap,Tb.pairs,_b.set,Hc.intTime,Hc.floatTime,Hc.timestamp];Uf.schema=jb});var ah=R(Dc=>{"use strict";var Zf=Xi(),Ob=Ha(),eh=Qi(),Hb=Un(),$b=pc(),$c=vc(),Fc=wc(),Fb=Af(),Db=Tf(),th=kc(),Zn=Pa(),ih=Rc(),nh=qa(),Yf=Kf(),rh=Tc(),Ya=jc(),Xf=new Map([["core",Fb.schema],["failsafe",[Zf.map,eh.seq,Hb.string]],["json",Db.schema],["yaml11",Yf.schema],["yaml-1.1",Yf.schema]]),Qf={binary:th.binary,bool:$b.boolTag,float:$c.float,floatExp:$c.floatExp,floatNaN:$c.floatNaN,floatTime:Ya.floatTime,int:Fc.int,intHex:Fc.intHex,intOct:Fc.intOct,intTime:Ya.intTime,map:Zf.map,merge:Zn.merge,null:Ob.nullTag,omap:ih.omap,pairs:nh.pairs,seq:eh.seq,set:rh.set,timestamp:Ya.timestamp},Mb={"tag:yaml.org,2002:binary":th.binary,"tag:yaml.org,2002:merge":Zn.merge,"tag:yaml.org,2002:omap":ih.omap,"tag:yaml.org,2002:pairs":nh.pairs,"tag:yaml.org,2002:set":rh.set,"tag:yaml.org,2002:timestamp":Ya.timestamp};function Bb(e,t,i){let n=Xf.get(t);if(n&&!e)return i&&!n.includes(Zn.merge)?n.concat(Zn.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(Xf.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(Zn.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Qf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Qf).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},[])}Dc.coreKnownTags=Mb;Dc.getTags=Bb});var Lc=R(oh=>{"use strict";var Mc=q(),Lb=Xi(),qb=Qi(),Vb=Un(),Xa=ah(),Wb=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Bc=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Xa.getTags(t,"compat"):t?Xa.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?Xa.coreKnownTags:{},this.tags=Xa.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Mc.MAP,{value:Lb.map}),Object.defineProperty(this,Mc.SCALAR,{value:Vb.string}),Object.defineProperty(this,Mc.SEQ,{value:qb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Wb:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};oh.Schema=Bc});var ch=R(sh=>{"use strict";var zb=q(),qc=zn(),er=Ln();function Jb(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=qc.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(er.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(zb.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(er.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=qc.stringify(e.contents,r,()=>s=null,c);s&&(l+=er.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(qc.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
54
|
+
${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function Ur({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Gr.indentComment(t(r),e);i.push(a.trimStart())}}gl.stringifyCollection=am});var st=y(Qa=>{"use strict";var cm=Ya(),lm=Ua(),um=$r(),ot=x(),Kr=at(),dm=L();function Ei(e,t){let i=ot.isScalar(t)?t.value:t;for(let r of e)if(ot.isPair(r)&&(r.key===t||r.key===i||ot.isScalar(r.key)&&r.key.value===i))return r}var Xa=class extends um.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ot.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Kr.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 t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;ot.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Kr.Pair(t,t?.value):r=new Kr.Pair(t.key,t.value);let n=Ei(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);ot.isScalar(n.value)&&dm.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(t){let i=Ei(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Ei(this.items,t)?.value;return(!i&&ot.isScalar(n)?n.value:n)??void 0}has(t){return!!Ei(this.items,t)}set(t,i){this.add(new Kr.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)lm.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!ot.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),cm.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Qa.YAMLMap=Xa;Qa.findPair=Ei});var Mt=y(yl=>{"use strict";var fm=x(),wl=st(),hm={collection:"map",default:!0,nodeClass:wl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return fm.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>wl.YAMLMap.from(e,t,i)};yl.map=hm});var ct=y(Nl=>{"use strict";var pm=gi(),mm=Ya(),vm=$r(),Xr=x(),gm=L(),wm=tt(),Za=class extends vm.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Xr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Yr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Yr(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Xr.isScalar(n)?n.value:n}has(t){let i=Yr(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Yr(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Xr.isScalar(n)&&gm.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(wm.toJS(a,String(n++),i));return r}toString(t,i,r){return t?mm.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);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(pm.createNode(s,void 0,r))}}return a}};function Yr(e){let t=Xr.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Nl.YAMLSeq=Za});var Ft=y(kl=>{"use strict";var ym=x(),bl=ct(),Nm={collection:"seq",default:!0,nodeClass:bl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return ym.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>bl.YAMLSeq.from(e,t,i)};kl.seq=Nm});var Pi=y(Sl=>{"use strict";var bm=bi(),km={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),bm.stringifyString(e,t,i,r)}};Sl.string=km});var Qr=y(xl=>{"use strict";var El=L(),Pl={identify:e=>e==null,createNode:()=>new El.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new El.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Pl.test.test(e)?e:t.options.nullStr};xl.nullTag=Pl});var eo=y(Cl=>{"use strict";var Sm=L(),Rl={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Sm.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Rl.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Cl.boolTag=Rl});var Vt=y(Al=>{"use strict";function Em({format:e,minFractionDigits:t,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(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Al.stringifyNumber=Em});var io=y(Zr=>{"use strict";var Pm=L(),to=Vt(),xm={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:to.stringifyNumber},Rm={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():to.stringifyNumber(e)}},Cm={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 Pm.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:to.stringifyNumber};Zr.float=Cm;Zr.floatExp=Rm;Zr.floatNaN=xm});var no=y(tn=>{"use strict";var _l=Vt(),en=e=>typeof e=="bigint"||Number.isInteger(e),ro=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Tl(e,t,i){let{value:r}=e;return en(r)&&r>=0?i+r.toString(t):_l.stringifyNumber(e)}var Am={identify:e=>en(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>ro(e,2,8,i),stringify:e=>Tl(e,8,"0o")},_m={identify:en,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>ro(e,0,10,i),stringify:_l.stringifyNumber},Tm={identify:e=>en(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>ro(e,2,16,i),stringify:e=>Tl(e,16,"0x")};tn.int=_m;tn.intHex=Tm;tn.intOct=Am});var jl=y(Il=>{"use strict";var Im=Mt(),jm=Qr(),$m=Ft(),Om=Pi(),Hm=eo(),ao=io(),oo=no(),Dm=[Im.map,$m.seq,Om.string,jm.nullTag,Hm.boolTag,oo.intOct,oo.int,oo.intHex,ao.floatNaN,ao.floatExp,ao.float];Il.schema=Dm});var Hl=y(Ol=>{"use strict";var Bm=L(),Lm=Mt(),Mm=Ft();function $l(e){return typeof e=="bigint"||Number.isInteger(e)}var rn=({value:e})=>JSON.stringify(e),Fm=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:rn},{identify:e=>e==null,createNode:()=>new Bm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:rn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:rn},{identify:$l,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>$l(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:rn}],Vm={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},qm=[Lm.map,Mm.seq].concat(Fm,Vm);Ol.schema=qm});var co=y(Dl=>{"use strict";var xi=Pr("buffer"),so=L(),Wm=bi(),zm={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof xi.Buffer=="function")return xi.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.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 t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof xi.Buffer=="function")s=o instanceof xi.Buffer?o.toString("base64"):xi.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=so.Scalar.BLOCK_LITERAL),t!==so.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(t===so.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return Wm.stringifyString({comment:e,type:t,value:s},r,n,a)}};Dl.binary=zm});var on=y(an=>{"use strict";var nn=x(),lo=at(),Jm=L(),Gm=ct();function Bl(e,t){if(nn.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!nn.isPair(r)){if(nn.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new lo.Pair(new Jm.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}e.items[i]=nn.isPair(r)?r:new lo.Pair(r)}}else t("Expected a sequence for this tag");return e}function Ll(e,t,i){let{replacer:r}=i,n=new Gm.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.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;n.items.push(lo.createPair(s,c,i))}return n}var Um={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Bl,createNode:Ll};an.createPairs=Ll;an.pairs=Um;an.resolvePairs=Bl});var ho=y(fo=>{"use strict";var Ml=x(),uo=tt(),Ri=st(),Km=ct(),Fl=on(),yt=class e extends Km.YAMLSeq{constructor(){super(),this.add=Ri.YAMLMap.prototype.add.bind(this),this.delete=Ri.YAMLMap.prototype.delete.bind(this),this.get=Ri.YAMLMap.prototype.get.bind(this),this.has=Ri.YAMLMap.prototype.has.bind(this),this.set=Ri.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(Ml.isPair(n)?(a=uo.toJS(n.key,"",i),o=uo.toJS(n.value,a,i)):a=uo.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=Fl.createPairs(t,i,r),a=new this;return a.items=n.items,a}};yt.tag="tag:yaml.org,2002:omap";var Ym={collection:"seq",identify:e=>e instanceof Map,nodeClass:yt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Fl.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Ml.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new yt,i)},createNode:(e,t,i)=>yt.from(e,t,i)};fo.YAMLOMap=yt;fo.omap=Ym});var Jl=y(po=>{"use strict";var Vl=L();function ql({value:e,source:t},i){return t&&(e?Wl:zl).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Wl={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 Vl.Scalar(!0),stringify:ql},zl={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 Vl.Scalar(!1),stringify:ql};po.falseTag=zl;po.trueTag=Wl});var Gl=y(sn=>{"use strict";var Xm=L(),mo=Vt(),Qm={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:mo.stringifyNumber},Zm={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():mo.stringifyNumber(e)}},ev={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 Xm.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:mo.stringifyNumber};sn.float=ev;sn.floatExp=Zm;sn.floatNaN=Qm});var Kl=y(Ai=>{"use strict";var Ul=Vt(),Ci=e=>typeof e=="bigint"||Number.isInteger(e);function cn(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){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 n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function vo(e,t,i){let{value:r}=e;if(Ci(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Ul.stringifyNumber(e)}var tv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>cn(e,2,2,i),stringify:e=>vo(e,2,"0b")},iv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>cn(e,1,8,i),stringify:e=>vo(e,8,"0")},rv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>cn(e,0,10,i),stringify:Ul.stringifyNumber},nv={identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>cn(e,2,16,i),stringify:e=>vo(e,16,"0x")};Ai.int=rv;Ai.intBin=tv;Ai.intHex=nv;Ai.intOct=iv});var wo=y(go=>{"use strict";var dn=x(),ln=at(),un=st(),Nt=class e extends un.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;dn.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new ln.Pair(t.key,null):i=new ln.Pair(t,null),un.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=un.findPair(this.items,t);return!i&&dn.isPair(r)?dn.isScalar(r.key)?r.key.value:r.key:r}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 r=un.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new ln.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(ln.createPair(o,null,r));return a}};Nt.tag="tag:yaml.org,2002:set";var av={collection:"map",identify:e=>e instanceof Set,nodeClass:Nt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Nt.from(e,t,i),resolve(e,t){if(dn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Nt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};go.YAMLSet=Nt;go.set=av});var No=y(fn=>{"use strict";var ov=Vt();function yo(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?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 Yl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ov.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var sv={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})=>yo(e,i),stringify:Yl},cv={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=>yo(e,!1),stringify:Yl},Xl={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(Xl.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let d=yo(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};fn.floatTime=cv;fn.intTime=sv;fn.timestamp=Xl});var eu=y(Zl=>{"use strict";var lv=Mt(),uv=Qr(),dv=Ft(),fv=Pi(),hv=co(),Ql=Jl(),bo=Gl(),hn=Kl(),pv=Wr(),mv=ho(),vv=on(),gv=wo(),ko=No(),wv=[lv.map,dv.seq,fv.string,uv.nullTag,Ql.trueTag,Ql.falseTag,hn.intBin,hn.intOct,hn.int,hn.intHex,bo.floatNaN,bo.floatExp,bo.float,hv.binary,pv.merge,mv.omap,vv.pairs,gv.set,ko.intTime,ko.floatTime,ko.timestamp];Zl.schema=wv});var uu=y(Po=>{"use strict";var nu=Mt(),yv=Qr(),au=Ft(),Nv=Pi(),bv=eo(),So=io(),Eo=no(),kv=jl(),Sv=Hl(),ou=co(),_i=Wr(),su=ho(),cu=on(),tu=eu(),lu=wo(),pn=No(),iu=new Map([["core",kv.schema],["failsafe",[nu.map,au.seq,Nv.string]],["json",Sv.schema],["yaml11",tu.schema],["yaml-1.1",tu.schema]]),ru={binary:ou.binary,bool:bv.boolTag,float:So.float,floatExp:So.floatExp,floatNaN:So.floatNaN,floatTime:pn.floatTime,int:Eo.int,intHex:Eo.intHex,intOct:Eo.intOct,intTime:pn.intTime,map:nu.map,merge:_i.merge,null:yv.nullTag,omap:su.omap,pairs:cu.pairs,seq:au.seq,set:lu.set,timestamp:pn.timestamp},Ev={"tag:yaml.org,2002:binary":ou.binary,"tag:yaml.org,2002:merge":_i.merge,"tag:yaml.org,2002:omap":su.omap,"tag:yaml.org,2002:pairs":cu.pairs,"tag:yaml.org,2002:set":lu.set,"tag:yaml.org,2002:timestamp":pn.timestamp};function Pv(e,t,i){let r=iu.get(t);if(r&&!e)return i&&!r.includes(_i.merge)?r.concat(_i.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(iu.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)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(_i.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?ru[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(ru).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},[])}Po.coreKnownTags=Ev;Po.getTags=Pv});var Co=y(du=>{"use strict";var xo=x(),xv=Mt(),Rv=Ft(),Cv=Pi(),mn=uu(),Av=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Ro=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?mn.getTags(t,"compat"):t?mn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?mn.coreKnownTags:{},this.tags=mn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,xo.MAP,{value:xv.map}),Object.defineProperty(this,xo.SCALAR,{value:Cv.string}),Object.defineProperty(this,xo.SEQ,{value:Rv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Av:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};du.Schema=Ro});var hu=y(fu=>{"use strict";var _v=x(),Ao=ki(),Ti=wi();function Tv(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=Ao.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Ti.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(_v.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);i.push(Ti.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ao.stringify(e.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(Ao.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(Ti.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(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
|
+
`}fu.stringifyDocument=Tv});var Ii=y(pu=>{"use strict";var Iv=vi(),qt=$r(),le=x(),jv=at(),$v=tt(),Ov=Co(),Hv=hu(),_o=_r(),Dv=ja(),Bv=gi(),To=Ia(),Io=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,le.NODE_TYPE,{value:le.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 To.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[le.NODE_TYPE]:{value:le.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=le.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Wt(this.contents)&&this.contents.add(t)}addIn(t,i){Wt(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=_o.anchorNames(this);t.anchor=!i||r.has(i)?_o.findNewAnchor(i||"a",r):i}return new Iv.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let v=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=i.filter(v).map(String);g.length>0&&(i=i.concat(g)),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}=_o.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Bv.createNode(t,f,m);return s&&le.isCollection(h)&&(h.flow=!0),u(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new jv.Pair(n,a)}delete(t){return Wt(this.contents)?this.contents.delete(t):!1}deleteIn(t){return qt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Wt(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return le.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return qt.isEmptyPath(t)?!i&&le.isScalar(this.contents)?this.contents.value:this.contents:le.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return le.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return qt.isEmptyPath(t)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=qt.collectionFromPath(this.schema,[t],i):Wt(this.contents)&&this.contents.set(t,i)}setIn(t,i){qt.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=qt.collectionFromPath(this.schema,Array.from(t),i):Wt(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new To.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new To.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);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 Ov.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=$v.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"?Dv.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Hv.stringifyDocument(this,t)}};function Wt(e){if(le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}pu.Document=Io});var Oi=y($i=>{"use strict";var ji=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},jo=class extends ji{constructor(t,i,r){super("YAMLParseError",t,i,r)}},$o=class extends ji{constructor(t,i,r){super("YAMLWarning",t,i,r)}},Lv=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.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=e.substring(t.lineStarts[r-2],t.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(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(
|
|
67
|
-
`+
|
|
68
|
-
`+N.comment:
|
|
69
|
-
`+
|
|
70
|
-
`+
|
|
71
|
-
`+
|
|
72
|
-
`+
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",
|
|
74
|
-
`;for(let
|
|
75
|
-
`):
|
|
76
|
-
`:!
|
|
77
|
-
`&&(
|
|
78
|
-
|
|
79
|
-
`),d+=
|
|
80
|
-
`,
|
|
65
|
+
`}};$i.YAMLError=ji;$i.YAMLParseError=jo;$i.YAMLWarning=$o;$i.prettifyError=Lv});var Hi=y(mu=>{"use strict";function Mv(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,m=!1,h=null,v=null,g=null,w=null,N=null,k=null,E=null;for(let b of e)switch(m&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),f=!0;break;case"comment":{f||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let O=b.source.substring(1)||" ";d?d+=u+O:d=O,u="",l=!1;break}case"newline":l?d?d+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=b.source,l=!0,p=!0,(v||g)&&(w=b),f=!0;break;case"anchor":v&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=b,E??(E=b.offset),l=!1,f=!1,m=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,E??(E=b.offset),l=!1,f=!1,m=!0;break}case i:(v||g)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),k=b,l=i==="seq-item-ind"||i==="explicit-key-ind",f=!1;break;case"comma":if(t){N&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=b,l=!1,f=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let S=e[e.length-1],R=S?S.offset+S.source.length:n;return m&&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:N,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:v,tag:g,newlineAfterProp:w,end:R,start:E??R}}mu.resolveProps=Mv});var vn=y(vu=>{"use strict";function Oo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(Oo(t.key)||Oo(t.value))return!0}return!1;default:return!0}}vu.containsNewline=Oo});var Ho=y(gu=>{"use strict";var Fv=vn();function Vv(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&Fv.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}gu.flowIndentCheck=Vv});var Do=y(yu=>{"use strict";var wu=x();function qv(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||wu.isScalar(a)&&wu.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}yu.mapIncludes=qv});var Pu=y(Eu=>{"use strict";var Nu=at(),Wv=st(),bu=Hi(),zv=vn(),ku=Ho(),Jv=Do(),Su="All mapping items must start at the same column";function Gv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Wv.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:m}=f,h=bu.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),v=!h.found;if(v){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",Su)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||zv.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",Su);i.atKey=!0;let g=h.end,w=u?e(i,u,h,n):t(i,g,d,null,h,n);i.schema.compat&&ku.flowIndentCheck(r.indent,u,n),i.atKey=!1,Jv.mapIncludes(i,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let N=bu.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=N.end,N.found){v&&(m?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<N.found.offset-1024&&n(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=m?e(i,m,N,n):t(i,c,p,null,N,n);i.schema.compat&&ku.flowIndentCheck(r.indent,m,n),c=k.range[2];let E=new Nu.Pair(w,k);i.options.keepSourceTokens&&(E.srcToken=f),s.items.push(E)}else{v&&n(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(w.comment?w.comment+=`
|
|
68
|
+
`+N.comment:w.comment=N.comment);let k=new Nu.Pair(w);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}Eu.resolveBlockMap=Gv});var Ru=y(xu=>{"use strict";var Uv=ct(),Kv=Hi(),Yv=Ho();function Xv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Uv.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=Kv.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?e(i,d,u,n):t(i,u.end,f,null,u,n);i.schema.compat&&Yv.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}xu.resolveBlockSeq=Xv});var zt=y(Cu=>{"use strict";function Qv(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&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`)}t+=c.length}}return{comment:n,offset:t}}Cu.resolveEnd=Qv});var Iu=y(Tu=>{"use strict";var Zv=x(),eg=at(),Au=st(),tg=ct(),ig=zt(),_u=Hi(),rg=vn(),ng=Do(),Bo="Block collections are not allowed within flow collections",Lo=e=>e&&(e.type==="block-map"||e.type==="block-seq");function ag({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Au.YAMLMap:tg.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 v=0;v<r.items.length;++v){let g=r.items[v],{start:w,key:N,sep:k,value:E}=g,S=_u.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:N??k?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!k&&!E){v===0&&S.comma?n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<r.items.length-1&&n(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),S.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+S.comment:l.comment=S.comment),d=S.end;continue}!o&&i.options.strict&&rg.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)S.comma&&n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(S.comma||n(S.start,"MISSING_CHAR",`Missing , between ${s} items`),S.comment){let R="";e:for(let b of w)switch(b.type){case"comma":case"space":break;case"comment":R=b.source.substring(1);break e;default:break e}if(R){let b=l.items[l.items.length-1];Zv.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
|
|
70
|
+
`+R:b.comment=R,S.comment=S.comment.substring(R.length+1)}}if(!o&&!k&&!S.found){let R=E?e(i,E,S,n):t(i,S.end,k,null,S,n);l.items.push(R),d=R.range[2],Lo(E)&&n(R.range,"BLOCK_IN_FLOW",Bo)}else{i.atKey=!0;let R=S.end,b=N?e(i,N,S,n):t(i,R,w,null,S,n);Lo(N)&&n(b.range,"BLOCK_IN_FLOW",Bo),i.atKey=!1;let O=_u.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:E,offset:b.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(O.found){if(!o&&!S.found&&i.options.strict){if(k)for(let M of k){if(M===O.found)break;if(M.type==="newline"){n(M,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<O.found.offset-1024&&n(O.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(O.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Ie=E?e(i,E,O,n):O.found?t(i,O.end,k,null,O,n):null;Ie?Lo(E)&&n(Ie.range,"BLOCK_IN_FLOW",Bo):O.comment&&(b.comment?b.comment+=`
|
|
71
|
+
`+O.comment:b.comment=O.comment);let ze=new eg.Pair(b,Ie);if(i.options.keepSourceTokens&&(ze.srcToken=g),o){let M=l;ng.mapIncludes(i,M.items,b)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),M.items.push(ze)}else{let M=new Au.YAMLMap(i.schema);M.flow=!0,M.items.push(ze);let Tc=(Ie??b).range;M.range=[b.range[0],Tc[1],Tc[2]],l.items.push(M)}d=Ie?Ie.range[2]:O.end}}let u=o?"}":"]",[p,...m]=r.end,h=d;if(p?.source===u)h=p.offset+p.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=f?`${v} must end with a ${u}`:`${v} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",g),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=ig.resolveEnd(m,h,i.options.strict,n);v.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+v.comment:l.comment=v.comment),l.range=[r.offset,h,v.offset]}else l.range=[r.offset,h,h];return l}Tu.resolveFlowCollection=ag});var $u=y(ju=>{"use strict";var og=x(),sg=L(),cg=st(),lg=ct(),ug=Pu(),dg=Ru(),fg=Iu();function Mo(e,t,i,r,n,a){let o=i.type==="block-map"?ug.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?dg.resolveBlockSeq(e,t,i,r,a):fg.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function hg(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,m=u&&a?u.offset>a.offset?u:a:u??a;m&&(!p||p.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===cg.YAMLMap.tagName&&s==="map"||o===lg.YAMLSeq.tagName&&s==="seq")return Mo(e,t,i,n,o);let c=t.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.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),Mo(e,t,i,n,o)}let l=Mo(e,t,i,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,d=og.isNode(f)?f:new sg.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ju.composeCollection=hg});var Vo=y(Ou=>{"use strict";var Fo=L();function pg(e,t,i){let r=t.offset,n=mg(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Fo.Scalar.BLOCK_FOLDED:Fo.Scalar.BLOCK_LITERAL,o=t.source?vg(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",v=r+n.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let h=0;h<s;++h){let[v,g]=o[h];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&i(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),f=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.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[v,g]=o[h];l+=v.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&v.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-g.length-(w?2:1),"BAD_INDENT",k),v=""}a===Fo.Scalar.BLOCK_LITERAL?(d+=u+v.slice(c)+g,u=`
|
|
75
|
+
`):v.length>c||g[0]===" "?(u===" "?u=`
|
|
76
|
+
`:!p&&u===`
|
|
77
|
+
`&&(u=`
|
|
78
|
+
|
|
79
|
+
`),d+=u+v.slice(c)+g,u=`
|
|
80
|
+
`,p=!0):g===""?u===`
|
|
81
81
|
`?d+=`
|
|
82
|
-
`:
|
|
83
|
-
`:(d+=
|
|
84
|
-
`+o[
|
|
82
|
+
`:u=`
|
|
83
|
+
`:(d+=u+g,u=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
|
|
84
|
+
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let m=n
|
|
87
|
+
`}let m=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,m,m]}}function mg({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[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 m=Number(p);!o&&m?o=m:c===-1&&(c=e+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<t.length;++u){let p=t[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 m=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:d}}function vg(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Ou.resolveBlockScalar=pg});var Wo=y(Du=>{"use strict";var qo=L(),gg=zt();function wg(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(u,p,m)=>i(r+u,p,m);switch(n){case"scalar":s=qo.Scalar.PLAIN,c=yg(a,l);break;case"single-quoted-scalar":s=qo.Scalar.QUOTE_SINGLE,c=Ng(a,l);break;case"double-quoted-scalar":s=qo.Scalar.QUOTE_DOUBLE,c=bg(a,l);break;default:return i(e,"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=gg.resolveEnd(o,f,t,i);return{value:c,type:s,comment:d.comment,range:[r,f,d.offset]}}function yg(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),Hu(e)}function Ng(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Hu(e.slice(1,-1)).replace(/''/g,"'")}function Hu(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
-
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let
|
|
90
|
-
`?
|
|
91
|
-
`:(
|
|
92
|
-
`))if(
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
94
|
-
`)for(a=e[
|
|
95
|
-
`)for(a=e[++
|
|
96
|
-
`&&!(o==="\r"&&e[
|
|
97
|
-
`)&&(i+=
|
|
98
|
-
`||
|
|
99
|
-
`);)
|
|
89
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)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(e),n+a+(r?.[1]??"")}function bg(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
|
|
92
|
+
`))if(n===`
|
|
93
|
+
`){let{fold:a,offset:o}=kg(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Sg[a];if(o)i+=o;else if(a===`
|
|
94
|
+
`)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
|
|
95
|
+
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=Eg(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
|
|
96
|
+
`&&!(o==="\r"&&e[r+2]===`
|
|
97
|
+
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function kg(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
98
|
+
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
99
|
+
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
|
-
`),t+=1,
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Sg={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Eg(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Du.resolveFlowScalar=wg});var Mu=y(Lu=>{"use strict";var bt=x(),Bu=L(),Pg=Vo(),xg=Wo();function Rg(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Pg.resolveBlockScalar(e,t,r):xg.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[bt.SCALAR]:c?l=Cg(e.schema,n,c,i,r):t.type==="scalar"?l=Ag(e,n,t,r):l=e.schema[bt.SCALAR];let f;try{let d=l.resolve(n,u=>r(i??t,"TAG_RESOLVE_FAILED",u),e.options);f=bt.isScalar(d)?d:new Bu.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",u),f=new Bu.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 Cg(e,t,i,r,n){if(i==="!")return e[bt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[bt.SCALAR])}function Ag({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[bt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[bt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}Lu.composeScalar=Rg});var Vu=y(Fu=>{"use strict";function _g(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}Fu.emptyScalarPosition=_g});var zu=y(Jo=>{"use strict";var Tg=vi(),Ig=x(),jg=$u(),qu=Mu(),$g=zt(),Og=Vu(),Hg={composeNode:Wu,composeEmptyNode:zo};function Wu(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,f=!0;switch(t.type){case"alias":l=Dg(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=qu.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=jg.composeCollection(Hg,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",u)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=zo(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Ig.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function zo(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Og.emptyScalarPosition(t,i,r),indent:-1,source:""},d=qu.composeScalar(e,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 Dg({options:e},{offset:t,source:i,end:r},n){let a=new Tg.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=$g.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Jo.composeEmptyNode=zo;Jo.composeNode=Wu});var Uu=y(Gu=>{"use strict";var Bg=Ii(),Ju=zu(),Lg=zt(),Mg=Hi();function Fg(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Bg.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Mg.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?Ju.composeNode(l,n,f,o):Ju.composeEmptyNode(l,f.end,r,null,f,o);let d=c.contents.range[2],u=Lg.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,d,u.offset],c}Gu.composeDoc=Fg});var Uo=y(Xu=>{"use strict";var Vg=Pr("process"),qg=Ia(),Wg=Ii(),Di=Oi(),Ku=x(),zg=Uu(),Jg=zt();function Bi(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function Yu(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":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"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Go=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Bi(i);a?this.warnings.push(new Di.YAMLWarning(o,r,n)):this.errors.push(new Di.YAMLParseError(o,r,n))},this.directives=new qg.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Yu(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Ku.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ku.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)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Yu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(Vg.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=Bi(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=zg.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new Di.YAMLParseError(Bi(t),"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 Di.YAMLParseError(Bi(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Jg.resolveEnd(t.end,t.offset+t.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 Di.YAMLParseError(Bi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new Wg.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}}};Xu.Composer=Go});var ed=y(gn=>{"use strict";var Gg=Vo(),Ug=Wo(),Kg=Oi(),Qu=bi();function Yg(e,t=!0,i){if(e){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 Kg.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ug.resolveFlowScalar(e,t,r);case"block-scalar":return Gg.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Xg(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Qu.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.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(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=
|
|
116
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:i,source:t,end:[
|
|
111
|
+
`),f=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
+
`,u=[{type:"block-scalar-header",offset:a,indent:r,source:f}];return Zu(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 Qg(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Qu.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Zg(e,c);break;case'"':Ko(e,c,"double-quoted-scalar");break;case"'":Ko(e,c,"single-quoted-scalar");break;default:Ko(e,c,"scalar")}}function Zg(e,t){let i=t.indexOf(`
|
|
114
|
+
`),r=t.substring(0,i),n=t.substring(i+1)+`
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Zu(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Zu(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Ko(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}gn.createScalarToken=Xg;gn.resolveAsScalar=Yg;gn.setScalarValue=Qg});var id=y(td=>{"use strict";var ew=e=>"type"in e?yn(e):wn(e);function yn(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=yn(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=wn(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=wn(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=wn(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function wn({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=yn(t)),i)for(let a of i)n+=a.source;return r&&(n+=yn(r)),n}td.stringify=ew});var od=y(ad=>{"use strict";var Yo=Symbol("break visit"),tw=Symbol("skip children"),rd=Symbol("remove item");function kt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),nd(Object.freeze([]),e,t)}kt.BREAK=Yo;kt.SKIP=tw;kt.REMOVE=rd;kt.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};kt.parentCollection=(e,t)=>{let i=kt.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function nd(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=nd(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Yo)return Yo;s===rd&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}ad.visit=kt});var Nn=y(ee=>{"use strict";var Xo=ed(),iw=id(),rw=od(),Qo="\uFEFF",Zo="",es="",ts="",nw=e=>!!e&&"items"in e,aw=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function ow(e){switch(e){case Qo:return"<BOM>";case Zo:return"<DOC>";case es:return"<FLOW_END>";case ts:return"<SCALAR>";default:return JSON.stringify(e)}}function sw(e){switch(e){case Qo:return"byte-order-mark";case Zo:return"doc-mode";case es:return"flow-error-end";case ts: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(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ee.createScalarToken=Xo.createScalarToken;ee.resolveAsScalar=Xo.resolveAsScalar;ee.setScalarValue=Xo.setScalarValue;ee.stringify=iw.stringify;ee.visit=rw.visit;ee.BOM=Qo;ee.DOCUMENT=Zo;ee.FLOW_END=es;ee.SCALAR=ts;ee.isCollection=nw;ee.isScalar=aw;ee.prettyToken=ow;ee.tokenType=sw});var ns=y(cd=>{"use strict";var Li=Nn();function be(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var sd=new Set("0123456789ABCDEFabcdef"),cw=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),bn=new Set(",[]{}"),lw=new Set(` ,[]{}
|
|
121
|
+
\r `),is=e=>!e||lw.has(e),rs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
|
-
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let
|
|
124
|
-
`||!
|
|
125
|
-
`||
|
|
126
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
127
|
-
`,this.pos);if(
|
|
128
|
-
`,a)}
|
|
123
|
+
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
124
|
+
`||!n&&!this.atEnd)return t+r+1}return i===`
|
|
125
|
+
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&be(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Li.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield Li.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&be(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&&!be(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&be(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 t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(is),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+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("..."))&&be(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(is),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||be(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let 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 t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>be(i)||i==="#")}*parseBlockScalar(){let t=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
129
|
`:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
|
-
`)break}default:break e}if(!
|
|
131
|
-
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let
|
|
132
|
-
`;)
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield
|
|
134
|
-
`?(
|
|
135
|
-
`,a=this.buffer[
|
|
136
|
-
`){let o=this.continueScalar(
|
|
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(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
|
+
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
|
+
`;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield Li.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=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(be(a)||t&&bn.has(a))break;i=r}else if(be(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
|
+
`?(r+=1,n=`
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||t&&bn.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&bn.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Li.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(is),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(be(r)||i&&bn.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!be(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(cw.has(i))i=this.buffer[++t];else if(i==="%"&&sd.has(this.buffer[t+1])&&sd.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};cd.Lexer=rs});var os=y(ld=>{"use strict";var as=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};ld.LineCounter=as});var cs=y(pd=>{"use strict";var uw=Pr("process"),ud=Nn(),dw=ns();function lt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function dd(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function hd(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function kn(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Jt(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Sn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function fd(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!lt(t.start,"explicit-key-ind")&&!lt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,hd(t.value)?t.value.end?Sn(t.value.end,t.sep):t.value.end=t.sep:Sn(t.start,t.sep),delete t.sep)}var ss=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new dw.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,uw.env.LOG_TOKENS&&console.log("|",ud.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=ud.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let 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"&&fd(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&&dd(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 t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{dd(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let i=kn(this.peek(2)),r=Jt(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let 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):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Sn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.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>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(lt(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(hd(i.key)&&!lt(i.sep,"newline")){let o=Jt(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(lt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Jt(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?t.items.push({start:a,key:null,sep:[this.sourceToken]}):lt(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!lt(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let 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):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Sn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||lt(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.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(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.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":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);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===t.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=kn(r),a=Jt(n);fd(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
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=ro(t),n=rn(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=ro(t),n=rn(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())}}};lp.Parser=Nl});var pp=R(ur=>{"use strict";var up=sl(),PS=tr(),lr=rr(),AS=ac(),xS=q(),IS=yl(),dp=bl();function fp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new IS.LineCounter||null,prettyErrors:t}}function TS(e,t={}){let{lineCounter:i,prettyErrors:n}=fp(t),r=new dp.Parser(i?.addNewLine),a=new up.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(lr.prettifyError(e,i)),s.warnings.forEach(lr.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function hp(e,t={}){let{lineCounter:i,prettyErrors:n}=fp(t),r=new dp.Parser(i?.addNewLine),a=new up.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 lr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(lr.prettifyError(e,i)),o.warnings.forEach(lr.prettifyError(e,i))),o}function _S(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=hp(e,i);if(!r)return null;if(r.warnings.forEach(a=>AS.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 jS(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 xS.isDocument(e)&&!n?e.toString(i):new PS.Document(e,n,i).toString(i)}ur.parse=_S;ur.parseAllDocuments=TS;ur.parseDocument=hp;ur.stringify=jS});var so=R(z=>{"use strict";var OS=sl(),HS=tr(),$S=Lc(),kl=rr(),FS=Mn(),Wt=q(),DS=Mt(),MS=ie(),BS=Lt(),LS=qt(),qS=io(),VS=gl(),WS=yl(),zS=bl(),oo=pp(),mp=Hn();z.Composer=OS.Composer;z.Document=HS.Document;z.Schema=$S.Schema;z.YAMLError=kl.YAMLError;z.YAMLParseError=kl.YAMLParseError;z.YAMLWarning=kl.YAMLWarning;z.Alias=FS.Alias;z.isAlias=Wt.isAlias;z.isCollection=Wt.isCollection;z.isDocument=Wt.isDocument;z.isMap=Wt.isMap;z.isNode=Wt.isNode;z.isPair=Wt.isPair;z.isScalar=Wt.isScalar;z.isSeq=Wt.isSeq;z.Pair=DS.Pair;z.Scalar=MS.Scalar;z.YAMLMap=BS.YAMLMap;z.YAMLSeq=LS.YAMLSeq;z.CST=qS;z.Lexer=VS.Lexer;z.LineCounter=WS.LineCounter;z.Parser=zS.Parser;z.parse=oo.parse;z.parseAllDocuments=oo.parseAllDocuments;z.parseDocument=oo.parseDocument;z.stringify=oo.stringify;z.visit=mp.visit;z.visitAsync=mp.visitAsync});import{promises as wu}from"fs";import Gm from"path";var Ko=qs(so(),1);import{promises as Bm}from"fs";import St from"path";import{createHash as KS}from"node:crypto";import{promises as Ke}from"node:fs";import He from"node:path";import{TextDecoder as YS}from"node:util";import Sl from"path";var JS=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),GS=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function US(e){return e.toLowerCase().startsWith(".env")}function dt(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>US(n))?"environment-file":i.some(n=>GS.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>JS.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function dr(e,t){let i=dt(t);if(i)return i;let n=Sl.resolve(e.projectRoot,...t.split("/")),r=Sl.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Sl.resolve(e.configFile)?"native-runtime":null}function zt(e){return e!==0&&e!==0n&&e!=="0"}function fe(e,t){return zt(e.dev)&&zt(t.dev)&&zt(e.ino)&&zt(t.ino)}function M(e,t){let i=zt(e.dev)&&zt(t.dev);if(i&&e.dev!==t.dev)return!1;let n=zt(e.ino)&&zt(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var fr=1024*1024;function El(e,t){let i=He.relative(e,t);return i===""||!He.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${He.sep}`)}function XS(e){let t=He.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})||He.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=dt(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 QS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ZS(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function co(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return fe(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function vp(e){let t=await Ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function eE(e,t){let i=He.resolve(e),n=He.resolve(t);if(!El(i,n))throw new Error("Native artifact path is outside its root");let r=[await vp(i)],a=i;for(let o of He.relative(i,n).split(He.sep).filter(Boolean)){a=He.join(a,o);let s=await vp(a);if(!El(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function gp(e){for(let t of e){let i=await Ke.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!ZS(t,i)||await Ke.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function he(e){let t=XS(e.ref),i=QS(e.maxBytes??fr),n=He.resolve(e.root,...t.split("/")),r=await eE(e.root,He.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Ke.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 Ke.realpath(n);if(!El(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ke.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ke.lstat(n),Ke.realpath(n)]);if(await gp(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!co(a,c)||!co(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let N=i+1-f,b=await s.read(h,0,Math.min(h.length,N),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(h.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,g]=await Promise.all([s.stat(),Ke.lstat(n),Ke.realpath(n)]);if(await gp(r),!p.isFile()||p.isSymbolicLink()||g!==o||!co(c,m)||!co(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),k;try{k=new YS("utf-8",{fatal:!0}).decode(S)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:KS("sha256").update(S).digest("hex"),text:k}}finally{await s.close()}}import{randomUUID as tE}from"crypto";import{promises as pe}from"fs";import Ye from"path";function Rl(e,t){let i=Ye.relative(e,t);return i===""||!Ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ye.sep}`)}function iE(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cl(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return fe(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function wp(e){let t=await pe.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 pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function hr(e){for(let t of e){let i=await pe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!iE(t,i)||await pe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function nE(e,t){let i=Ye.resolve(e),n=Ye.resolve(t);if(!Rl(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await wp(i)],a=Ye.relative(i,n).split(Ye.sep).filter(Boolean),o=i;for(let s of a){await hr(r),o=Ye.join(o,s);try{await pe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await wp(o);if(!Rl(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await hr(r),r}async function rE(e){let t;try{t=await pe.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 aE(e,t,i={}){let n=Ye.dirname(e),r=i.containedRoot?await nE(i.containedRoot,n):null;r||await pe.mkdir(n,{recursive:!0});let a=Ye.join(n,`.${Ye.basename(e)}.${tE()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await pe.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([pe.lstat(a),pe.realpath(a)]);if(await hr(r),!c.isFile()||c.isSymbolicLink()||!Cl(s,c)||!Rl(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(),!Cl(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 hr(r);let c=await pe.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Cl(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await pe.link(a,e),await pe.unlink(a)):await pe.rename(a,e),await rE(n)}catch(c){if(await o?.close(),!r)await pe.rm(a,{force:!0});else try{await hr(r),await pe.rm(a,{force:!0})}catch{}throw c}}async function wi(e,t,i={}){await aE(e,t,i)}async function Pe(e,t,i={}){await wi(e,JSON.stringify(t,null,2)+`
|
|
143
|
-
`,i)}var Al=qs(so(),1);import lo from"path";var mr=64*1024,uo=1024,fo=64,ho=5,oE=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],ke={include:["**/*"],exclude:[...oE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function sE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||lo.posix.isAbsolute(i)||lo.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 yi(e){let t=sE(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Np(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 xl(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||lo.posix.isAbsolute(n)||lo.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 pr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function bp(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 po(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>uo)throw new Error(`${t} exceeds ${uo} 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>fo)throw new Error(`${t} contains more than ${fo} wildcard tokens`);return e}function yp(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=>po(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function Pl(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 cE(e){if(e===void 0)return{...ke,include:[...ke.include],exclude:[...ke.exclude]};let t=pr(e,"native.snapshot");return{include:yp(t.include,"native.snapshot.include",ke.include),exclude:yp(t.exclude,"native.snapshot.exclude",ke.exclude),max_files:Pl(t.max_files,ke.max_files,"native.snapshot.max_files"),max_total_bytes:Pl(t.max_total_bytes,ke.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Pl(t.max_duration_ms,ke.max_duration_ms,"native.snapshot.max_duration_ms")}}function lE(e){if(e===void 0)return;let t=pr(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=pr(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:yi(n),toArtifactRoot:yi(r),stage:a,...o?{cleanup:o}:{}}}function uE(e,t={}){let i=pr(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??ho;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=lE(i.pending_root_move);return{artifact_root:yi(n),language:bp(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:cE(i.snapshot),...s?{pending_root_move:s}:{}}}function dE(e){let t=pr(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:Np(t.artifact_layout),language:bp(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function fE(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function hE(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 vr(e,t={}){let i=(0,Al.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=fE(r.ambient_resume),o=r.native===void 0?void 0:uE(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:dE(r.classic),c=hE(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function mo(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:yi(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:ho,snapshot:{...ke,include:[...ke.include],exclude:[...ke.exclude]}}}}import{createHash as mE}from"crypto";import{promises as wo}from"fs";import Jt from"path";import{constants as vo,promises as Ni}from"fs";var Xe=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function Il(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function kp(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function gr(e){return{dev:e.dev,ino:e.ino,birthtime:Il(e)}}function go(e,t){let i=gr(e),n=gr(t);return fe(i,n)?M(i,n):M(i,n)&&Il(e)===Il(t)&&kp(e)===kp(t)&&e.size===t.size}async function bi(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 Ni.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new Xe("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Xe("too-large",`${n} exceeds ${t} bytes`);let o=await Ni.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:gr(a)});let s=process.platform==="win32"?vo.O_RDONLY:vo.O_RDONLY|vo.O_NOFOLLOW|vo.O_NONBLOCK,c;try{c=await Ni.open(e,s)}catch(l){throw l.code==="ELOOP"?new Xe("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),Ni.lstat(e,{bigint:r}),Ni.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!go(a,l)||!go(a,u))throw new Xe("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:gr(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let k=t+1-h,{bytesRead:N}=await c.read(m,0,Math.min(m.length,k),null);if(N===0)break;if(h+=N,h>t)throw new Xe("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[p,g,S]=await Promise.all([c.stat({bigint:r}),Ni.lstat(e,{bigint:r}),Ni.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||S!==o||!go(a,p)||!go(a,g))throw new Xe("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:gr(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:S}}finally{await c.close()}}function pE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Tl(e,t){let i=Jt.relative(e,t);return i===""||!Jt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Jt.sep}`)}async function Sp(e,t){let i=Jt.resolve(e),n=await wo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return wo.realpath(i)}async function Ep(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=Jt.join(r,i[a]);let o;try{o=await wo.lstat(r)}catch(u){if(pE(u))return{exists:!1,kind:"missing"};throw u}let s=Jt.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 wo.realpath(r);if(!Tl(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 wr(e,t,i){let n=xl(t,i.label),r=Jt.resolve(e),a=await Sp(r,i.label),o=n.split("/"),s=Jt.resolve(r,...o);if(!Tl(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Ep(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ki(e,t,i,n){let r=await wr(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 Sp(r.projectRoot,n.label);return bi(r.target,i,{...n,verify:async(o,s)=>{if(!Tl(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Ep(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var yr=".comet/config.yaml";function vE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function _l(e,t={}){return(await yo(e,t)).document}async function gE(e){try{return(await ki(e,yr,mr,{label:yr})).bytes}catch(t){if(vE(t))return null;throw t}}function wE(e){return e?{exists:!0,sha256:mE("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function yo(e,t={}){let i=await gE(e);return{document:i?vr(i.toString("utf8"),t):null,identity:wE(i)}}var kj=16*1024;import{promises as an}from"fs";import U from"path";import SE from"os";var bo=".comet/config.yaml";async function Hl(e){try{return await an.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function EE(e){try{let t=await an.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Nr(e,t){let i=U.relative(e,t);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}async function br(e){let t=[],i=e;for(;!await Hl(i);){let r=U.dirname(i);if(r===i)break;t.push(U.basename(i)),i=r}let n=await an.realpath(i);return U.resolve(n,...t.reverse())}async function Rp(e){try{return(await an.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ko(e){let t=U.resolve(e);try{(await an.stat(t)).isDirectory()||(t=U.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=U.resolve(SE.homedir());for(;;){if(!(t===n&&i!==n)){let o=U.join(t,...bo.split("/")),s=t===i||await EE(o);if(await Hl(o)&&s)return t}if(await Hl(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return i;t=a}}function So(e){return yi(e)}async function CE(e,t){let i=So(t),n=U.resolve(e,...i.split("/")),r=await an.realpath(e),a=await br(n);if(!Nr(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function $l(e,t){let i=So(t),n=await CE(e,i),r=U.join(n,"comet");if(await Rp(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([br(n),br(r)]);if(!Nr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:U.resolve(e),configFile:U.join(e,...bo.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:U.join(r,"specs"),changesDir:U.join(r,"changes"),archiveDir:U.join(r,"archive"),runtimeDir:U.join(r,"runtime"),locksDir:U.join(r,"runtime","locks"),transactionsDir:U.join(r,"runtime","transactions")}}function F(e,t){return Nr(U.resolve(e),U.resolve(t))}async function O(e,t){let i=U.resolve(e),n=U.resolve(t);if(!Nr(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Rp(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([br(i),br(n)]);if(!Nr(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Fl=ke,Pp=ho,Eo=po;function PE(e="docs",t="en"){return mo(e,t)}async function Gt(e){let t=(await _l(e))?.config??null;return t?.native?t:null}async function kr(e){let t=await Gt(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 Ap(e){let t=await ko(e.startPath),i=await Gt(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${bo} 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?So(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??PE(n??"docs"),a=await $l(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as tC}from"fs";import iC from"path";import{AsyncLocalStorage as AE}from"async_hooks";import{randomUUID as Tp}from"crypto";import{promises as $e}from"fs";import _p from"os";import ge from"path";var xp=16*1024,jp=".coordinator",xE=5e3,Ip=new AE,Co=new Map;function IE(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function TE(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 Op(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 Dl(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return fe(i,n)?M(i,n):M(i,n)&&e.size===t.size}function Ml(e,t){return Dl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function bt(e){let t,i;try{let n=await bi(e,xp,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Xe?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${xp} 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:TE(JSON.parse(t.toString("utf8")),e),identity:Op(i)}}async function _E(e){return(await bt(e))?.owner??null}function Hp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==_p.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=DE(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function jE(e,t){try{await $e.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await $e.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Bl(e,t){let i=await bt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ml(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await $e.mkdir(t,{recursive:!0});let n=ge.join(t,`${ge.basename(e.file)}.${e.owner.id}.${Tp()}.removed`);try{await $e.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await bt(n);if(!r||r.owner.id!==e.owner.id||!Dl(r.identity,e.identity))throw await jE(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await $e.rm(n,{force:!0}),"removed"}function $p(e){return{id:Tp(),pid:process.pid,hostname:_p.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Fp(e,t){let i;try{i=await $e.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await _E(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(),Op(await i.stat({bigint:!0}))}finally{await i.close()}}async function OE(e,t){let i=await O(e.nativeRoot,e.locksDir);await $e.mkdir(i,{recursive:!0});let n=await O(e.nativeRoot,ge.join(i,jp));await $e.mkdir(n,{recursive:!0});let r=$p(t),a=ge.join(n,`.${r.id}.tmp`),o=ge.join(n,`${r.id}.claim`);try{let s=await Fp(a,r);await $e.rename(a,o);let c=await bt(o);if(!c||!Dl(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 $e.rm(a,{force:!0})}}async function HE(e){let t=ge.dirname(e.file),i=!1,n=ge.basename(e.file);for(let r of await $e.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ge.join(t,r.name);if(ge.resolve(a)!==ge.resolve(e.file))try{let o=await bt(a),s=Hp(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Bl(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function Dp(e){let t=await bt(e.file);if(t){if(t.owner.id!==e.owner.id||!Ml(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Bl(t,ge.dirname(e.file))}}async function $E(e,t){let i=Date.now()+xE;for(;;){let n=await OE(e,t);if(!await HE(n))return n;if(await Dp(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 FE(e){let t=Co.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Co.set(e,r),await t,()=>{i(),Co.get(e)===r&&Co.delete(e)}}async function Mp(e,t,i){let n=ge.resolve(e.locksDir),r=Ip.getStore();if(r?.has(n))return i();let a=await FE(n);try{let o=await $E(e,t),s=new Map(r??[]);return s.set(n,o),await Ip.run(s,async()=>{try{return await i()}finally{await Dp(o)}})}finally{a()}}async function Sr(e,t,i){return Mp(e,`acquire ${t}`,async()=>{let n=await O(e.nativeRoot,e.locksDir);await $e.mkdir(n,{recursive:!0});let r=await O(e.nativeRoot,ge.join(n,IE(t))),a=$p(i),o=await Fp(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function Er(e){await bt(e.file)&&await Mp(e,`release ${ge.basename(e.file)}`,async()=>{let t=await bt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ml(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=ge.join(e.locksDir,jp);await Bl(t,i)})}function DE(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Bp(e){return Hp(await bt(e))}import kt from"path";import{TextDecoder as zE}from"util";import{createHash as ME}from"node:crypto";import{constants as Ro,promises as Ae}from"node:fs";import Qe from"node:path";import{TextDecoder as BE}from"node:util";function Ao(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}function Lp(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function LE(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qE(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Po(e,t){return M({...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 Ll(e,t){let i=await Ae.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function ql(e,t,i){let n=Qe.resolve(e),r=Qe.resolve(t);if(!Ao(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Ll(n,i)],o=n;for(let s of Qe.relative(n,r).split(Qe.sep).filter(Boolean)){await ft(a,i),o=Qe.join(o,s);let c=await Ll(o,i);if(!Ao(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ft(a,i),a}async function ft(e,t){for(let i of e){let n=await Ae.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!LE(i,n)||await Ae.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function VE(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 ht(e){let t=Lp(e.maxBytes),i=Qe.resolve(e.file),n=await ql(e.root,Qe.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>Ll(Qe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ft(n,e.label);let a=await Ae.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=qE(a),s=await Ae.realpath(i);if(!Ao(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Ao(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ro.O_RDONLY:Ro.O_RDONLY|Ro.O_NOFOLLOW|Ro.O_NONBLOCK,l=await Ae.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ae.lstat(i),Ae.realpath(i)]);if(await ft(n,e.label),await ft(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Po(o,u)||!Po(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await VE(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,g]=await Promise.all([l.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await ft(n,e.label),await ft(r,e.label),!p.isFile()||p.isSymbolicLink()||g!==s||!Po(o,m)||!Po(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:ME("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function qp(e){let t=await ht(e),i;try{i=new BE("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 Cr(e){let t=await ql(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Ae.readdir(e.directory,{withFileTypes:!0});else{let n=Lp(e.maxEntries);i=[];let r=await Ae.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 ft(t,e.label),{entries:i,verify:()=>ft(t,e.label)}}async function xo(e){let t=await ql(e.root,e.directory,e.label);return{verify:()=>ft(t,e.label)}}var JE=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),GE=new Set(["id","type","source","target","staged","backup"]),UE=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),KE=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var zp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var YE=256*1024,fO=1024*1024,hO=16*1024;var pO=64*1024*1024;var XE=new zE("utf-8",{fatal:!0});function To(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _o(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 Jp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Vl(e,t){if(typeof e!="string"||e.length===0||kt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Io(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Vp(e,t){if(Vl(e,t),e.includes("\\")||e!==kt.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 QE(e,t){let i=To(e,`transaction operations[${t}]`);if(_o(i,GE,`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`);Vl(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Vl(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 Gp(e){let t=To(e,"Native Archive transaction journal");if(_o(t,UE,"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"||!zp.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(!Jp(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Io(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=To(s,`Archive transaction operations[${c}]`);if(_o(l,KE,`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`);Vp(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Vp(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Io(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(Io(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`);Io(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 ZE(e){let t=To(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Gp(t);if(_o(t,JE,"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"||!zp.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!kt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!kt.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(!Jp(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(QE),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 eC(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return kt.join(e.transactionsDir,t)}function Up(e,t){let i=eC(e,t);return{directory:i,journal:kt.join(i,"transaction.json"),events:kt.join(i,"events.jsonl"),staged:kt.join(i,"staged"),backups:kt.join(i,"backups")}}async function Wl(e,t){let i=Up(e,t);return await Promise.all(Object.values(i).map(n=>O(e.nativeRoot,n))),i}async function zl(e,t,i={}){let n=await Wl(e,t),r=await ht({root:e.nativeRoot,file:n.journal,maxBytes:YE,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(XE.decode(r.bytes)),o=ZE(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function nC(e,t){let i;try{i=await tC.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 zl(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function rC(e,t){let i=Date.now()+5e3,n=iC.join(e.locksDir,"root-move.lock");for(;;)try{return await Sr(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await Bp(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 Fe(e,t,i,n){let r=await rC(e,t);try{if(await kr(e.projectRoot),await nC(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Er(r)}}function Kp(e){return Number.isSafeInteger(e)&&e>=1}async function Yp(e){if(!Kp(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!Kp(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Fo}from"crypto";import{spawn as om}from"node:child_process";import{promises as X}from"fs";import B from"path";import{createHash as Xp}from"crypto";import{createReadStream as aC}from"fs";async function Rr(e){let t=Xp("sha256");for await(let i of aC(e))t.update(i);return t.digest("hex")}function G(e){return Xp("sha256").update(e).digest("hex")}var jo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Xl=1e3,oC=8*1024*1024,sC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),lC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),uC=new Set(["schema","include","exclude","hash"]),dC=new Set(["provider","gitSelection","physicalSelection","projection"]),fC=new Set(["provider","selection"]),hC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),pC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),mC=new Set(["schema","status","before","after"]),vC=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),gC=new Set(["path","hash","size","type","gitObjectId"]),wC=new Set(["path","size","type","reason"]),yC=new Set(["ref","hash","count"]),NC=new Set(["change-created","legacy-migration","explicit"]),bC=new Set(["file","directory","other"]),kC=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"]),Do=/^[a-f0-9]{64}$/u,sm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,SC=new Set(["EACCES","EPERM"]),un=64*1024,Kl=64*1024,EC=6e4,CC=1e3,RC=2,Ql={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},PC={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function cm(e){let t=e.deadlineMs??EC;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 Ze(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return Ze(e)>=1}function Jl(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 cn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function AC(e){let t={...PC,...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 xC(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&&B.win32.isAbsolute(n)?B.win32.resolve(n):"C:\\Windows",a=B.win32.join(r,"System32","taskkill.exe");if(!B.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,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=om(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),CC),u.unref()}catch{d(!1)}});for(let s=0;s<RC;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 Zl(e,t,i,n){let r=Ze(e);if(r<1)throw Jl();let a=e.gitProcess,o=om(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",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=xC(o,a).then(()=>({error:null}),h=>({error:h}))},r);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Jl(m.error):Jl()}return{code:h,spawnError:s}});return{child:o,completion:f}}function lm(e){let t={...Ql,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Oo(e,t,i,n=Kl){let{child:r,completion:a}=Zl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",h=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>n&&(u=!0)}),r.stderr.on("data",h=>{if(c>=un)return;let m=un-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.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 Gl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Ar(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}=Zl(e,t,i,n.stdin!==void 0),c=[],l=Fo("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),g=!1,S=!1,k=!1,N=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&&(p.byteLength+v.byteLength>n.maxRecordBytes?(p=Buffer.alloc(0),g=!0,S=!0):p=Buffer.concat([p,v])),y<0)break;m+=1,p.byteLength===0&&!g&&(k=!0);let E=p.byteLength+1;!g&&m<=n.maxRecords&&h+E<=n.maxBytes?(c.push(p),h+=E):S=!0,p=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){N(b);return}for(let y=0;y<b.byteLength;y+=C)N(b.subarray(y,Math.min(b.byteLength,y+C)))}),o.stderr.on("data",b=>{if(d>=un)return;let C=un-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&&!k&&p.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}`:k||p.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 Ho(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 IC(e,t,i){if(i.length===0)return new Set;let n=await Ar(e,t,["check-ignore","--no-index","-z","--stdin"],{...Ql,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=Ho(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function TC(e,t,i){let{child:n,completion:r}=Zl(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>=un)return;let d=un-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 ln(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||B.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||B.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function _C(e,t){return e.map(i=>{let n=ln(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function jC(e){let t=B.resolve(e);for(;;){try{return await X.lstat(B.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=B.dirname(t);if(i===t)return!1;t=i}}async function um(e,t,i,n={}){let r=B.resolve(t.projectRoot),a=B.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(f=>{let h=B.relative(r,B.resolve(f)).replaceAll("\\","/"),m=ln(h);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 Ar(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await Ar(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await Ar(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function dm(e){return{stageBefore:Gl(e.stagedBefore),combined:Gl(e.combined),stageAfter:Gl(e.stagedAfter)}}async function fm(e,t,i=Ql,n={}){let r=B.resolve(t.projectRoot);if(!await jC(r))return null;let a;try{a=await Oo(e,r,["rev-parse","--is-inside-work-tree"])}catch(k){throw cn(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}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 um(e,t,i,n)}catch(k){throw cn(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=k=>{for(let N of k){let b=Ho(N),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=ln(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)}};h(s.records),h(l.records);let m=c.records.map(Ho),p=_C(m,"combined"),g=new Set(p.filter(k=>!u.has(k))),S=new Set(p.filter((k,N)=>!u.has(k)&&m[N].endsWith("/")));for(let k of f)S.delete(k);return{tracked:u,trackedObjectIds:d,untracked:g,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:dm(o)}}function Kt(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Qp(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function OC(e,t){return!Kt(e.stageBefore,e.stageAfter)||!Kt(e.stageAfter,t.stageBefore)||!Kt(e.combined,t.combined)||!Kt(t.stageBefore,t.stageAfter)}async function hm(e,t,i,n,r){let a;try{a=await um(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw cn(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=dm(a),c=Qp(o)||Qp(s),l=OC(o,s);c&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),n.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(n.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:G(`comet.native.git-selection-overflow.v2
|
|
145
|
-
|
|
146
|
-
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):G(`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:k,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:h}}}function pm(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 FC(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!pm(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 mm(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function em(e,t){let n=(await Oo(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!sm.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return G(`gitlink:${n}`)}async function tm(e,t){let i=await em(e,t),n=await TC(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await em(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function Pr(e,t){if(dt(t)!==null)return!1;let i=B.resolve(e.projectRoot,...t.split("/"));return!Yt(B.resolve(e.nativeRoot),i)}function DC(e,t){return B.relative(e,t).split(B.sep).join("/")}function MC(e,t){return t.map(i=>B.resolve(e,...i.split(/[\\/]/u)))}function Yt(e,t){let i=B.resolve(e),n=B.resolve(t);return n===i||F(i,n)}function re(e){return SC.has(e.code??"")}function ne(e){return e.code==="ENOENT"}function eu(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
148
|
-
`)}function BC(e,t){return G(`comet.native.snapshot-policy.v1
|
|
149
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Ul(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 LC(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function im(e){let t=Eo(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?LC(r):void 0;if(a&&!a())return!1;let o=Ul(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=Ul(i,c,a),o===null||o.size===0)return!1}return Ul(i,o,a)?.has(i.length)??!1}}function vm(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>Eo(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>Eo(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=BC(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(im),excludeMatchers:i.map(im),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 qC(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function nm(e,t,i){if(!e)return!0;let n=()=>H(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 xr(e,t,i){let n=JSON.stringify(i);return G(`${e}
|
|
150
|
-
${Buffer.byteLength(t)}:${t}
|
|
151
|
-
${Buffer.byteLength(n)}:${n}`)}function Yl(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function $o(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Yl(i))return e.splice(t,1),i}return null}function Ut(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return fe(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function VC(e,t,i,n){if(!H(n))return{status:"budget-exhausted"};let r;try{r=await X.open(e,"r")}catch(c){if(!H(n))return{status:"budget-exhausted"};throw c}if(!H(n))return await r.close(),{status:"budget-exhausted"};let a=Fo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(n))return{status:"budget-exhausted"};let c=await r.stat();if(!H(n))return{status:"budget-exhausted"};if(!c.isFile()||!Ut(i,c))return{status:"changed"};for(;;){if(!H(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(!H(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(n))return{status:"budget-exhausted"};let d=await r.stat();return H(n)?!d.isFile()||!Ut(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 De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Me(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function sn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function gm(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=B.posix.normalize(e);if(i!==e||B.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function WC(e,t){let i=De(e,`Native snapshot entry ${t}`);Me(i,gC,`Native snapshot entry ${t}`);let n=gm(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Do.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:pt(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!sm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function zC(e,t){let i=De(e,`Native snapshot omission ${t}`);if(Me(i,wC,`Native snapshot omission ${t}`),!bC.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!kC.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:gm(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:pt(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function JC(e){let t=De(e,"Native snapshot omission overflow");if(Me(t,yC,"Native snapshot omission overflow"),typeof t.hash!="string"||!Do.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:sn(t.count,"Native snapshot omission overflow count")}}function on(e,t){let i=De(e,t);if(Me(i,pC,t),typeof i.hash!="string"||!Do.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=pt(i.recordCount,`${t} recordCount`),r=pt(i.storedRecordCount,`${t} storedRecordCount`),a=pt(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 rm(e){let t=De(e,"Native Git selection evidence");if(Me(t,hC,"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=on(t.stageBefore,"Native Git selection stageBefore"),n=on(t.combined,"Native Git selection combined"),r=on(t.stageAfter,"Native Git selection stageAfter"),a=on(t.finalStageBefore,"Native Git selection finalStageBefore"),o=on(t.finalCombined,"Native Git selection finalCombined"),s=on(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Kt(i,r)||!Kt(r,a)||!Kt(n,o)||!Kt(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 am(e,t){let i=De(e,t);if(Me(i,vC,t),typeof i.hash!="string"||!Do.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=pt(i.visitedNodeCount,`${t} visitedNodeCount`),r=pt(i.recordCount,`${t} recordCount`),a=pt(i.storedRecordCount,`${t} storedRecordCount`),o=pt(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 GC(e){let t=De(e,"Native physical selection evidence");if(Me(t,mC,"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=am(t.before,"Native physical selection before"),n=am(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!pm(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 Si(e){let t=De(e,"Native content snapshot manifest");if(Me(t,cC,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!NC.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=De(t.capture,"Native content snapshot capture");if(Me(y,dC,"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:rm(y.gitSelection),v=y.physicalSelection===void 0?void 0:GC(y.physicalSelection),E=null;if(y.projection!==void 0){let j=De(y.projection,"Native content snapshot projection");if(Me(j,fC,"Native content snapshot projection"),j.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...j.selection===void 0?{}:{selection:rm(j.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=De(t.limits,"Native content snapshot limits");Me(n,lC,"Native content snapshot limits");let r={maxFiles:sn(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:sn(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:sn(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:sn(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:sn(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=De(t.policy,"Native snapshot policy");if(Me(y,uC,"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=vm({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(WC),s=t.omitted.map(zC),c=pt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:JC(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>Xl||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 h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(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 k=i?.physicalSelection,N=k?.status==="overflow"||k?.status==="overflow-and-changed",b=k?.status==="changed"||k?.status==="overflow-and-changed";if(N!==(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(eu(C)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return C}async function dn(e,t,i={}){let n=Si(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=B.resolve(e.projectRoot),a=cm(i),o=lm(i.gitSelectionLimits),s=await fm(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(mm(s).filter(v=>Pr(e,v))),l=[...s.gitlinks].filter(v=>c.has(v)),u=[...s.nestedRepositories].filter(v=>Pr(e,v)),d=(v,E)=>E.some(j=>v===j||v.startsWith(`${j}/`)),f=v=>d(v,l),h=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)&&!h(v)),p=await IC(a,r,m),g=n.entries.filter(v=>!f(v.path)&&!h(v.path)&&Pr(e,v.path)&&(c.has(v.path)||!p.has(v.path)));await hm(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 k=n.omitted.filter(v=>f(v.path)||h(v.path)||!Pr(e,v.path)?!1:p.has(v.path)?c.has(v.path)||[...c].some(E=>E.startsWith(`${v.path}/`)):!0);for(let v of S)k.some(E=>E.path===v.path&&E.reason===v.reason)||k.push(v);k.sort((v,E)=>v.path.localeCompare(E.path,"en"));let N=n.omissionOverflow?.count??0,b=n.omissionOverflow?.hash??G("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,b=xr(b,"git-selection",{source:"git-selection",...s.overflow}));let C=v=>{N+=1,b=xr(b,"omission",v)};for(;k.length>Xl;){let v=$o(k);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:k.length+N===0,entries:g,omitted:k,omittedCount:k.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:N}}:{}}),w=y();for(;eu(w)>n.limits.maxManifestBytes;){let v=$o(k);if(v===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");C(v),w=y()}return Si(w)}function UC(e,t){if(!sC.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=B.join(e.changesDir,t);if(!F(e.changesDir,i))throw new Error("Native change path escaped");return B.join(i,"runtime","baseline-manifest.json")}async function wm(e,t={}){let i={maxFiles:t.limits?.maxFiles??jo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??jo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??jo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??jo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=vm(t.policy),r=cm({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=lm(t.gitSelectionLimits),o=AC(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=B.resolve(e.projectRoot),c=await X.realpath(s),l=B.resolve(e.nativeRoot),u=await X.realpath(l),d=B.resolve(e.configFile),f=B.join(s,".comet","current-change.json"),h=MC(s,t.denylist??[]),m=[],p=[],g=new Map,S=new Map,k=0,N=0,b=G("comet.native.snapshot-omission-overflow.v1"),C=0,y=!1,w=null,v=x=>{N+=1,b=xr(b,"omission",x)},E=x=>{if(k+=1,p.length<Xl){p.push(x);return}if(Yl(x)){let A=$o(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");v(A),p.push(x);return}v(x)},j=x=>{k+=x.count,N+=x.count,b=xr(b,"git-selection",{source:"git-selection",...x})},V=x=>{N+=1,b=xr(b,"manifest-entry",{reason:"manifest-size",entry:x})},L=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 I=m.findIndex(Y=>Y.path===x);if(I<0)return;let[D]=m.splice(I,1);C-=D.size,g.delete(x),E(A)},K=async(x,A,I,D)=>{if(!I.isFile()||I.isSymbolicLink()||!H(r))return;let Y;try{Y=await X.realpath(x)}catch(P){if(!H(r))return;if(!re(P)&&!ne(P))throw P;E({path:A,size:I.size,type:"file",reason:ne(P)?"changed-during-read":"unreadable"});return}if(!H(r)||!F(c,Y)||Yt(u,Y))return;if(m.length>=i.maxFiles){E({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){E({path:A,size:I.size,type:"file",reason:"file-size"});return}if(C+I.size>i.maxTotalBytes){E({path:A,size:I.size,type:"file",reason:"total-size"});return}let W,$,Q;try{if(W=await VC(Y,I.size,I,r),W.status==="budget-exhausted"||!H(r))return;if(W.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(r)||(Q=await X.realpath(x),!H(r)))return;$=await X.lstat(x)}catch(P){if(!H(r))return;if(!re(P)&&!ne(P))throw P;E({path:A,size:I.size,type:"file",reason:ne(P)?"changed-during-read":"unreadable"});return}if(H(r)){if(W.bytes!==I.size||Q!==Y||!Ut(I,W.finalStat)||!Ut(W.finalStat,$)||!$.isFile()||$.isSymbolicLink()||$.size!==I.size||$.mtimeMs!==I.mtimeMs||$.ctimeMs!==I.ctimeMs){E({path:A,size:$.isFile()?$.size:null,type:$.isFile()?"file":"other",reason:"changed-during-read"});return}H(r)&&await L({path:A,hash:W.hash,size:$.size,type:"file",...D===void 0?{}:{gitObjectId:D}},{kind:"file",target:x,realTarget:Y,stat:$})}},st=async(x,A,I)=>{if(!H(r))return;let D,Y,W;try{if(D=await X.readlink(x,{encoding:"buffer"}),!H(r)||(W=await X.lstat(x),!H(r)))return;Y=await X.readlink(x,{encoding:"buffer"})}catch(P){if(!H(r))return;if(!re(P)&&!ne(P))throw P;E({path:A,size:null,type:"other",reason:ne(P)?"changed-during-read":"unreadable"});return}if(!H(r))return;if(!W.isSymbolicLink()||!Ut(I,W)||W.mtimeMs!==I.mtimeMs||W.ctimeMs!==I.ctimeMs||!D.equals(Y)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let $=D.byteLength;if(m.length>=i.maxFiles){E({path:A,size:$,type:"other",reason:"file-count"});return}if($>i.maxFileBytes){E({path:A,size:$,type:"other",reason:"file-size"});return}if(C+$>i.maxTotalBytes){E({path:A,size:$,type:"other",reason:"total-size"});return}let Q=Fo("sha256").update("symlink\0").update(D).digest("hex");H(r)&&await L({path:A,hash:Q,size:$,type:"file"},{kind:"symlink",target:x,rawTarget:D,stat:W})},ct=async()=>{for(let[x,A]of[...g]){if(!H(r))return;if(A.kind==="file"){let $,Q;try{if($=await X.realpath(A.target),!H(r))return;Q=await X.lstat(A.target)}catch(P){if(!H(r))return;if(!re(P)&&!ne(P))throw P;J(x,{path:x,size:null,type:"file",reason:re(P)?"unreadable":"changed-during-read"});continue}if(!H(r))return;($!==A.realTarget||!Q.isFile()||Q.isSymbolicLink()||!Ut(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 $,Q;try{if($=await X.lstat(A.target),!H(r))return;Q=await X.readlink(A.target,{encoding:"buffer"})}catch(P){if(!H(r))return;if(!re(P)&&!ne(P))throw P;J(x,{path:x,size:null,type:"other",reason:re(P)?"unreadable":"changed-during-read"});continue}if(!H(r))return;(!$.isSymbolicLink()||!Ut(A.stat,$)||$.mtimeMs!==A.stat.mtimeMs||$.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Q))&&J(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let I,D;try{if(I=await X.realpath(A.target),!H(r))return;D=await X.lstat(A.target)}catch{if(!H(r))return;J(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(r))return;if(!(I===A.realTarget&&D.isDirectory()&&!D.isSymbolicLink()&&Ut(A.stat,D)&&F(c,I)&&!Yt(u,I))){J(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let W;try{if(!H(r))return;W=await tm(r,I)}catch($){if(cn($))throw $;J(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(r))return;W.dirty?J(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):W.hash!==A.hash&&J(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"})}for(let[x,A]of S){if(!H(r))return;try{let I=await X.lstat(A);if(!H(r))return;E({path:x,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!H(r))return;if(ne(I))continue;if(!re(I))throw I;E({path:x,size:null,type:"file",reason:"unreadable"})}}},Ce=await fm(r,e,a,t.gitSelectionHooks);if(Ce===null){let x=await Zp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:h,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let D of x.records){if(D.type!=="file"&&D.type!=="symlink"||g.has(D.path))continue;if(Ze(r)<1)break;if(!nm(n,D.path,r))continue;if(Ze(r)<1)break;let Y=B.resolve(s,...D.path.split("/")),W;try{W=await X.lstat(Y)}catch($){if(!H(r))break;if(!re($)&&!ne($))throw $;E({path:D.path,size:null,type:"file",reason:ne($)?"changed-during-read":"unreadable"});continue}if(Ze(r)<1)break;if(D.type==="symlink"&&W.isSymbolicLink()){if(await st(Y,D.path,W),Ze(r)<1)break;continue}if(D.type!=="file"||!W.isFile()||W.isSymbolicLink()){E({path:D.path,size:W.isFile()?W.size:null,type:W.isDirectory()?"directory":W.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await K(Y,D.path,W),Ze(r)<1)break}Ze(r)>=1&&await ct();let A=await Zp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:h,policy:n,limits:o}),I=FC(x.evidence,A.evidence);w=I.evidence;for(let D of[...x.omissions,...A.omissions,...I.omissions])p.some(Y=>Y.path===D.path&&Y.reason===D.reason)||E(D)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let x=t.incrementalBaseline,A=new Map,I=!1;if(x){let P=Si(x);for(let Z of P.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);I=A.size>0}let D=new Set,Y=!0;try{let P=await Ar(r,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)I=!1,Y=!1,A.clear();else for(let Z of P.records){let ee=Ho(Z),ve=ee.indexOf(" "),de=ve<0?null:ln(ee.slice(ve+1));if(ve!==1||de===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&D.add(de)}}catch(P){if(cn(P))throw P;I=!1,Y=!1,A.clear()}let W=new Set;try{let P=await Oo(r,s,["ls-files","--modified","-z"],Kl);for(let Z of P.toString("utf8").split("\0")){let ee=ln(Z);ee!==null&&W.add(ee)}}catch{I=!1,Y=!1,A.clear()}let $=new Set,Q=new Set;for(let P of mm(Ce)){if(g.has(P)||!Pr(e,P))continue;if(Ze(r)<1)break;if(!nm(n,P,r))continue;if(Ze(r)<1)break;let Z=B.resolve(s,...P.split("/"));if(Z===d||Z===f||h.some(Re=>Yt(Re,Z)))continue;if(Ce.gitlinks.has(P)){if(m.length>=i.maxFiles){E({path:P,size:0,type:"file",reason:"file-count"});continue}let Re,sa;try{[Re,sa]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(sa.isSymbolicLink()||!sa.isDirectory()||!F(c,Re)||Yt(u,Re)){E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ji=await tm(r,Re);if(Ji.dirty){E({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await L({path:P,hash:Ji.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Re,stat:sa,hash:Ji.hash})}catch(Ji){if(cn(Ji))throw Ji;E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await X.lstat(Z)}catch(Re){if(ne(Re)&&Ce.tracked.has(P)){S.set(P,Z);continue}if(!re(Re)&&!ne(Re))throw Re;E({path:P,size:null,type:"file",reason:ne(Re)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await st(Z,P,ee);continue}if(!ee.isFile()){Ce.nestedRepositories.has(P)||E({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let ve=Ce.trackedObjectIds.get(P),de=ve?A.get(P):void 0;if(I&&de?.gitObjectId!==void 0&&de.gitObjectId===ve&&!D.has(P)&&!W.has(P)){if(m.length>=i.maxFiles){E({path:P,size:de.size,type:"file",reason:"file-count"});continue}if(de.size>i.maxFileBytes){E({path:P,size:de.size,type:"file",reason:"file-size"});continue}if(C+de.size>i.maxTotalBytes){E({path:P,size:de.size,type:"file",reason:"total-size"});continue}m.push({...de}),C+=de.size,$.add(P);continue}let Cd=Y&&!D.has(P)&&!W.has(P)?ve:void 0;await K(Z,P,ee,Cd),Cd!==void 0&&Q.add(P)}if(await ct(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await hm(r,e,a,Ce,t.gitSelectionHooks?.outputChunkBytes),$.size>0||I&&Q.size>0){let P=await Oo(r,s,["ls-files","--modified","-z"],Kl),Z=new Set;for(let ee of P.toString("utf8").split("\0")){let ve=ln(ee);ve!==null&&Z.add(ve)}for(let ee of $){if(!Z.has(ee))continue;let ve=m.find(de=>de.path===ee);J(ee,{path:ee,size:ve?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Q){if(!Z.has(ee))continue;let ve=m.find(de=>de.path===ee);ve&&delete ve.gitObjectId}}for(let P of Ce.omissions)E(P);Ce.overflow&&j(Ce.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),p.sort((x,A)=>x.path.localeCompare(A.path,"en"));let fy=Ce===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...Ce.evidence?{gitSelection:Ce.evidence}:{}},Ed=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:fy,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:p,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:N}}:{}}),Ls=Ed();for(;eu(Ls)>i.maxManifestBytes;){if(p.filter(A=>!Yl(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I=0;I<A;I+=1){let D=$o(p);if(D===null)break;v(D)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I of m.splice(-A))k+=1,V(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ls=Ed()}return Ls}async function Xt(e,t,i={}){let r=(await Gt(e.projectRoot))?.native.snapshot??Fl;return wm(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 Qt(e,t){let i=UC(e,t);await O(e.nativeRoot,i);try{let n=await qp({root:e.nativeRoot,file:i,maxBytes:oC,label:"Native baseline snapshot manifest"});return Si(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as hR}from"crypto";import ou from"path";import KC from"path";var xe=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});function YC(e){if(e.length===0||KC.isAbsolute(e)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error("Run storage ref must stay inside the Run root")}function ym(e){for(let t of Object.values(e))YC(t)}import{constants as Bo,promises as we}from"node:fs";import Ie from"node:path";import{TextDecoder as cR}from"node:util";import rR from"path";var iR=qs(so(),1);var Nm=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Tr(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 Ir(e,t){let i=Tr(e,t);if(rR.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 aR(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 bm(e){if(!e.run_id)return null;let t=Tr(e,"run_id"),i=Tr(e,"skill"),n=Tr(e,"skill_version"),r=Tr(e,"skill_hash"),a=Ir(e,"pending_ref"),o=Ir(e,"trajectory_ref"),s=Ir(e,"context_ref"),c=Ir(e,"artifacts_ref"),l=Ir(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:Nm(e,"current_step"),iteration:u,pending:Nm(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:aR(e)}}var LH=256*1024;var oR=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function sR(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=bm(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Mo(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=>!oR.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 sR(t)}function km(e,t,i,n){return ym(n),{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:i,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:n.pendingRef,trajectoryRef:n.trajectoryRef,contextRef:n.contextRef,artifactsRef:n.artifactsRef,checkpointRef:n.checkpointRef,status:"running",retries:{}}}var Se={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 jr(e,t){let i=Ie.relative(e,t);return i===""||!Ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ie.sep}`)}function Em(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function _r(e,t){return M({...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 lR(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ei(e,t,i){let n=xe[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Ie.resolve(e),a=Ie.resolve(r,...n.split("/"));if(!jr(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Sm(e){let t=await we.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await we.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function tu(e,t){let i=Ie.resolve(e),n=Ie.resolve(t);if(!jr(i,n))throw new Error("Native Run path is outside its change");let r=[await Sm(i)],a=i;for(let o of Ie.relative(i,n).split(Ie.sep).filter(Boolean)){a=Ie.join(a,o);let s;try{s=await Sm(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!jr(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function Lo(e){for(let t of e){let i=await we.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!lR(t,i)||await we.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function uR(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 fn(e,t,i,n,r){let a=await tu(e,Ie.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await we.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=Em(o),c=await we.realpath(t);if(!jr(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?Bo.O_RDONLY:Bo.O_RDONLY|Bo.O_NOFOLLOW|Bo.O_NONBLOCK,u;try{u=await we.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),we.lstat(t),we.realpath(t)]);if(await Lo(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!_r(s,d)||!_r(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await uR(u,i,n);await r?.beforeFinalCheck?.();let[p,g,S]=await Promise.all([u.stat(),we.lstat(t),we.realpath(t)]);if(await Lo(a),!g.isFile()||g.isSymbolicLink()||S!==c||!_r(s,p)||!_r(s,g))throw new Error(`${n} changed while reading`);let k;try{k=new cR("utf-8",{fatal:!0}).decode(m)}catch(N){throw new Error(`${n} is not valid UTF-8`,{cause:N})}return{text:k,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function dR(e,t,i){let n=await tu(e,Ie.dirname(t));if(!n)return{exists:!1};let r;try{r=await we.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await we.realpath(t);if(!jr(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Lo(n),{exists:!0,identity:Em(r),realPath:a}}async function fR(e,t,i,n){let r=await tu(e,Ie.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await we.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!_r(i.identity,a)||await we.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await Lo(r)}async function iu(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await dR(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await wi(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await fR(e.changeDir,e.file,i,e.label)}});let n=await fn(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 Cm(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Rm(e){return`${JSON.stringify(e,null,2)}
|
|
152
|
-
`}function nu(e){return Mo(e)}function Pm(e,t,i){return km(e,t,i,xe)}async function Be(e,t){let i=Ei(e,"stateRef"),n=await fn(e,i,Se.runStateBytes,"Native Run state",t);return n?Mo(Cm(n.text,"Native Run state")):null}async function ru(e,t,i){let n=Mo(t);await iu({changeDir:e,file:Ei(e,"stateRef"),content:Rm(n),maxBytes:Se.runStateBytes,label:"Native Run state",hooks:i})}async function Le(e,t,i){let n=Ei(e,"trajectoryRef",t),r=await fn(e,n,Se.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>Se.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Se.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 Am(e,t,i){return(await fn(e,Ei(e,"trajectoryRef",t),Se.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function xm(e,t,i,n){let r=Ei(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
|
|
153
|
-
`;if(Buffer.byteLength(a,"utf8")>Se.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Se.trajectoryEventBytes} bytes`);let o=await fn(e,r,Se.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Se.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Se.trajectoryEvents} events`);await iu({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Se.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function qo(e,t,i){let n=await fn(e,Ei(e,"checkpointRef",t),Se.checkpointBytes,"Native Run checkpoint",i);return n?Cm(n.text,"Native Run checkpoint"):null}async function Im(e,t,i,n){await iu({changeDir:e,file:Ei(e,"checkpointRef",t),content:Rm(i),maxBytes:Se.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var pR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,su=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 au(e){return hR("sha256").update(e).digest("hex")}function mR(e,t){if(!pR.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=ou.join(e.changesDir,t);if(!F(e.changesDir,i))throw new Error("Native change path escaped");return ou.join(i,"runtime","trajectory.jsonl")}function vR(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 gR(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 wR(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=vR(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(!gR(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:au(t),targetHash:au(l),tailHash:au(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function yR(e,t){let i=mR(e,t);await O(e.nativeRoot,i);let n=ou.join(e.changesDir,t),r=await Am(n,xe.trajectoryRef);return r===null?{status:"clean",file:i}:wR(i,Buffer.from(r))}async function cu(e,t){let i=await yR(e,t);return"inspection"in i?i.inspection:i}async function Or(e,t){let i=await cu(e,t);if(i.status!=="clean")throw new su(i)}import{createHash as kR}from"node:crypto";import{promises as Wo}from"node:fs";import Zt from"node:path";import{execFileSync as NR}from"child_process";import Vo from"path";function lu(e,t){return NR("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function bR(e,t){let i=Vo.normalize(e),n=Vo.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Tm(e){try{let t=Vo.resolve(lu(e,["rev-parse","--show-toplevel"])),n=lu(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?Vo.resolve(n.slice(9)):t,a=null;try{a=lu(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!bR(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var Hr=/^[a-f0-9]{64}$/u,SR=16*1024,uu=process.platform,ER=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function hn(e){return ER.has(e)}function Hm(e,t){let i=Zt.relative(e,t);return Zt.isAbsolute(i)||i===".."||i.startsWith(`..${Zt.sep}`)?null:i.replaceAll("\\","/")||"."}function $m(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Fm(e,t){if(e.length===0||$m(e)||e.includes("\\")||Zt.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=Zt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function du(e,t){return kR("sha256").update(`${e}
|
|
155
|
-
${t}`).digest("hex")}async function _m(e,t){let i=await Wo.realpath(t),n=await Wo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=uu==="win32"?Zt.normalize(i).toLowerCase():i;return du(e,`${r}
|
|
156
|
-
${n.dev}
|
|
157
|
-
${n.ino}
|
|
158
|
-
${n.birthtimeMs}`)}async function jm(e,t){let i=await Wo.realpath(t),n=await Wo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=uu==="win32"?Zt.normalize(i).toLowerCase():i;return du(e,r)}function CR(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 Om(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||$m(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Dm(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Om(e.changeBranch,"Native workspace change branch"),Om(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 zo(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"||!Hr.test(String(t.projectRootId))||!Hr.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");CR(t.capturedAt),Fm(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&&!Hr.test(String(t.projectRootPathId))||a&&!Hr.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Hr.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(Dm(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 RR(e,t){return Zt.join(e.changesDir,t,"runtime","workspace.json")}function PR(e,t){let i=Hm(e.nativeRoot,RR(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Fm(i,"Native workspace file ref")}async function AR(e,t){try{let i=await he({root:e.nativeRoot,ref:PR(e,t),maxBytes:SR});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function xR(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Hm(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([_m("comet.native.workspace-project-root.v2",e.paths.projectRoot),_m("comet.native.workspace-native-root.v2",e.paths.nativeRoot),jm("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),jm("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&&Dm(e.binding);let s={capturedAt:o,capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:du("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 zo(c),c}async function ei(e,t){let i=await AR(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(zo(i),i)}async function Jo(e){zo(e.identity);let t=await xR({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")),uu==="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 Go(e){if(zo(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 Jo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Tm(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 Mm(e,t){let i=await ei(e,t);if(i===null)return null;let n=await Go({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var ti="comet.native.v3",Ci="comet.native.v2",Ri="comet.native.v1",Pi="comet.native.transition.v3",pn="comet.native.transition.v2",$r="comet.native.transition.v1";var Lm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],IR=new Set(Lm),qm=new Set([...Lm,"minimum_runtime_version","revision"]),TR=new Set([...qm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),_R=new Set(["capability","operation","source","base_hash"]),jR=new Set(["shape","build","verify","archive"]),OR=new Set(["implicit","confirmed"]),HR=new Set(["pending","pass","fail"]),ii="comet-state.yaml",pu=/^[a-f0-9]{64}$/u,Vm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$R=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Fr=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"},Ai=class extends Error{constructor(i,n){super(i!==ti||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"},Dr=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"},Uo=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"},xi=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"},B0=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
161
|
-
`);function Br(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Wm(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 mn(e){if(!Vm.test(e))throw new Error(`Invalid Native change name: ${e}`)}function FR(e){if(!Vm.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function zm(e,t){if(e.length===0||St.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function DR(e,t){let i=Br(e,`spec_changes[${t}]`);if(Wm(i,_R,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(FR(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"&&zm(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"||!pu.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"||!pu.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 MR(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 mu(e,t){if(Wm(e,t,ii),typeof e.name!="string")throw new Error("Native change name is required");if(mn(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"||!jR.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&&!OR.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(DR),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"||!HR.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"&&zm(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!MR(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 Lr(e){let t=Br(e,ii);if(t.schema!==Ri)throw new Error(`Expected ${Ri}`);return{schema:Ri,...mu(t,IR)}}function Mr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function fu(e,t,i){if(e===null)return null;let n=typeof e=="string"?$R.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 BR(e){if(e==null)return null;if(typeof e!="string"||!pu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function LR(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 qr(e){let t=Br(e,ii);if(t.schema!==Ci)throw new Error(`Expected ${Ci}`);if(Mr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ci} minimum_runtime_version must be 2`);return{schema:Ci,minimum_runtime_version:2,revision:Mr(t.revision,"Native v2 revision"),...mu(t,qm)}}function Et(e){let t=Br(e,ii);if(t.schema!==ti){if(t.schema===Ri||t.schema===Ci){let o=t.schema===Ri?Lr(t):qr(t);throw new Fr(o.name,o.schema)}throw new Ai(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Mr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ai(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=Mr(t.revision,"Native revision"),r=mu(t,TR),a=BR(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ti,minimum_runtime_version:3,revision:n,verification_protocol:LR(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:fu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:fu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:fu(t.partial_allowance,"Native partial_allowance","allowances")}}function qR(e){let t=Br(e,ii);if(t.schema===Ri){let r=Lr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${ti}`}}if(t.schema===Ci){let r=qr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${ti}`}}if(t.schema!==ti){let r=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Ai(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=Mr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Ai(t.schema,i).message};let n=Et(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function hu(e){let t=Et(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 T(e,t){mn(t);let i=St.join(e.changesDir,t);if(!F(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Ii(e,t){let i=St.join(T(e,t),"runtime","schema-migration.json");await O(e.nativeRoot,i);try{return await Bm.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function vu(e,t){let i=St.join(T(e,t),"runtime","checkpoint-journal.json");await O(e.nativeRoot,i);try{return await Bm.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var VR=256*1024;async function Jm(e,t=St.dirname(e)){let i=St.relative(t,e).split(St.sep).join("/"),n=await he({root:t,ref:i,maxBytes:VR}),r=(0,Ko.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 gu(e,t){let i=St.join(T(e,t),ii);await O(e.nativeRoot,i);let n=qR(await Jm(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Ii(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 WR(e,n.state),n)}async function WR(e,t){if(await Qt(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function le(e,t){let i=await gu(e,t);if(i.status==="migration-required")throw new Fr(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ai(i.schema,i.minimumRuntimeVersion);return await Mm(e,t),i.state}async function zR(e,t,i){let n={...t,schema:ti,minimum_runtime_version:3,revision:i+1},r=await Yp({expectedRevision:i,next:n,read:async()=>{let a=Et(await Jm(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>wi(e,(0,Ko.stringify)(hu(a))),equals:(a,o)=>JSON.stringify(hu(a))===JSON.stringify(hu(o)),conflict:a=>new Dr(t.name,i,a)});return Object.assign(t,r),r}async function Vr(e,t,i,n){if(await kr(e.projectRoot),await Ii(e,t.name))throw new Fr(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await vu(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await le(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Or(e,t.name);let a=St.join(T(e,t.name),ii);return await O(e.nativeRoot,a),zR(a,t,i)}var Um=["Outcome","Scope","Non-goals","Acceptance examples"],JR=[...Um,"Constraints and invariants","Decisions","Open questions","Verification expectations"],GR=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Km={maxFileBytes:fr};function Ym(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 UR(e,t){let i=Gm.resolve(e,...t.split(/[\\/]/u));if(!F(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await wu.realpath(e),r=await wu.realpath(i);if(!F(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await wu.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Wr(e){return{valid:e.length===0,findings:e}}async function vn(e,t){let i=[],n;try{n=(await he({root:e,ref:t,maxBytes:Km.maxFileBytes})).text}catch(o){return Wr([{code:"brief-missing",message:o.message,path:t}])}let r=Ym(n);for(let o of JR)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Um)(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}),Wr(i)}async function zr(e,t){let i=[],n;try{n=(await he({root:e,ref:t,maxBytes:Km.maxFileBytes})).text}catch(a){return Wr([{code:"verification-missing",message:a.message,path:t}])}let r=Ym(n);for(let a of GR)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 Wr(i)}function gn(e,t){return Gm.join(e.specsDir,t,"spec.md")}async function wn(e,t){let i=[],n=T(e,t.name);for(let r of t.spec_changes){let a=gn(e,r.capability),o=null;try{await O(e.nativeRoot,a),o=await Rr(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 UR(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Wr(i)}import Xm from"node:path";import{createHash as KR}from"crypto";function et(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function YR(e,t){t.has(e)&&et("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)||et("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&et("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),`[${e.map(n=>yu(n,t)).join(",")}]`}finally{t.delete(e)}}function XR(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&et("only plain objects are supported"),t.has(e)&&et("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&et("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))&&et("accessor properties are not supported"),`${JSON.stringify(o)}:${yu(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function yu(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)||et("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?YR(e,t):XR(e,t);case"bigint":case"function":case"symbol":case"undefined":return et(`${typeof e} values are not supported`)}return et("unsupported value type")}function Jr(e){return yu(e,new Set)}function _(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 KR("sha256").update(`${e}
|
|
163
|
-
${Jr(t)}`).digest("hex")}var QR="comet.native.acceptance.v1",ZR=/^acceptance-[a-f0-9]{64}$/u,eP=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),tP=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,iP=/^[a-f0-9]{64}$/u,nP=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function rP(e,t){return e<t?-1:e>t?1:0}var Ct=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Gr=Object.freeze({maxCriteria:1024}),Qm="<!-- comet-native:acceptance-evidence:start -->",Zm="<!-- comet-native:acceptance-evidence:end -->";function ev(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 tv(e,t){let i=t.toString(36),n=_("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function aP(e){if(!iP.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=nP.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]!==_("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function oP(e,t){let i=ev(e.text,Ct.maxTextBytes),n=e.context.slice(0,Ct.maxContextItems).map(r=>ev(r,Ct.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 Yo(e){let t=aP({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(rP),r=n.slice(0,Ct.maxFailedCheckIds),a=e.criteria.slice(t,t+Ct.maxItems);for(let c of a){let l=[...i,oP(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?tv(e.acceptanceHash,u):null,limits:{...Ct}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Ct.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?tv(e.acceptanceHash,o):null,limits:{...Ct}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Ct.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function ku(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 Nu(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 iv(e){return e.includes("-->")||e.includes("--!>")}function*yn(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: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=kn(t),r=Jt(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=kn(t),r=Jt(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.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())}}};pd.Parser=ss});var yd=y(Fi=>{"use strict";var md=Uo(),fw=Ii(),Mi=Oi(),hw=za(),pw=x(),mw=os(),vd=cs();function gd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new mw.LineCounter||null,prettyErrors:t}}function vw(e,t={}){let{lineCounter:i,prettyErrors:r}=gd(t),n=new vd.Parser(i?.addNewLine),a=new md.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Mi.prettifyError(e,i)),s.warnings.forEach(Mi.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function wd(e,t={}){let{lineCounter:i,prettyErrors:r}=gd(t),n=new vd.Parser(i?.addNewLine),a=new md.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Mi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Mi.prettifyError(e,i)),o.warnings.forEach(Mi.prettifyError(e,i))),o}function gw(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=wd(e,i);if(!n)return null;if(n.warnings.forEach(a=>hw.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 ww(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),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(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return pw.isDocument(e)&&!r?e.toString(i):new fw.Document(e,r,i).toString(i)}Fi.parse=gw;Fi.parseAllDocuments=vw;Fi.parseDocument=wd;Fi.stringify=ww});var Gt=y(C=>{"use strict";var yw=Uo(),Nw=Ii(),bw=Co(),ls=Oi(),kw=vi(),ut=x(),Sw=at(),Ew=L(),Pw=st(),xw=ct(),Rw=Nn(),Cw=ns(),Aw=os(),_w=cs(),En=yd(),Nd=fi();C.Composer=yw.Composer;C.Document=Nw.Document;C.Schema=bw.Schema;C.YAMLError=ls.YAMLError;C.YAMLParseError=ls.YAMLParseError;C.YAMLWarning=ls.YAMLWarning;C.Alias=kw.Alias;C.isAlias=ut.isAlias;C.isCollection=ut.isCollection;C.isDocument=ut.isDocument;C.isMap=ut.isMap;C.isNode=ut.isNode;C.isPair=ut.isPair;C.isScalar=ut.isScalar;C.isSeq=ut.isSeq;C.Pair=Sw.Pair;C.Scalar=Ew.Scalar;C.YAMLMap=Pw.YAMLMap;C.YAMLSeq=xw.YAMLSeq;C.CST=Rw;C.Lexer=Cw.Lexer;C.LineCounter=Aw.LineCounter;C.Parser=_w.Parser;C.parse=En.parse;C.parseAllDocuments=En.parseAllDocuments;C.parseDocument=En.parseDocument;C.stringify=En.stringify;C.visit=Nd.visit;C.visitAsync=Nd.visitAsync});var Os=di(Gt(),1);import{promises as Fd}from"node:fs";import pe from"node:path";import{execFileSync as Tw}from"child_process";import qi from"path";function Vi(e,t){return Tw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Iw(e,t){let i=qi.normalize(e),r=qi.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function ue(e){try{let t=qi.resolve(Vi(e,["rev-parse","--show-toplevel"])),r=Vi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?qi.resolve(r.slice(9)):t,a=null;try{a=Vi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Iw(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function bd(e){try{Vi(e,["rev-parse","--is-inside-work-tree"]);let t=Vi(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:qi.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Pn(e){return bd(e).map(t=>t.root)}import{execFileSync as jw}from"node:child_process";var $w=3e4,Ow=8*1024*1024,us=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function Hw(e,t){try{return jw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$w,maxBuffer:Ow,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new us(e,t,r)}}function ds(e,t){return Hw(e,t).trim()}import{createHash as Mw}from"node:crypto";import{promises as ke}from"node:fs";import de from"node:path";import{TextDecoder as Fw}from"node:util";var Dw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Bw=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Lw(e){return e.toLowerCase().startsWith(".env")}function Wi(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Lw(r))?"environment-file":i.some(r=>Bw.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Dw.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function dt(e){return e!==0&&e!==0n&&e!=="0"}function ae(e,t){return dt(e.dev)&&dt(t.dev)&&dt(e.ino)&&dt(t.ino)}function $(e,t){let i=dt(e.dev)&&dt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=dt(e.ino)&&dt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var Rn=1024*1024;function fs(e,t){let i=de.relative(e,t);return i===""||!de.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${de.sep}`)}function Vw(e){let t=de.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||de.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(),r=Wi(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function qw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Ww(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xn(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ae(i,r)?$(i,r):$(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kd(e){let t=await ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zw(e,t){let i=de.resolve(e),r=de.resolve(t);if(!fs(i,r))throw new Error("Native artifact path is outside its root");let n=[await kd(i)],a=i;for(let o of de.relative(i,r).split(de.sep).filter(Boolean)){a=de.join(a,o);let s=await kd(a);if(!fs(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Sd(e){for(let t of e){let i=await ke.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ww(t,i)||await ke.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function V(e){let t=Vw(e.ref),i=e.maxBytes===null?null:qw(e.maxBytes??Rn),r=de.resolve(e.root,...t.split("/")),n=await zw(e.root,de.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await ke.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await ke.realpath(r);if(!fs(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ke.open(r,"r");try{let[c,l,f]=await Promise.all([s.stat(),ke.lstat(r),ke.realpath(r)]);if(await Sd(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!xn(a,c)||!xn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let N=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,N),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),ke.lstat(r),ke.realpath(r)]);if(await Sd(n),!h.isFile()||h.isSymbolicLink()||v!==o||!xn(c,m)||!xn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,u),w;try{w=new Fw("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:u,hash:e.includeHash===!1?null:Mw("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}import{createHash as Jw}from"crypto";function Se(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Gw(e,t){t.has(e)&&Se("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||Se("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Se("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Se("symbol properties are not supported"),`[${e.map(r=>hs(r,t)).join(",")}]`}finally{t.delete(e)}}function Uw(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Se("only plain objects are supported"),t.has(e)&&Se("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Se("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Se("accessor properties are not supported"),`${JSON.stringify(o)}:${hs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function hs(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)||Se("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Gw(e,t):Uw(e,t);case"bigint":case"function":case"symbol":case"undefined":return Se(`${typeof e} values are not supported`)}return Se("unsupported value type")}function ps(e){return hs(e,new Set)}function te(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 Jw("sha256").update(`${e}
|
|
143
|
+
${ps(t)}`).digest("hex")}var vs=di(Gt(),1);import Cn from"path";var zi=64*1024,An=1024,_n=64,gs=5,Kw=[".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/**"],Yw=["**/.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"],Xw=[...Kw,...Yw].sort((e,t)=>e.localeCompare(t,"en"));var oe={include:["**/*"],exclude:[...Xw],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Qw(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Cn.posix.isAbsolute(i)||Cn.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function St(e){let t=Qw(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Pd(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 Tn(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Cn.posix.isAbsolute(r)||Cn.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Ut(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function xd(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function ws(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>An)throw new Error(`${t} exceeds ${An} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>_n)throw new Error(`${t} contains more than ${_n} wildcard tokens`);return e}function Ed(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(r=>ws(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ms(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Zw(e){if(e===void 0)return{...oe,include:[...oe.include],exclude:[...oe.exclude]};let t=Ut(e,"native.snapshot");return{include:Ed(t.include,"native.snapshot.include",oe.include),exclude:Ed(t.exclude,"native.snapshot.exclude",oe.exclude),max_files:ms(t.max_files,oe.max_files,"native.snapshot.max_files"),max_total_bytes:ms(t.max_total_bytes,oe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ms(t.max_duration_ms,oe.max_duration_ms,"native.snapshot.max_duration_ms")}}function ey(e){if(e===void 0)return;let t=Ut(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=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 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(t.cleanup!==void 0){let s=Ut(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:i,fromArtifactRoot:St(r),toArtifactRoot:St(n),stage:a,...o?{cleanup:o}:{}}}function ty(e,t={}){let i=Ut(e,"native"),r=i.artifact_root??(t.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??gs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=ey(i.pending_root_move);return{artifact_root:St(r),language:xd(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Zw(i.snapshot),...s?{pending_root_move:s}:{}}}function iy(e){let t=Ut(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Pd(t.artifact_layout),language:xd(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function ry(e){let i=Ut(e,"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)=>Tn(r,`hook.allow_paths[${n}]`)))]}}function ny(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function ay(e,t,i,r,n,a){let o=e.schema!==void 0;if(!(o||e.default_workflow!==void 0||e.workflows!==void 0||!a.allowPartialProject&&e.native!==void 0)||a.allowPartialProject&&!o)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 c=e.workflows??[e.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(e.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:e.default_workflow,workflows:l,ambient_resume:n,...t?{hook:t}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function Ji(e,t={}){let i=(0,vs.parseDocument)(e,{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=ny(n.ambient_resume),o=n.hook===void 0?void 0:ry(n.hook),s=n.native===void 0?void 0:ty(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:iy(n.classic),l=ay(n,o,s,c,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function In(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:St(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:gs,snapshot:{...oe,include:[...oe.include],exclude:[...oe.exclude]}}}}import{createHash as sy}from"crypto";import{promises as On}from"fs";import ft from"path";import{constants as jn,promises as Et}from"fs";var Ee=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function ys(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Rd(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Gi(e){return{dev:e.dev,ino:e.ino,birthtime:ys(e)}}function $n(e,t){let i=Gi(e),r=Gi(t);return ae(i,r)?$(i,r):$(i,r)&&ys(e)===ys(t)&&Rd(e)===Rd(t)&&e.size===t.size}async function Kt(e,t,i={}){if(!Number.isSafeInteger(t)||t<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 Et.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ee("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ee("too-large",`${r} exceeds ${t} bytes`);let o=await Et.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Gi(a)});let s=process.platform==="win32"?jn.O_RDONLY:jn.O_RDONLY|jn.O_NOFOLLOW|jn.O_NONBLOCK,c;try{c=await Et.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ee("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Et.lstat(e,{bigint:n}),Et.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!$n(a,l)||!$n(a,f))throw new Ee("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Gi(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:N}=await c.read(m,0,Math.min(m.length,w),null);if(N===0)break;if(p+=N,p>t)throw new Ee("too-large",`${r} exceeds ${t} bytes`);u.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),Et.lstat(e,{bigint:n}),Et.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!$n(a,h)||!$n(a,v))throw new Ee("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Gi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await c.close()}}function oy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ns(e,t){let i=ft.relative(e,t);return i===""||!ft.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ft.sep}`)}async function Cd(e,t){let i=ft.resolve(e),r=await On.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return On.realpath(i)}async function Ad(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=ft.join(n,i[a]);let o;try{o=await On.lstat(n)}catch(f){if(oy(f))return{exists:!1,kind:"missing"};throw f}let s=ft.relative(e,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 On.realpath(n);if(!Ns(t,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 Yt(e,t,i){let r=Tn(t,i.label),n=ft.resolve(e),a=await Cd(n,i.label),o=r.split("/"),s=ft.resolve(n,...o);if(!Ns(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Ad(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function ht(e,t,i,r){let n=await Yt(e,t,{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 Cd(n.projectRoot,r.label);return Kt(n.target,i,{...r,verify:async(o,s)=>{if(!Ns(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Ad(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Ui=".comet/config.yaml";function cy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Hn(e,t={}){return(await Dn(e,t)).document}async function ly(e){try{return(await ht(e,Ui,zi,{label:Ui})).bytes}catch(t){if(cy(t))return null;throw t}}function uy(e){return e?{exists:!0,sha256:sy("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Dn(e,t={}){let i=await ly(e);return{document:i?Ji(i.toString("utf8"),t):null,identity:uy(i)}}async function bs(e){return(await Hn(e))?.config??null}var GP=16*1024;import{randomUUID as my}from"crypto";import{promises as K}from"fs";import Pe from"path";function Ps(e,t){let i=Pe.relative(e,t);return i===""||!Pe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Pe.sep}`)}function vy(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Es(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ae(i,r)?$(i,r):$(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Td(e){let t=await K.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 K.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Yi(e){for(let t of e){let i=await K.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!vy(t,i)||await K.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function gy(e,t){let i=Pe.resolve(e),r=Pe.resolve(t);if(!Ps(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Td(i)],a=Pe.relative(i,r).split(Pe.sep).filter(Boolean),o=i;for(let s of a){await Yi(n),o=Pe.join(o,s);try{await K.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Td(o);if(!Ps(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Yi(n),n}async function wy(e){let t;try{t=await K.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function yy(e,t,i={}){let r=Pe.dirname(e),n=i.containedRoot?await gy(i.containedRoot,r):null;n||await K.mkdir(r,{recursive:!0});let a=Pe.join(r,`.${Pe.basename(e)}.${my()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await K.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([K.lstat(a),K.realpath(a)]);if(await Yi(n),!c.isFile()||c.isSymbolicLink()||!Es(s,c)||!Ps(n[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(),!Es(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 Yi(n);let c=await K.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Es(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await K.link(a,e),await K.unlink(a)):await K.rename(a,e),await wy(r)}catch(c){if(await o?.close(),!n)await K.rm(a,{force:!0});else try{await Yi(n),await K.rm(a,{force:!0})}catch{}throw c}}async function xe(e,t,i={}){await yy(e,t,i)}async function fe(e,t,i={}){await xe(e,JSON.stringify(t,null,2)+`
|
|
144
|
+
`,i)}import{existsSync as Id,promises as Pt}from"fs";import A from"path";import Ny from"os";var Bn=".comet/config.yaml",by=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function xs(e){try{return await Pt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ky(e){try{let t=await Pt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Qt(e,t){let i=A.relative(e,t);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function Xt(e){let t=[],i=e;for(;!await xs(i);){let n=A.dirname(i);if(n===i)break;t.push(A.basename(i)),i=n}let r=await Pt.realpath(i);return A.resolve(r,...t.reverse())}async function Rs(e){try{return(await Pt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ln(e){let t=A.resolve(e);try{(await Pt.stat(t)).isDirectory()||(t=A.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=A.resolve(Ny.homedir());for(;;){if(!(t===r&&i!==r)){let o=A.join(t,...Bn.split("/")),s=t===i||await ky(o);if(await xs(o)&&s)return t}if(await xs(A.join(t,".git")))return t;let a=A.dirname(t);if(a===t)return i;t=a}}function Mn(e){return St(e)}async function Sy(e,t){let i=Mn(t),r=A.resolve(e,...i.split("/")),n=await Pt.realpath(e),a=await Xt(r);if(!Qt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function xt(e,t){let i=Mn(t),r=await Sy(e,i),n=A.join(r,"comet");if(await Rs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Xt(r),Xt(n)]);if(!Qt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=A.resolve(e),c=A.join(s,".comet","runtime","native");if(await Rs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Pt.realpath(s),Xt(c)]);if(!Qt(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:A.join(e,...Bn.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:A.join(n,"specs"),changesDir:A.join(n,"changes"),archiveDir:A.join(n,"archive"),runtimeDir:c,changesRuntimeDir:A.join(c,"changes"),locksDir:A.join(c,"locks"),transactionsDir:A.join(c,"transactions")}}function jd(e){if(!by.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ue(e,t){jd(t);let i=A.join(e.changesRuntimeDir,t);if(!X(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Cs(e,t){jd(t);let i=A.join(e.changesDir,t,"runtime");if(!X(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function Oe(e,t){let i=Ue(e,t);if(Id(i))return i;let r=Cs(e,t);return Id(r)?r:i}function He(e,t){let i=A.resolve(t);if(X(e.runtimeDir,i))return e.runtimeDir;if(X(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function X(e,t){return Qt(A.resolve(e),A.resolve(t))}async function B(e,t){let i=A.resolve(e),r=A.resolve(t);if(!Qt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Rs(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Xt(i),Xt(r)]);if(!Qt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function Py(e="docs",t="en"){return In(e,t)}async function De(e){let t=(await Hn(e))?.config??null;return t?.native?t:null}async function Fn(e){let t=await De(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 $d(e){let t=await Ln(e.startPath),i=await De(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Bn} 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=e.explicitArtifactRoot?Mn(e.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??Py(r??"docs"),a=await xt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}var Wn=di(Gt(),1);import{promises as xy}from"node:fs";var Zt="comet.native.v4",Xi="comet.native.local-execution.v4";function As(){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 Ry=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Cy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ay=/^A[1-9][0-9]*$/u,_y=/^[a-f0-9]{64}$/u,Ty=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"]),qn=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 ie(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function re(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function G(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Ts(e,t){return e===null?null:G(e,t)}function Iy(e,t){let i=G(e,t);if(!_y.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ei(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function D(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function jy(e,t){return e===null?null:D(e,t,Number.MIN_SAFE_INTEGER)}function J(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Be(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function zn(e,t){return Be(e,t,(i,r)=>G(i,`${t}[${r}]`))}function Rt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ti(e,t){let i=G(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Is(e,t,i=!1){let r=G(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Re(e,t){let i=ie(e,t);return re(i,new Set(["text","truncated"]),t),{text:G(i.text,`${t}.text`,{empty:!0}),truncated:ei(i.truncated,`${t}.truncated`)}}function $y(e,t){let i=`Native spec_changes[${t}]`,r=ie(e,i);re(r,new Set(["capability","operation","source"]),i);let n=G(r.capability,`${i}.capability`);if(!Cy.test(n))throw new Error(`${i}.capability is invalid`);let a=J(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Is(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 Oy(e){let t="Native workspace",i=ie(e,t);re(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=J(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ts(i.change_branch,`${t}.change_branch`),a=Ts(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:J(i.finish,["merge","push","pull-request","keep"],`${t}.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 Hy(e){let t="Native loop",i=ie(e,t);re(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=zn(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Rt(r,`${t}.previous_unresolved_ids`),{stage:J(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:D(i.goal_cycle,`${t}.goal_cycle`,1),iteration:D(i.iteration,`${t}.iteration`),attempt:D(i.attempt,`${t}.attempt`),retry_epoch:D(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:D(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:D(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:D(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ts(i.next_action,`${t}.next_action`)}}function Dy(e,t){let i=`Native acceptance[${t}]`,r=ie(e,i);re(r,new Set(["id","source","text","result","reason"]),i);let n=G(r.id,`${i}.id`);if(!Ay.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Is(r.source,`${i}.source`),text:G(r.text,`${i}.text`),result:J(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Re(r.reason,`${i}.reason`)}}function By(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ie(e,i);return re(r,new Set(["name","result","note"]),i),{name:Re(r.name,`${i}.name`),result:J(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Re(r.note,`${i}.note`)}}function Ly(e){let t="Native builder_handoff",i=ie(e,t);re(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"]),t);let r=zn(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Rt(r,`${t}.addressed_acceptance_ids`),{candidate_id:G(i.candidate_id,`${t}.candidate_id`),identity_provider:G(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:G(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:D(i.iteration,`${t}.iteration`,1),summary:Re(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Be(i.checks,`${t}.checks`,By),checks_truncated:ei(i.checks_truncated,`${t}.checks_truncated`),known_limits:Be(i.known_limits,`${t}.known_limits`,(n,a)=>Re(n,`${t}.known_limits[${a}]`)),known_limits_truncated:ei(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:ti(i.submitted_at,`${t}.submitted_at`)}}function My(e,t){let i=`Native blockers[${t}]`,r=ie(e,i);re(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=zn(r.acceptance_ids,`${i}.acceptance_ids`);return Rt(n,`${i}.acceptance_ids`),{owner:J(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Re(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:J(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Fy(e,t){let i=`Native verification.checks[${t}]`,r=ie(e,i);return re(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:G(r.id,`${i}.id`),name:Re(r.name,`${i}.name`),argv_display:Be(r.argv_display,`${i}.argv_display`,(n,a)=>Re(n,`${i}.argv_display[${a}]`)),argv_truncated:ei(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Is(r.cwd_ref,`${i}.cwd_ref`,!0),status:J(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:jy(r.exit_code,`${i}.exit_code`),duration_ms:D(r.duration_ms,`${i}.duration_ms`)}}function Vy(e){let t="Native verification",i=ie(e,t);re(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Be(i.checks,`${t}.checks`,Fy);Rt(r.map(a=>a.id),`${t}.checks IDs`);let n=G(i.identity_provider,`${t}.identity_provider`);return{candidate_id:G(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:G(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:D(i.iteration,`${t}.iteration`,1),attempt:D(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":J(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:J(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Re(i.summary,`${t}.summary`),risks:Be(i.risks,`${t}.risks`,(a,o)=>Re(a,`${t}.risks[${o}]`)),risks_truncated:ei(i.risks_truncated,`${t}.risks_truncated`),completed_at:ti(i.completed_at,`${t}.completed_at`)}}function Od(e,t){let i=`Native history[${t}]`,r=ie(e,i);re(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=zn(r.unresolved_ids,`${i}.unresolved_ids`);return Rt(n,`${i}.unresolved_ids`),{goal_cycle:D(r.goal_cycle,`${i}.goal_cycle`,1),iteration:D(r.iteration,`${i}.iteration`),attempt:D(r.attempt,`${i}.attempt`),outcome:J(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Re(r.summary,`${i}.summary`),completed_at:ti(r.completed_at,`${i}.completed_at`)}}function qy(e){let t="Native history_overflow.outcome_counts",i=ie(e,t),r=["pass","fail","blocked","execution-error","recovery"];return re(i,new Set(r),t),{pass:D(i.pass,`${t}.pass`),fail:D(i.fail,`${t}.fail`),blocked:D(i.blocked,`${t}.blocked`),"execution-error":D(i["execution-error"],`${t}.execution-error`),recovery:D(i.recovery,`${t}.recovery`)}}function Wy(e){let t="Native history_overflow",i=ie(e,t);re(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=D(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:ti(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:ti(i.last_dropped_at,`${t}.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=qy(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 zy(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.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(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Jy(e){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"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function P(e){let t=ie(e,"Native portable state");if(re(t,Ty,"Native portable state"),t.schema!==Zt)throw new Error(`Native portable state schema must be ${Zt}`);let i=G(t.name,"Native state name");if(!Ry.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=Be(t.spec_changes,"Native spec_changes",$y);Rt(r.map(s=>s.capability),"Native spec change capabilities");let n=Be(t.acceptance,"Native acceptance",Dy);Rt(n.map(s=>s.id),"Native acceptance IDs");let a=Be(t.history,"Native history",Od);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Zt,name:i,language:J(t.language,["en","zh-CN"],"Native state language"),phase:J(t.phase,["shape","build","verify","archive"],"Native state phase"),status:J(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:D(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Iy(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Oy(t.workspace),loop:Hy(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ly(t.builder_handoff),blockers:Be(t.blockers,"Native blockers",My),verification:t.verification===null?null:Vy(t.verification),history:a,history_overflow:Wy(t.history_overflow),verification_result:J(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:J(t.verification_report,["verification.md"],"Native verification_report"),archived:ei(t.archived,"Native archived"),created_at:ti(t.created_at,"Native created_at")};return zy(o),Jy(o),o}function he(e,t){let i=P(e),r=Od(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return P({...i,history:n,history_overflow:a})}function Gy(e,t){let i=(0,Wn.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ce(e){let t=await xy.readFile(e,"utf8");return P(Gy(t,"Native portable state"))}async function Jn(e,t,i={}){let r=P(t);await xe(e,(0,Wn.stringify)(r),i)}var Vn=new Map;async function Uy(e,t){let i=Vn.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Vn.set(e,a),await i;try{return await t()}finally{r(),Vn.get(e)===a&&Vn.delete(e)}}async function Qi(e){return Uy(e.file,async()=>{let t=D(e.expectedStateVersion,"Native expected state version",1),i=P(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ce(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new qn(t,r.state_version);return await Jn(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ce(e.file);if(n.state_version!==t)throw new qn(t,n.state_version)}}),i})}var Hd="children.yaml",js="comet.native.children.v1",Ky=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Yy=new Set(["schema","children"]),Xy=new Set(["name","depends_on","covers"]);function Dd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bd(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0)throw new Error(`${i} fields are invalid`)}function Ld(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function $s(e,t){let i=pe.normalize(pe.resolve(e)),r=pe.normalize(pe.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Qy(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function Zy(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function eN(e,t){let i=(0,Os.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Dd(i.toJS({mapAsMap:!1}),"Native children contract");if(Bd(r,Yy,"Native children contract"),r.schema!==js)throw new Error(`Native children schema must be ${js}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Dd(s,`Native child ${c}`);if(Bd(l,Xy,`Native child ${c}`),typeof l.name!="string"||!Ky.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:Ld(l.depends_on,`Native child ${l.name} depends_on`),covers:Ld(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return Qy(n),t&&Zy(n,t),{schema:js,children:n}}async function Zi(e){let t=pe.join(e.changeDir,Hd);try{await Fd.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await V({root:e.changeDir,ref:Hd});return{contract:eN(i.text,e.acceptanceIds),size:i.size}}function Gn(e){return te("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function tN(e){let t=Pn(e.projectRoot);t.some(r=>$s(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>pe.resolve(n)))]){let n=await De(r);n&&i.push({projectRoot:r,paths:await xt(r,n.native.artifact_root),parent:$s(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function iN(e,t){let i=pe.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ce(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function rN(e,t){let i;try{i=await Fd.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=pe.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ce(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function nN(e,t,i){let r=pe.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${pe.sep}`))return null;let n=r.split(pe.sep).join("/");try{let a=(0,Os.parseDocument)(ds(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:P(a.toJS({mapAsMap:!1}))}catch{return null}}function aN(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Md(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ct(e){let t=pe.join(e.paths.changesDir,e.state.name),i=await Zi({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=Gn({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await tN(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:h})=>h)),c=new Map,l=new Map;for(let h of a){let v=h.parent&&o?`refs/heads/${o}`:"HEAD";for(let g of await rN(h,s)){let w={...g,source:h,committedState:nN(h,g.file,v)};c.set(g.state.name,[...c.get(g.state.name)??[],w])}for(let g of s){let w=await iN(h,g);w&&l.set(g,[...l.get(g)??[],{source:h,state:w}])}}let f=new Map;for(let h of i.contract.children){let v=(c.get(h.name)??[]).find(({source:N,committedState:k})=>N.parent&&k?.name===h.name&&Md(k,o));if(v){f.set(h.name,{kind:"done",phase:v.state.phase,projectRoot:v.source.projectRoot,message:null});continue}let g=c.get(h.name)?.[0];if(g){f.set(h.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=l.get(h.name)??[];w.length>1?f.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):w[0]&&f.set(h.name,aN(w[0].state,w[0].source,o))}let d=new Map(i.contract.children.map(h=>[h.name,h])),u=new Map,p=h=>{let v=u.get(h);if(v)return v;let g=d.get(h),N=g.depends_on.map(p).every(({status:O})=>O==="done"),k=f.get(h),E=k?.kind==="active"&&N?g.depends_on.filter(O=>!(c.get(O)??[]).some(({source:Ie,committedState:ze})=>$s(Ie.projectRoot,k.projectRoot)&&ze?.name===O&&Md(ze,o))):[],S,R=k?.message??null;k?.kind==="done"?(S=N?"done":"blocked",N||(R=`Native child ${h} was merged before its dependencies`)):k?.kind==="active"?(S=N&&E.length===0?"active":"blocked",N?E.length>0&&(R=`Native child ${h} does not include merged dependencies: ${E.join(", ")}`):R=`Native child ${h} started before its dependencies merged`):k?.kind==="blocked"?S="blocked":(S=n&&N?"ready":"pending",n||(R="Parent Shape confirmation is required"));let b={name:h,dependsOn:[...g.depends_on],covers:[...g.covers],status:S,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:R};return u.set(h,b),b},m=i.contract.children.map(({name:h})=>p(h));return{contractHash:r,confirmed:n,parentBranch:o,children:m,readyChildren:m.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:m.every(({status:h})=>h==="done")}}function me(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",e.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")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.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")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.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(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?["comet","native","next",e.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(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",e.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(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.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:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.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(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.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:e.loop.iteration,attempt:e.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:e.loop.iteration,attempt:e.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:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.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",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as Wk}from"node:crypto";import{promises as br}from"node:fs";import zk from"node:path";var nc=di(Gt(),1);import ni from"path";import{promises as lb}from"fs";import ub from"path";import{AsyncLocalStorage as oN}from"async_hooks";import{randomUUID as Wd}from"crypto";import{promises as ve}from"fs";import zd from"os";import Q from"path";var Vd=16*1024,Jd=".coordinator",sN=5e3,qd=new oN,Un=new Map;function cN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function lN(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 Gd(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 Hs(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ae(i,r)?$(i,r):$(i,r)&&e.size===t.size}function Ds(e,t){return Hs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ke(e){let t,i;try{let r=await Kt(e,Vd,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Ee?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${Vd} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:lN(JSON.parse(t.toString("utf8")),e),identity:Gd(i)}}async function uN(e){return(await Ke(e))?.owner??null}function Ud(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==zd.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=vN(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dN(e,t){try{await ve.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ve.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Bs(e,t){let i=await Ke(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ds(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ve.mkdir(t,{recursive:!0});let r=Q.join(t,`${Q.basename(e.file)}.${e.owner.id}.${Wd()}.removed`);try{await ve.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ke(r);if(!n||n.owner.id!==e.owner.id||!Hs(n.identity,e.identity))throw await dN(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ve.rm(r,{force:!0}),"removed"}function Kd(e){return{id:Wd(),pid:process.pid,hostname:zd.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Yd(e,t){let i;try{i=await ve.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await uN(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
145
|
+
`,"utf8"),await i.sync(),Gd(await i.stat({bigint:!0}))}finally{await i.close()}}async function fN(e,t){let i=await B(e.runtimeDir,e.locksDir);await ve.mkdir(i,{recursive:!0});let r=await B(e.runtimeDir,Q.join(i,Jd));await ve.mkdir(r,{recursive:!0});let n=Kd(t),a=Q.join(r,`.${n.id}.tmp`),o=Q.join(r,`${n.id}.claim`);try{let s=await Yd(a,n);await ve.rename(a,o);let c=await Ke(o);if(!c||!Hs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await ve.rm(a,{force:!0})}}async function hN(e){let t=Q.dirname(e.file),i=!1,r=Q.basename(e.file);for(let n of await ve.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Q.join(t,n.name);if(Q.resolve(a)!==Q.resolve(e.file))try{let o=await Ke(a),s=Ud(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Bs(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function Xd(e){let t=await Ke(e.file);if(t){if(t.owner.id!==e.owner.id||!Ds(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Bs(t,Q.dirname(e.file))}}async function pN(e,t){let i=Date.now()+sN;for(;;){let r=await fN(e,t);if(!await hN(r))return r;if(await Xd(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function mN(e){let t=Un.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Un.set(e,n),await t,()=>{i(),Un.get(e)===n&&Un.delete(e)}}async function Qd(e,t,i){let r=Q.resolve(e.locksDir),n=qd.getStore();if(n?.has(r))return i();let a=await mN(r);try{let o=await pN(e,t),s=new Map(n??[]);return s.set(r,o),await qd.run(s,async()=>{try{return await i()}finally{await Xd(o)}})}finally{a()}}async function Kn(e,t,i){return Qd(e,`acquire ${t}`,async()=>{let r=await B(e.runtimeDir,e.locksDir);await ve.mkdir(r,{recursive:!0});let n=await B(e.runtimeDir,Q.join(r,cN(t))),a=Kd(i),o=await Yd(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Yn(e){await Ke(e.file)&&await Qd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Q.basename(e.file)}`,async()=>{let t=await Ke(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ds(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=Q.join(e.locksDir,Jd);await Bs(t,i)})}function vN(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Zd(e){return Ud(await Ke(e))}import Gs from"node:path";import kN from"node:path";import tf from"node:path";var gN="comet.native.acceptance.v1";var zx=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ir=Object.freeze({maxCriteria:1024});function Ms(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 Ls(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function ef(e){return e.includes("-->")||e.includes("--!>")}function*er(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.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:t===null&&!i&&
|
|
166
|
-
`))),"Brief")}function
|
|
167
|
-
`),a.context)),a=null}};for(let{line:s,body:c}of yn(e)){let l=c?ku(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=bu(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(),Eu(n,"Specification")}function av(e,t="spec.md",i=Gr.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(Su("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 yn(e)){let d=u?ku(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||Nu(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 h=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(h){s(),o={parts:[h[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(),Eu(n,"Specification mandatory requirements")}function uP(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||cP(i)||Xm.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=Xm.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(!tP.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function dP(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=>!eP.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function ov(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=dP(i,n),a=r.acceptance_id;if(typeof a!="string"||!ZR.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 uP(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 sv(e){let t=sP(e);if(t.some(({line:l,body:u})=>!u&&(l===Qm||l===Zm)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===Qm?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===Zm?[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=ov(o),c=fP(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function fP(e){let t=ov([...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 cv from"node:path";var hP="comet.native.contract.v1",pP="comet.native.acceptance-set.v1",lv=/^[a-f0-9]{64}$/u,Ur={maxAcceptanceCriteria:Gr.maxCriteria};function uv(e,t){let i=cv.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})||cv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function dv(e){return _("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
169
|
-
`))}function mP(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(lv))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(lv))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=uv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:dv(e.markdown)},markdown:e.markdown}}function vP(e,t){return fv(e.id,t.id)}function fv(e,t){return e<t?-1:e>t?1:0}function hv(e){let t=uv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(mP).sort((d,f)=>fv(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=nv(e.briefMarkdown,t,Ur.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...rv(f,d.source,Ur.maxAcceptanceCriteria-a.length)),a.push(...av(f,d.source,Ur.maxAcceptanceCriteria-a.length)));if(a.sort(vP),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ur.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ur.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:dv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=_(pP,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:_(hP,u)}}var Ti={maxSpecs:64,maxFileBytes:fr,maxTotalBytes:4*1024*1024};async function Te(e){if(e.specChanges.length>Ti.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await he({root:e.changeDir,ref:e.briefRef,maxBytes:Ti.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 he({root:e.changeDir,ref:r.source,maxBytes:Ti.maxFileBytes});if(i+=a.size,i>Ti.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:hv({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import gP from"path";var Cu="comet.selection.v2",wP=16*1024;function mv(e){return gP.join(e,".comet","current-change.json")}function yP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pv(e){return e===null||typeof e=="string"}function NP(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(!yP(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&&!pv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Cu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Cu)throw new Error(`current change selection schema must be ${Cu}`);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(!pv(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 vv(e){let t;try{let n=mv(e),{bytes:r}=await bi(n,wP,{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",...NP(t)}}var g$=16*1024;async function gv(e){let t=await vv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(mn(t.selection.change),t.selection)}import bP from"path";function Ru(e,t){return bP.resolve(e,...t.split(/[\\/]/u))}async function Xo(e,t){let i=[],n=T(e,t.name),r=Ru(n,xe.stateRef),a;try{a=await Be(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=Ru(n,a.trajectoryRef),s=await cu(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 Le(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=Ru(n,a.checkpointRef);try{let u=await qo(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 NA}from"crypto";import{promises as bA}from"fs";import kA from"path";import{isDeepStrictEqual as qu}from"util";var kP=/\b(Bearer|Basic)\s+[^\s"']+/giu,SP=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,EP=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,CP=/\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,RP=/("(?:[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,PP=/(["'])((?:[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,AP=/\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 ue(e){return e.replace(kP,"$1 [REDACTED]").replace(SP,"[REDACTED PRIVATE KEY]").replace(EP,"$1[REDACTED]@").replace(CP,"[REDACTED TOKEN]").replace(RP,'$1"[REDACTED]"').replace(PP,"$1$2$1$3$4[REDACTED]$4").replace(AP,"$1$2[REDACTED]")}var xP="comet.native.repair-signature.v1",_e={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3},IP="comet.native.repair-signature.v1",TP="comet.native.repair-override-summary.v1",_P=/^[a-f0-9]{64}$/u,jP=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function yv(e,t){return e<t?-1:e>t?1:0}function Qo(e,t){if(typeof e!="string"||!_P.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Pu(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zo(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"||!jP.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(yv)}function Nn(e=[]){return Zo(e,"Native repair failed check IDs",_e.maxFailedCheckIds,!0)}function Nv(e){let t=Nn(e.failedCheckIds),i=Zo(e.failedAcceptanceIds,"Native repair failed acceptance IDs",_e.maxFailedAcceptanceIds,!0),n={schema:xP,contractHash:Qo(e.contractHash,"Native repair contract hash"),failedAcceptanceIds:i,failedCheckIds:t};return{...n,signatureHash:_(IP,n)}}function OP(e){if(!Array.isArray(e)||e.length>_e.maxHistoryRecords)throw new Error("Native repair history exceeds its record boundary");let t=0,i=0;return e.map((n,r)=>{if(!n||n.kind!=="failure"&&n.kind!=="override")throw new Error(`Native repair history record ${r} is invalid`);let a=n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?["iteration","kind","revision","signatureHash"]:["failedAcceptanceIds","failedCheckIds","iteration","kind","revision","signatureHash"]:["iteration","kind","revision","signatureHash","summaryHash"],o=Object.keys(n).sort(yv);if(o.length!==a.length||o.some((f,h)=>f!==a[h]))throw new Error(`Native repair history record ${r} fields are invalid`);let s=Pu(n.iteration,`Native repair history ${r} iteration`),c=Pu(n.revision,`Native repair history ${r} revision`),l=r>0?e[r-1]:null;if(!(n.kind==="override"&&l?.kind==="failure"&&s===t&&c>=i&&n.signatureHash===l.signatureHash)&&(s<=t||c<=i))throw new Error("Native repair history must be strictly ordered by revision and iteration");t=s,i=c;let d=Qo(n.signatureHash,`Native repair history ${r} signature`);return n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?{kind:"failure",iteration:s,revision:c,signatureHash:d}:{kind:"failure",iteration:s,revision:c,signatureHash:d,failedAcceptanceIds:Zo(n.failedAcceptanceIds??[],`Native repair history ${r} failed acceptance IDs`,_e.maxFailedAcceptanceIds,!0),failedCheckIds:Zo(n.failedCheckIds??[],`Native repair history ${r} failed check IDs`,_e.maxFailedCheckIds,!0)}:{kind:"override",iteration:s,revision:c,signatureHash:d,summaryHash:Qo(n.summaryHash,`Native repair history ${r} summary`)}})}function wv(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function HP(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:wv(e.failedAcceptanceIds,t.failedAcceptanceIds)&&wv(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Kr(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(HP(n,a))break;i+=1,n=a}return i}function bv(e){let t=e.trim();if(t.length===0||t.length>_e.maxOverrideSummaryCharacters)throw new Error("Native repair override summary is invalid");return t}function es(e){return _(TP,{summary:bv(e)})}function kv(e){let t=Nv(e.facts),i=OP(e.history),n=i.filter(l=>l.kind==="failure"),r=n.length+1,a=Pu(e.maxVerifyFailures,"Native maximum Verify failures"),o=Math.max(0,a-r),s=Kr({signatureHash:t.signatureHash,failedAcceptanceIds:t.failedAcceptanceIds,failedCheckIds:t.failedCheckIds},n);if(r>=a)return{disposition:"hard-stop",reasonCode:"repair-iteration-limit",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(s<_e.warningAtConsecutiveFailures)return{disposition:"continue",reasonCode:"new-failure-signature",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(s<_e.manualStopAtConsecutiveFailures)return{disposition:"warn",reasonCode:"repeated-failure-warning",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(e.override){if(Qo(e.override.expectedSignatureHash,"Native repair override expected signature")!==t.signatureHash)throw new Error("Native repair override does not match the current failure signature");bv(e.override.summary);let u=i.some(d=>d.kind==="override"&&d.signatureHash===t.signatureHash);return{disposition:u?"manual-stop":"continue",reasonCode:u?"override-already-used":"override-accepted",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!u}}return{disposition:"manual-stop",reasonCode:i.some(l=>l.kind==="override"&&l.signatureHash===t.signatureHash)?"override-already-used":"repeated-failure-stop",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1}}import Dv from"node:path";import{createHash as xv}from"node:crypto";import Sv from"path";var Au="comet.native.implementation-scope.v2",Iv="comet.native.content-snapshot-projection.v1",Yr="comet.native.content-snapshot-projection.v1",Tv="comet.native.implementation-scope.v2",$P="comet.native.unresolved-scope-id.v1",FP="comet.native.scope-detail-overflow.v1",DP="comet.native.snapshot-projection-overflow.v2",_u=/^[a-f0-9]{64}$/u,ji=1024*1024,MP=128,BP=128;function me(e,t){return e<t?-1:e>t?1:0}function xu(e){if(!_u.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function LP(e,t){return e===t?0:e===null?-1:t===null?1:me(e,t)}function ri(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=Sv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Sv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function _v(e,t){return e==="."?e:ri(e,t)}function bn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function qP(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:ri(e.path,`${t} path`),hash:e.hash,size:bn(e.size,`${t} size`),type:"file"}}function VP(e,t){return{path:_v(e.path,`${t} path`),size:e.size===null?null:bn(e.size,`${t} size`),type:e.type,reason:e.reason}}function WP(e,t){return me(e.path,t.path)||me(e.hash,t.hash)||e.size-t.size}function zP(e,t){return me(e.path,t.path)||me(e.reason,t.reason)||me(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Xr(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
170
|
-
`,"utf8")}function ni(e,t,i){let n=`${t}
|
|
171
|
-
${
|
|
172
|
-
`),
|
|
173
|
-
`);let i=0;jv(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){ni(t,"change",r);let a=0;for(let o of e.declaredArtifacts)rs(o,r.path)&&(a+=1,ni(t,"change-attribution",o));ni(t,"change-end",{attributionCount:a}),a===0&&ni(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&&ni(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function $v(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=XP(e,t,r,i.gitChangedPaths),s=_(Yr,e),c=_(Yr,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let v of w.omitted){if(l.length>=BP)break;l.push(Rt({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=[...Cv("baseline",e),...Cv("current",t),...o.totalChanges===0&&a===null?[Rt({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))}},h=y=>{let w=o.candidates.slice(0,y.detailedChangeCount),v=w.filter(ct=>ct.attributedTo.length===0),E=o.totalChanges-w.length,j=o.totalUnattributed-v.length,V=u-y.detailedOmissionCount,L=j+V,J=[...v.map(ct=>Rt({kind:"unattributed-change",source:"implementation-scope",path:ct.path,evidence:{after:ct.after,before:ct.before,changeKind:ct.kind}},`Changed path is not covered by a declared artifact: ${ct.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||L>0?[Hv(y.overflowHash,{changes:E,unattributed:j,unresolved:L})]:[]],K=KP(J),st=y.includeGitAdvisory?f():void 0;return{schema:Au,contractHash:n,baselineProjectionRef:xu(s),baselineProjectionHash:s,currentProjectionRef:xu(c),currentProjectionHash:c,complete:K.length===0,declaredArtifacts:r,changes:w,unattributed:v,unresolvedScopes:K,noCodeReason:a,...st?{gitAdvisory:st}:{}}},m=o.candidates.length,p=l.length,g=i.gitChangedPaths!==void 0,S="0".repeat(64);for(;;){let y=h({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:g,overflowHash:S});if(Xr({...y,scopeHash:S})<=ji)break;if(g){g=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>m||u>p?ZP({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:p}):S,b=h({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:g,overflowHash:N}),C={...b,scopeHash:_(Tv,b)};if(Xr(C)>ji)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return C}function ai(e){let t=Iu(e.baseline),i=Iu(e.current),n=Ov(e);return{authority:n,baseline:t,current:i,scope:$v(t,i,n)}}var eA=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Pt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function At(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 _i(e,t){if(typeof e!="string"||!_u.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Rv(e,t,i){let n=xu(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function is(e,t){let i=Pt(e,"Native snapshot projection");if(At(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Iv)throw new Error("Native snapshot projection schema is invalid");let n=Si({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=Iu(n);if(_(Yr,i)!==_(Yr,r))throw new Error("Native snapshot projection is not canonical");let a=_(Yr,r);if(t!==void 0&&_i(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function ju(e,t){let i=Pt(e,`Declared artifact ${t}`);if(At(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ri(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Pv(e,t){if(e===null)return null;let i=Pt(e,t);return At(i,["hash","size"],[],t),{hash:_i(i.hash,`${t} hash`),size:bn(i.size,`${t} size`)}}function Av(e,t){let i=Pt(e,`Implementation change ${t}`);if(At(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(ju),r=ns(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Pv(i.before,`Implementation change ${t} before`),o=Pv(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:ri(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function tA(e,t){let i=Pt(e,`Unresolved scope ${t}`);At(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"?_v(i.path,`Unresolved scope ${t} path`):ri(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function ts(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)=>ri(r,`${t} ${a}`)),n=[...new Set(i)].sort(me);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function as(e){let t=Pt(e,"Native implementation scope"),i=[...eA].filter(w=>w!=="gitAdvisory");if(At(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==Au)throw new Error("Native implementation scope schema is invalid");let n=_i(t.contractHash,"Implementation scope contractHash"),r=_i(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Rv(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=_i(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Rv(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(ju);if(JSON.stringify(c)!==JSON.stringify(ns(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Av),u=[...l].sort((w,v)=>me(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=>rs(v,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Av),h=l.filter(w=>w.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(tA),p=m.filter(w=>w.kind==="scope-detail-overflow");if(p.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=p[0]===void 0?null:QP(p[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,k=[...h.map(w=>Rt({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?[Rt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],N=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Tu))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(N)!==JSON.stringify(k.sort(Tu))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=Pt(t.gitAdvisory,"Implementation scope Git advisory");if(At(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=ts(w.changedPaths,"Git changed paths"),E=ts(w.pathsPresentInSnapshotChanges,"Git present paths"),j=ts(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),V=[...E,...j].sort(me),L=new Set(l.map(J=>J.path));if(JSON.stringify(V)!==JSON.stringify(v)||(g?.changes??0)===0&&E.some(J=>!L.has(J))||j.some(J=>L.has(J)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:v,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:j}}let C={schema:Au,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=_i(t.scopeHash,"Implementation scope scopeHash");if(_(Tv,C)!==y)throw new Error("Implementation scope content hash mismatch");return{...C,scopeHash:y}}function iA(e){let t=Pt(e,"Native implementation scope authority");if(At(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(ju);if(JSON.stringify(i)!==JSON.stringify(ns(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=ts(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Ov({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 tt(e){let t=Pt(e,"Native implementation scope bundle");At(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=iA(t.authority),n=is(t.baseline),r=is(t.current),a=as(t.scope),o=$v(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 Fv(e){let t=as(e.scope);return tt({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 Mv=/^[a-f0-9]{64}$/u,nA=8,Bv="comet.native.acceptance-trace.v2",Lv="comet.native.partial-allowance.v1",qv="comet.native.verification-evidence.v2";function qe(e,t){if(!Mv.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ls(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function us(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 kn(e,t,i=2e3){let n=ue(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function oi(e,t){let i=Dv.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})||Dv.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 Vv(e,t,i){let n=oi(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=dt(n),a=n.toLowerCase(),o=i?oi(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 Qr(e){let t=oi(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 Wv(e){let t=e.toISOString();if(Number.isNaN(Date.parse(t)))throw new Error("Native evidence timestamp is invalid");return t}function rA(e){return _("comet.native.acceptance-set.v1",[...e].sort((t,i)=>Ve(t.id,i.id)))}function Ve(e,t){return e<t?-1:e>t?1:0}function zv(e,t,i){let n=oi(i.nativeRootRef,"Native root ref"),r=new Map(e.map(u=>[u.id,u]));if(r.size!==e.length)throw new Error("Native contract has duplicate acceptance IDs");let a=new Map;for(let u of t){if(!r.has(u.acceptance_id))throw new Error(`Verification references unknown acceptance ID: ${u.acceptance_id}`);if(a.has(u.acceptance_id))throw new Error(`Verification repeats acceptance ID: ${u.acceptance_id}`);a.set(u.acceptance_id,u)}let o=[...r.keys()].filter(u=>!a.has(u));if(o.length>0&&i.allowMissing!==!0){let u=o.slice(0,nA),d=o.length-u.length;throw new Error(`Verification is missing ${o.length} acceptance evidence entr${o.length===1?"y":"ies"}: ${u.join(", ")}${d>0?`, ... (${d} more)`:""}`)}let s=[...r.values()].sort((u,d)=>Ve(u.id,d.id)).map(u=>{let d=a.get(u.id);if(!d)return{acceptanceId:u.id,status:"missing",kind:u.kind,source:oi(u.source,`Acceptance source for ${u.id}`),evidenceRefs:[],skippedReason:null};let f=d.status,h=[...d.evidence_refs].map(g=>Qr(g)).sort();if(new Set(h).size!==h.length)throw new Error(`Verification repeats an evidence ref for ${u.id}`);let m=d.skipped_reason?.trim()||null,p=m===null?null:kn(m,`Skipped reason for ${u.id}`);if(f==="passed"&&(h.length===0||p!==null)||f==="failed"&&h.length===0&&p===null)throw new Error(`Acceptance ${u.id} has an invalid evidence state`);return{acceptanceId:u.id,status:f,kind:u.kind,source:oi(u.source,`Acceptance source for ${u.id}`),evidenceRefs:h,skippedReason:p}}),c=rA(e),l={schema:"comet.native.acceptance-trace.v2",nativeRootRef:n,criteriaHash:c,total:s.length,evidenced:s.filter(u=>u.evidenceRefs.length>0).length,skipped:s.filter(u=>u.skippedReason!==null).length,entries:s};return{...l,traceHash:_(Bv,l)}}function Jv(e){let t=tt(e.scopeBundle).scope;if(t.complete)throw new Error("Complete implementation scope cannot be partially allowed");let i=new Set(t.unresolvedScopes.map(s=>s.id));if(new Set(e.allowedScopeIds).size!==e.allowedScopeIds.length)throw new Error("Partial allowance has duplicate allowed scope IDs");let n=[...e.allowedScopeIds].sort(Ve);if(n.length===0)throw new Error("Partial allowance requires at least one scope ID");if([...i,...n].some(s=>!/^scope:[a-f0-9]{64}$/u.test(s)))throw new Error("Partial allowance scope IDs are invalid");let r=n.filter(s=>!i.has(s)),a=[...i].filter(s=>!n.includes(s));if(r.length>0)throw new Error(`Partial allowance has unknown scope IDs: ${r}`);if(a.length>0)throw new Error(`Partial allowance is missing scope IDs: ${a}`);let o={schema:"comet.native.partial-allowance.v1",change:us(e.change),scopeHash:t.scopeHash,scopeIds:n,reason:kn(e.reason,"Partial allowance reason"),confirmedSummary:kn(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:ls(e.sourceRevision),confirmedAt:Wv(e.now??new Date)};return{...o,allowanceHash:_(Lv,o)}}function Gv(e){if(e.result!=="pass"&&e.result!=="fail")throw new Error("Native verification evidence result is invalid");let t=Kv(e.acceptanceTrace),i=tt(e.implementationScope.bundle).scope,n=cs(e.implementationScope.ref,"scopes",i.scopeHash);if(i.contractHash!==e.contractHash)throw new Error("Implementation scope does not match the verification contract");let r=e.partialAllowance??null,a=r?Ou(r.allowance):null,o=r&&a?{ref:cs(r.ref,"allowances",a.allowanceHash),allowance:a}:null;if(i.complete&&o!==null)throw new Error("Complete implementation scope must not use a partial allowance");if(!i.complete&&o===null)throw new Error("Partial implementation scope requires a confirmed allowance");let s=i.unresolvedScopes.map(f=>f.id).sort(Ve);if(o&&(o.allowance.change!==e.change||o.allowance.scopeHash!==i.scopeHash||JSON.stringify(o.allowance.scopeIds)!==JSON.stringify(s)))throw new Error("Partial allowance does not match the verification scope");if(t.criteriaHash!==e.acceptanceHash)throw new Error("Acceptance trace does not match the verification contract");if(o&&o.allowance.sourceRevision>=e.sourceRevision)throw new Error("Partial allowance must precede the verification evidence revision");let c=[...new Set(t.entries.flatMap(f=>f.evidenceRefs))].sort(Ve),l=[...new Set(e.requiredReceiptRefs.map(Qr))].sort(Ve),u=c;if(e.result==="pass"&&l.length===0)throw new Error("Passing verification requires at least one current required check receipt");let d={schema:"comet.native.verification-evidence.v2",change:us(e.change),sourceRevision:ls(e.sourceRevision),result:e.result,freshness:i.complete?"complete":"partial",contractHash:qe(e.contractHash,"Verification contractHash"),acceptanceCriteriaHash:qe(e.acceptanceHash,"Verification acceptanceHash"),implementationScopeRef:n,implementationScopeHash:i.scopeHash,reportRef:Vv(e.reportRef,"Verification report ref"),reportHash:qe(e.reportHash,"Verification report hash"),acceptanceTrace:t,partialAllowanceRef:o?.ref??null,partialAllowanceHash:o?.allowance.allowanceHash??null,requiredReceiptRefs:l,receiptRefs:u,createdAt:Wv(e.now??new Date)};return{...d,envelopeHash:_(qv,d)}}function os(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ss(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 Uv(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 cs(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 Kv(e){let t=os(e,"Native acceptance trace");if(ss(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"||!Mv.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=oi(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=os(o,`Native acceptance trace entry ${s}`);if(ss(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=>Qr(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ve))||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:oi(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:kn(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>Ve(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=qe(t.traceHash,"Native acceptance trace hash");if(_(Bv,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Ou(e){let t=os(e,"Native partial allowance");if(ss(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(Ve))||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:us(t.change),scopeHash:qe(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:kn(t.reason,"Partial allowance reason"),confirmedSummary:kn(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:ls(t.sourceRevision),confirmedAt:Uv(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=qe(t.allowanceHash,"Native partial allowance hash");if(_(Lv,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function ds(e){let t=os(e,"Native verification evidence");if(ss(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=qe(t.implementationScopeHash,"Native verification implementation scope hash"),n=Kv(t.acceptanceTrace),r=qe(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:qe(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Qr(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ve)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(Ve);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=>Qr(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ve)))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:us(t.change),sourceRevision:ls(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:qe(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:cs(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:Vv(t.reportRef,"Native verification report ref"),reportHash:qe(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:cs(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Uv(t.createdAt,"Native verification timestamp")},d=qe(t.envelopeHash,"Native verification envelope hash");if(_(qv,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Oi(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 Yv="repairStagnation",je={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},oA=/^[a-f0-9]{64}$/u,Xv="comet.native.repair-scope.v1",sA=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),cA=["data","runId","sequence","timestamp","type"],Qv=["disposition","overrideSummaryHash","signatureHash"],lA=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Zv=12;function fs(e,t){return e<t?-1:e>t?1:0}function $u(e,t,i){let n=Object.keys(e).sort(fs);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function Zr(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 Sn(e,t){if(typeof e!="string"||!oA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function uA(e){if(!Array.isArray(e)||e.length>_e.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(fs)}function En(e){let t=tt(e).scope;return _(Xv,{schema:Xv,contractHash:t.contractHash,artifactSnapshotHash:t.currentProjectionHash})}function eg(e){if(typeof e!="string"||e.length===0||e.length>je.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 Hu(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>je.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>je.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>je.maxTextCharacters&&(!r||e.length>je.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>je.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>je.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Hu(s,t+1,i,`${n}[${c}]`));return}let a=Zr(e,n),o=Object.keys(a);if(o.length>je.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>je.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>je.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Hu(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function dA(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 fA(e,t,i){let n=Zr(e,`Native repair trajectory event ${t+1}`);if($u(n,cA,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(dA(n.timestamp),typeof n.type!="string"||!sA.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(eg(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 Hu(n.data,0,r,"Native trajectory event data"),Zr(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Fu(e){let t=Zr(e,"Native repair trajectory projection"),i=Object.keys(t).sort(fs),n=i.length===Qv.length&&i.every((l,u)=>l===Qv[u]);n||$u(t,lA,"Native repair trajectory projection");let r=Sn(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:Sn(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=Sn(t.contractHash,"Native repair trajectory contract hash"),s=uA(t.failedAcceptanceIds),c=Nn(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 hA(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 pA(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??Zv;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Kr({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<_e.warningAtConsecutiveFailures?"continue":a<_e.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function mA(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??Zv;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 hs(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>je.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=eg(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=fA(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>je.maxTotalDataNodes||c>je.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?Sn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Sn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Yv)){if(n?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&r!==null&&h!==r||h===null&&(n?.disposition==="manual-stop"||n?.disposition==="hard-stop"))){i.length=0,n=null,r=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Fu(f[Yv]);if(hA(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&&h!==null&&r!==null&&h!==r&&(i.length=0,o=0),h!==null&&(r=h),pA(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&&h!==null&&r!==null&&h!==r)throw new Error("Native repair override cannot cross implementation scope progress");mA(m,i,n);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(n=m,i.length>_e.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function tg(e){return hs(e).history}function ig(e){let t=hs(e).latestProjection;return t?{...t}:null}function ng(e){let t=hs(e),i=Zr(e.override,"Native repair override request");$u(i,["expectedSignatureHash","summary"],"Native repair override request");let n=Sn(i.expectedSignatureHash,"Native repair override expected signature");if(typeof i.summary!="string")throw new Error("Native repair override summary is invalid");if(t.latestProjection?.disposition==="hard-stop")throw new Error("Native repair hard stop cannot be overridden");if(t.latestProjection?.disposition!=="manual-stop"||t.latestProjection.signatureHash!==n)throw new Error("Native repair override does not match the latest manual stop");if(t.history.some(a=>a.kind==="override"&&a.signatureHash===n))throw new Error("Native repair signature was already overridden");let r=es(i.summary);return{history:t.history,eventProjection:{signatureHash:n,disposition:"continue",overrideSummaryHash:r,contractHash:t.latestProjection.contractHash,failedAcceptanceIds:[...t.latestProjection.failedAcceptanceIds],failedCheckIds:[...t.latestProjection.failedCheckIds],maxVerifyFailures:t.latestProjection.maxVerifyFailures}}}function vA(e){let t=ds(e.envelope),i=tt(e.implementationScope);if(t.result!=="fail")throw new Error("Native repair stagnation requires a failed verification envelope");if(t.contractHash!==i.scope.contractHash||t.implementationScopeHash!==i.scope.scopeHash)throw new Error("Native repair evidence does not match the implementation scope authority");return{contractHash:i.scope.contractHash,implementationScopeHash:En(i),artifactSnapshotHash:i.scope.currentProjectionHash,failedAcceptanceIds:t.acceptanceTrace.entries.filter(n=>n.status==="failed"||n.status==="missing").map(n=>n.acceptanceId).sort(fs),failedCheckIds:Nn(e.failedCheckIds)}}function gA(e,t){return{signatureHash:e.signature.signatureHash,disposition:e.disposition,overrideSummaryHash:t,contractHash:e.signature.contractHash,failedAcceptanceIds:[...e.signature.failedAcceptanceIds],failedCheckIds:[...e.signature.failedCheckIds],maxVerifyFailures:e.totalRepairFailures+e.remainingIterations}}function wA(e){let t=vA(e),i=hs(e);return{facts:t,history:i.latestProjection?.contractHash!==null&&i.latestProjection?.contractHash!==t.contractHash?[]:i.history}}function rg(e){let t=wA(e),i=kv({...t,maxVerifyFailures:e.maxVerifyFailures});return{...t,decision:i,eventProjection:gA(i,null)}}var mt={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:[]},ea=G("comet-native-runtime:v3:semantic-repair-budget"),yA=[{skillVersion:"2",skillHash:G("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:G("comet-native-runtime:v1")}];function ag(e){return e.skillVersion===mt.definition.metadata.version&&e.skillHash===ea||yA.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var ps={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function ms(e){let i={sequence:(await Le(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 xm(e.changeDir,e.run.trajectoryRef,i),i}async function Du(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:G(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Im(e.changeDir,e.run.checkpointRef,t),t}function vs(e){return G(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 hg=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],SA=new Set(hg),pg=new Set([...hg,"minimum_runtime_version","revision"]),EA=new Set([...pg,"operation"]),CA=512*1024,Mu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),RA=new Set([...Mu,"implementationScopeHash","repairScopeHash","repairStagnation"]),Bu=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 ta(e,t){return kA.join(T(e,t),"runtime","transition.json")}function PA(e){return`transition-${e}`}async function AA(e,t,i){let n=PA(t);return Sr(e,n,i)}async function Hi(e,t,i,n){let r=await AA(e,t,i);try{return await n()}finally{await Er(r)}}function ws(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Vu(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 gs(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function vt(e,t){return qu(e,t)}function Lu(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=>!RA.has(u)),a=[...Mu].find(u=>!Object.hasOwn(i,u)),o=Mu.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(Oi(i.summary,"Native transition journal event summary"),ue(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&&(Oi(i.noCodeReason,"Native transition journal event no-code reason"),ue(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")?Fu(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 xA(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 Lu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Lu(e,t)}function Wu(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?xA(e.eventData,e.evidenceHash):Lu(e.eventData,e.evidenceHash),r=nu(e.nextRun),a=e.previousRun===null?null:nu(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function og(e,t,i=!1){if(e.skill!==mt.definition.metadata.name||(i?!ag(e):e.skillVersion!==mt.definition.metadata.version||e.skillHash!==ea)||e.orchestration!==mt.definition.orchestration.mode||e.pendingRef!==xe.pendingRef||e.trajectoryRef!==xe.trajectoryRef||e.contextRef!==xe.contextRef||e.artifactsRef!==xe.artifactsRef||e.checkpointRef!==xe.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function sg(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 cg(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 zu(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(og(a,"next Run",n||r!==null),cg(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(og(r,"previous Run",!0),cg(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(!qu(sg(r),sg(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function IA(e,t,i){return G(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function mg(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function lg(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Ju(e,t,i,n,r=!1){let a=i.eventData,o=lg(e),s=lg(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&&qu(e.spec_changes,t.spec_changes),l=vs({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=IA(e.name,a.summary,t.spec_changes),l=G(`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 vg(e,t){let i=ws(e);if(Vu(i,EA),i.schema!==Pi)throw new Error(`Expected Native transition schema ${Pi}`);let n=gs(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 ${Pi} minimum_runtime_version must be ${3}`);let r=gs(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=Wu(i,t),o=Et(i.previousState),s=Et(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Ju(o,s,a,i.operation),zu(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Pi,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 TA(e,t){let i=ws(e);if(Vu(i,SA),i.schema!==$r)throw new Error(`Expected Native transition schema ${$r}`);let n=Wu(i,t,!0),r=Lr(i.previousState),a=Lr(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Ju(r,a,n,mg(r,a,n.eventData),!0),zu(r,a,n,!0),{schema:$r,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 _A(e,t){let i=ws(e);if(Vu(i,pg),i.schema!==pn)throw new Error(`Expected Native transition schema ${pn}`);if(gs(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${pn} minimum_runtime_version must be 2`);let r=gs(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Wu(i,t,!0),o=qr(i.previousState),s=qr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Ju(o,s,a,mg(o,s,a.eventData),!0),zu(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:pn,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 jA(e,t){let i=ws(e);if(i.schema===Pi)return{status:"current",journal:vg(i,t)};if(i.schema===$r)return{status:"migration-required",journal:TA(i,t)};if(i.schema===pn)return{status:"migration-required",journal:_A(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function OA(e,t){let i=ta(e,t);await O(e.nativeRoot,i);try{let n=await ht({root:e.nativeRoot,file:i,maxBytes:CA,label:`Native transition journal ${t}`});return jA(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Cn(e,t){let i=await OA(e,t);if(!i)return null;if(i.status==="migration-required")throw new Bu(t);return i.journal}async function ys(e){if(await Ii(e.paths,e.nextState.name))throw new Error(`Native schema migration is incomplete for ${e.nextState.name}; run doctor --repair`);await Or(e.paths,e.nextState.name);let t={schema:Pi,minimum_runtime_version:3,revision:1,operation:e.operation??"advance",id:e.transitionId?.()??NA(),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=vg(t,t.change),n=ta(e.paths,i.change);if(await O(e.paths.nativeRoot,n),await Cn(e.paths,i.change))throw new Error(`Native transition recovery is already pending for ${i.change}`);return await Pe(n,i),i}function ug(e,t){if(vt(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(vt(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function dg(e,t){if(vt(e,t.nextState))return"next";if(vt(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function HA(e){let{journal:t}=e;return gg({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 gg(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function fg(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=HA({sequence:a.index+1,journal:t,type:a.event.type});if(!vt(gg(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 $i(e,t,i){if(await Ii(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Or(e,t);let n=await Cn(e,t);if(!n)return null;let r=T(e,t),a=fg(await Le(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([Be(r),le(e,t)]),c=ug(o,n),l=dg(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 ru(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!vt(await Be(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 Vr(e,n.nextState,n.previousState.revision);if(!vt(g,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!vt(await le(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await Cn(e,t);if(!u||!vt(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=fg(await Le(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await ms({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 ms({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Du({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[h,m]=await Promise.all([Be(r),le(e,t)]);ug(h,{...n,previousRun:n.nextRun}),dg(m,{...n,previousState:n.nextState});let p=await Cn(e,t);if(!p||!vt(p,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await bA.rm(ta(e,t),{force:!0}),n.nextState}var $A=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function FA(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 We(e){let i=(e.findings??[]).filter(u=>!hn(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||$A.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:FA(e.state)}}import ia from"path";var wg=8,DA={"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 MA(e){let t=DA[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"}:hn(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 BA(e,t,i){if(!i.path)return null;let n;if(ia.isAbsolute(i.path)?n=ia.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=ia.resolve(T(e,t.name),...i.path.split(/[\\/]/u)):n=ia.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!F(e.projectRoot,n))return null;let r=ia.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function LA(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 it(e){return e.findings.map(t=>{let i=MA(t.code);return{code:t.code,message:t.message,severity:i.severity,path:BA(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:LA(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 yg(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,wg),truncated:t.length>wg}}import Eg from"path";import Rn from"path";var ci={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Pn=/^[a-f0-9]{64}$/u;function Ns(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bs(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 si(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 Ng(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Gu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function qA(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Rn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Rn.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Uu(e,t){return Rn.join(T(e,t),"runtime","checkpoints","progress.json")}function An(e,t){return Rn.join(T(e,t),"runtime","checkpoint-journal.json")}function Ku(e,t,i){if(!Pn.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Rn.join(T(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function VA(e){if(!Pn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Yu(e,t,i){let n=await ht({root:e,file:t,maxBytes:ci.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function WA(e,t){let i=Ns(e,`checkpoint manifest artifact ${t}`);bs(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=qA(si(i.path,`checkpoint artifact ${t} path`,4096)),r=dt(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Pn.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:Gu(i.size,`checkpoint artifact ${t} size`)}}function ks(e,t){let i=Ns(e,"Native checkpoint manifest");if(bs(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>ci.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(WA),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=Gu(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>ci.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 Xu(e){return G(JSON.stringify(ks(e,e.change)))}function Qu(e,t){let i=Ns(e,"Native progress checkpoint");if(bs(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=Ng(i.previousRevision,"Native checkpoint previousRevision"),a=Ng(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=si(i.manifestHash,"Native checkpoint manifestHash",64);if(!Pn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=VA(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=si(i.inputHash,"Native checkpoint inputHash",64);if(!Pn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=si(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Gu(i.artifactCount,"Native checkpoint artifactCount");if(u>ci.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=si(i.summary,"Native checkpoint summary"),f=si(i.nextAction,"Native checkpoint nextAction");if(ue(d)!==d||ue(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:si(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 zA(e,t){let i=Ns(e,"Native checkpoint journal");if(bs(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=Et(i.previousState),r=Et(i.nextState),a=Qu(i.checkpoint,t),o=ks(i.manifest,t),s=si(i.inputHash,"Native checkpoint journal inputHash",64),c=G(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Pn.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!==Xu(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 JA(e,t,i){let n=Rn.resolve(e.projectRoot,...t.split("/"));if(!F(e.projectRoot,n)||F(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=dr(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await ht({root:e.projectRoot,file:n,maxBytes:ci.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 GA(e,t){let i=Uu(e,t);await O(e.nativeRoot,i);try{return Qu(await Yu(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Zu(e,t,i){let n=Ku(e,t,i);await O(e.nativeRoot,n);let r=await Yu(e.nativeRoot,n,"Native checkpoint manifest"),a=ks(r,t);if(ed(e,a),Xu(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Ss(e,t){let i=An(e,t);await O(e.nativeRoot,i);try{let n=zA(await Yu(e.nativeRoot,i,"Native checkpoint journal"),t);return ed(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function bg(e,t,i,n){let r=ks(i,t);ed(e,r);let a=Xu(r),o=Ku(e,t,a);await O(e.nativeRoot,o);try{let s=await Zu(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 Pe(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function ed(e,t){for(let i of t.artifacts){let n=dr(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function kg(e,t){let i=Qu(t,t.change),n=await Zu(e,i.change,i.manifestHash),r=G(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Uu(e,t.change);await O(e.nativeRoot,a),await Pe(a,i,{containedRoot:e.nativeRoot})}async function Sg(e){let t;try{t=await GA(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:Uu(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 Zu(e.paths,e.name,t.manifestHash);let a=G(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 JA(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:Ku(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}var Cg=240,Rg=8,Es=50;function Pg(e){let t=Array.from(e);return t.length<=Cg?e:`${t.slice(0,Cg-1).join("")}…`}function UA(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function KA(e){let t=[...new Set(e.map(UA))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Rg),reasonCount:e.length,codesTruncated:t.length>Rg};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Es),reasonsTruncated:e.length>Es}}}async function Ag(e){let t=null;try{let s=await Ss(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:An(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:An(e.paths,e.state.name)}}let i=await Sg({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=KA(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ci.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Pg(i.checkpoint.summary),nextAction:Pg(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:Eg.relative(e.paths.projectRoot,Eg.join(T(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:ci.maxArtifacts}}import{promises as xI}from"node:fs";import Cw from"node:path";import xg from"node:path";var YA="comet.native.archive-preflight.v1",XA="comet.native.archive-preflight.v1",QA="comet.native.archive-operation.v1",ZA=/^[a-f0-9]{64}$/u,Ig=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ex=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Cs(e,t){return e<t?-1:e>t?1:0}function tx(e,t){if(typeof e!="string"||!ZA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function xt(e,t){return e===null?null:tx(e,t)}function ix(e,t){let i=xg.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||xg.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 nx(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function rx(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 ax(e,t){if(!Ig.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=xt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=xt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=xt(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 ox(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:xt(e.contractHash,"Native archive contract hash"),acceptanceHash:xt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:xt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:xt(e.reportHash,"Native archive report hash"),envelopeHash:xt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:xt(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 sx(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!ex.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(Cs);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function cx(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(Cs)}function Tg(e){if(!Ig.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(ax).sort((l,u)=>Cs(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:_(QA,l)})),n=ox(e.evidence),r=rx(e.workspace),a=[...new Set([...sx(e.findingCodes??[]),...cx({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(Cs),o=nx(e.revision),s=ix(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:YA,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:_(XA,c)}}import{createHash as lx}from"node:crypto";import _g from"node:path";var ux="comet.native.conflict-radar.v1",Ee=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}),dx="comet.native.conflict-radar.v1",fx="comet.native.conflict-radar-signals.v1",hx=/^[a-f0-9]{64}$/u,Hg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,px=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),mx=new Set(["capability","operation","baseHash"]),vx=new Set(["path","kind"]);function xn(e,t){return e<t?-1:e>t?1:0}function td(e){return Buffer.byteLength(e,"utf8")}function id(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 nd(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(td(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function gx(e,t){let i=nd(e,t,Ee.maxArtifactPathBytes),n=_g.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)||_g.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 $g(e,t){if(typeof e!="string"||!hx.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function wx(e,t){let i=id(e,mx,t),n=nd(i.capability,`${t} capability`,Ee.maxCapabilityBytes);if(!Hg.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:$g(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 yx(e,t){let i=id(e,vx,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:gx(i.path,`${t} path`),kind:i.kind}}function Nx(e,t){let i=id(e,px,`Conflict radar change ${t}`),n=nd(i.name,`Conflict radar change ${t} name`,Ee.maxNameBytes);if(!Hg.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>Ee.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>Ee.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>wx(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>xn(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)=>yx(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>xn(c.path,l.path)||xn(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:$g(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function bx(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ee.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(Nx).sort((r,a)=>xn(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)>Ee.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>Ee.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function kx(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 Sx(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 Ex(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function Cx(e,t){let i=[],n=lx("sha256").update(`${fx}
|
|
174
|
-
[`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(Jr(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ee.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(kx(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=Sx(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:Ex(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function jg(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function Rx(e,t){return jg(e.classification)-jg(t.classification)||xn(e.left,t.left)||xn(e.right,t.right)}function Og(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:ux,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 Fg(e){let t=bx(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(Cx(t[s],t[c]));i.sort(Rx);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=_(dx,{changes:t,relationships:n}),a=i.slice(0,Ee.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Og(t,i,a,r);for(;a.length>0&&td(JSON.stringify(o))>Ee.maxSerializedBytes;)a=a.slice(0,-1),o=Og(t,i,a,r);if(td(JSON.stringify(o))>Ee.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as Zg}from"node:crypto";import{promises as ze}from"node:fs";import rt from"node:path";import Dg from"node:path";var Rs="comet.native.check-receipt.v1",Lg="comet.native.check-receipt.v1",li="scoped-text-safety",na=1,ae=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Px=/^[a-f0-9]{64}$/u,Ax=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xx="comet.native.checker-policy.v1",Ix="comet.native.check-input.v1",Tx=2048,Ps=_(xx,{policy:li,version:na,limits:ae,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),_x=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Mg=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],qg=["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"],jx=new Set(qg);function Di(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mi(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 It(e,t){if(typeof e!="string"||!Px.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Fi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Vg(e,t){let i=Fi(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Bg(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 Ox(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>Tx||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=Dg.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Dg.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Hx(e){let t=Di(e,"Native check receipt checker");Mi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Di(t.limits,"Native check receipt limits");if(Mi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==li||t.version!==na||t.hash!==Ps||i.maxFiles!==ae.maxFiles||i.maxFileBytes!==ae.maxFileBytes||i.maxTotalBytes!==ae.maxTotalBytes||i.maxIssues!==ae.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:li,version:na,hash:Ps,limits:{...ae}}}function $x(e){let t=Di(e,"Native check receipt contract");return Mi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:It(t.expectedHash,"Native check expected contract hash"),beforeHash:It(t.beforeHash,"Native check before contract hash"),afterHash:It(t.afterHash,"Native check after contract hash")}}function Fx(e){let t=Di(e,"Native check receipt implementation");return Mi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:It(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:It(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:It(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:It(t.afterSnapshotHash,"Native check after snapshot hash")}}function Dx(e){let t=Di(e,"Native check receipt counts");Mi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:Fi(t.filesSelected,"Native check filesSelected"),filesScanned:Fi(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Fi(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Fi(t.bytesScanned,"Native check bytesScanned"),issueCount:Fi(t.issueCount,"Native check issueCount"),recordedIssueCount:Fi(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>ae.maxFiles||i.bytesScanned>ae.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ae.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function Mx(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Mg.indexOf(e.kind)-Mg.indexOf(t.kind)}function Bx(e){if(!Array.isArray(e)||e.length>ae.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=Di(n,`Native check issue ${r}`);if(Mi(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!_x.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:Ox(a.path,`Native check issue ${r} path`),line:Vg(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(Mx);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function Lx(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!jx.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=qg.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 Wg(e){return _(Ix,e)}function Bi(e){let t=Di(e,"Native check receipt");if(Mi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Rs)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!Ax.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Vg(t.sourceRevision,"Native check source revision"),n=Hx(t.checker),r=$x(t.contract),a=Fx(t.implementation),o=Wg({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(It(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=Bg(t.startedAt,"Native check receipt startedAt"),c=Bg(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=Dx(t.counts),u=Bx(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=Lx(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>ae.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>ae.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Rs,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=It(t.receiptHash,"Native check receipt content hash");if(_(Lg,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}function zg(e){let t={policy:li,version:na,hash:Ps,limits:{...ae}},i={schema:Rs,...e,checker:t,inputHash:Wg({change:e.change,sourceRevision:e.sourceRevision,checkerHash:t.hash,contractHash:e.contract.expectedHash,scopeHash:e.implementation.scopeHash,snapshotHash:e.implementation.expectedSnapshotHash})};return Bi({...i,receiptHash:_(Lg,i)})}var As="comet.native.verification-receipt.v3",Jg=As,qx="comet.native.declared-artifacts.v1",Vx=/^[a-f0-9]{64}$/u,Wx=/^acceptance-[a-f0-9]{64}$/u,zx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Jx=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Gx=4096,Ux=256,Kx=1024;function In(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 ui(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 Tt(e,t){if(typeof e!="string"||!Vx.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function nt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=ue(e).trim();if(!i||i.length>Gx||i!==e.trim())throw new Error(`${t} is invalid`);return i}function rd(e,t){let i=nt(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 ra(e,t,i=nt,n=!1,r=Ux){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 Yx(e,t){if(typeof e!="string"||!Wx.test(e))throw new Error(`${t} is invalid`);return e}function Xx(e){let t=In(e,"Native verification receipt bindings");if(ui(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!zx.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:Tt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Tt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Tt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Tt(t.artifactHash,"Native verification receipt artifact hash")}}function Qx(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Jx.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function Zx(e,t,i,n){let r=In(t,`Native ${e} evidence`);if(e==="automated-check"){if(ui(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=rd(r.startedAt,"Native automated-check start time"),o=rd(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=In(r.worktree,"Native automated-check worktree");if(ui(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=In(r.afterFence,"Native automated-check after fence");if(ui(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:nt(r.executable,"Native automated-check executable"),args:ra(r.args,"Native automated-check arguments",nt,!0),cwd:nt(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:nt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Tt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Tt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Tt(r.outputHash,"Native automated-check output hash"),outputSummary:nt(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){ui(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=Qx(r.checkReceiptRef);if(Tt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:ra(r.subjects,"Native static inspection subjects",nt,n==="required-check"),rule:nt(r.rule,"Native static inspection rule"),resultSummary:nt(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ui(r,["steps","observations"],"Native manual-evidence evidence"),{steps:ra(r.steps,"Native manual evidence steps"),observations:ra(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function Gg(e){let t=In(e,"Native verification receipt");if(ui(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=nt(t.actor,"Native verification receipt actor"),o=ra(t.acceptanceIds,"Native receipt acceptance IDs",Yx,n==="required-check",Kx).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:As,kind:i,role:n,status:r,bindings:Xx(t.bindings),acceptanceIds:o,actor:a,issuedAt:rd(t.issuedAt,"Native verification receipt issue time"),evidence:Zx(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==li||s.actor!==`native-runtime:${li}`))throw new Error("Native required check policy identity is invalid");return s}function Ug(e){let t=Gg({schema:As,...e});return{...t,receiptHash:_(Jg,t)}}function ad(e){let t=In(e,"Native verification receipt");if(ui(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==As)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=Gg(n),a=Tt(t.receiptHash,"Native verification receipt hash");if(_(Jg,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function xs(e){return _(qx,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}function Kg(e){return e.kind==="static-inspection"?`static:${e.evidence.rule}`:e.kind==="automated-check"?`automated:${_("comet.native.failed-check.v1",{executable:e.evidence.executable,args:e.evidence.args,acceptanceIds:e.acceptanceIds})}`:`manual:${_("comet.native.failed-check.v1",{acceptanceIds:e.acceptanceIds})}`}var ew=/^[a-f0-9]{64}$/u,_t=ji,f1=3*_t;function od(e,t){let i=rt.relative(e,t);return i===""||!rt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${rt.sep}`)}function eI(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Is(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return fe(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Yg(e){let t=await ze.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ze.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function tI(e,t){let i=rt.resolve(e),n=rt.resolve(t);if(!od(i,n))throw new Error("Native evidence path is outside its change");let r=[await Yg(i)],a=i;for(let o of rt.relative(i,n).split(rt.sep).filter(Boolean)){a=rt.join(a,o);let s=await Yg(a);if(!od(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Xg(e){for(let t of e){let i=await ze.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!eI(t,i)||await ze.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function iI(e,t,i={}){let n=await tI(t,rt.dirname(e));await i.afterParentChainCaptured?.();let r=await ze.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ze.realpath(e);if(!od(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ze.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ze.lstat(e),ze.realpath(e)]);if(await Xg(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Is(s,r)||!Is(s,c))throw new Error("Native evidence document changed while opening");if(s.size>_t)throw new Error(`Native evidence document exceeds ${_t} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let g=_t+1-d,S=await o.read(f,0,Math.min(f.length,g),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>_t)throw new Error(`Native evidence document exceeds ${_t} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),ze.lstat(e),ze.realpath(e)]);if(await Xg(n),!m.isFile()||m.isSymbolicLink()||p!==a||!Is(s,h)||!Is(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 gt(e,t){if(!ew.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function tw(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>_t||Zg("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Li({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function nI(e,t,i,n,r){if(!ew.test(i))throw new Error("Native report evidence hash is invalid");let a=await jt({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"||Zg("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 Tn(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 iw(e,t,i,n,r){return rt.join(r??T(e,t),...gt(i,n).split("/"))}async function jt(e){let t=e.changeDir??T(e.paths,e.name),i=iw(e.paths,e.name,e.kind,e.hash,t);return await O(e.paths.nativeRoot,i),iI(i,t,e.hooks)}async function Li(e){Ts(e.value);let t=iw(e.paths,e.name,e.kind,e.hash);await O(e.paths.nativeRoot,t);try{let n=await jt(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return gt(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await Pe(t,e.value,{containedRoot:e.paths.nativeRoot});let i=await jt(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return gt(e.kind,e.hash)}function Ts(e){if(rI(e)>_t)throw new Error(`Native evidence document exceeds ${_t} bytes`)}function rI(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
175
|
-
|
|
176
|
-
`,"utf8")>Wi)throw new Error(`Native check receipt exceeds ${Wi} bytes`);await O(e.paths.nativeRoot,n);try{let o=await Hs(e.paths,e.name,i);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return i}catch(o){if(o.code!=="ENOENT")throw o}await Pe(n,t,{containedRoot:e.paths.nativeRoot});let a=await Hs(e.paths,e.name,i);if(JSON.stringify(a)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return i}var aa=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var nD=64*1024;var rD=3600*1e3;var aD=vI(mI);var oD=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");async function gw(e,t){if(t.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([wt(e,t.name,t.implementation_scope),Te({changeDir:T(e,t.name),briefRef:t.brief,specChanges:t.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=t.run_id?`run:${t.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:t.name,sourceRevision:t.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:xs(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var gI=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ld(e,t){let i=[];for(let n of gI){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}}function wI(e,t){return ld(e,t).ok}async function ww(e){let t=await gw(e.paths,e.state),i=e.checkReceipt.stale||e.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),n=e.checkReceipt.status==="passed"?"passed":i?"blocked":"failed",r=Ug({kind:"static-inspection",role:"required-check",status:n,bindings:t.bindings,acceptanceIds:[],actor:`native-runtime:${e.checkReceipt.checker.policy}`,issuedAt:e.checkReceipt.endedAt,evidence:{subjects:t.scope.scope.changes.map(o=>o.path).sort(),rule:e.checkReceipt.checker.policy,resultSummary:n==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${e.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:e.checkReceiptRef,checkReceiptHash:e.checkReceipt.receiptHash}}),a=await cw({paths:e.paths,name:e.state.name,receipt:r});return{receipt:r,ref:a}}function yI(e){let{receipt:t,checkReceipt:i,context:n}=e;if(t.kind!=="static-inspection"||t.role!=="required-check"||t.status!=="passed"||!wI(t,n.bindings)||i.status!=="passed"||i.stale)return!1;let r=n.scope.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return i.change===n.bindings.change&&i.sourceRevision===n.bindings.sourceRevision&&i.contract.expectedHash===n.bindings.contractHash&&i.contract.beforeHash===n.bindings.contractHash&&i.contract.afterHash===n.bindings.contractHash&&i.implementation.scopeHash===n.bindings.scopeHash&&i.implementation.expectedSnapshotHash===n.bindings.snapshotHash&&i.implementation.beforeSnapshotHash===n.bindings.snapshotHash&&i.implementation.afterSnapshotHash===n.bindings.snapshotHash&&i.counts.filesSelected===r.length&&i.counts.filesScanned+i.counts.binaryFilesSkipped===r.length&&i.counts.bytesScanned===a&&i.counts.issueCount===0&&i.counts.recordedIssueCount===0&&i.issues.length===0&&!i.issuesTruncated}async function yw(e){let t=await lw(e.paths,e.state.name);if(t.length===0)return null;let i=[];for(let a of t)try{let o=await _n(e.paths,e.state.name,a);o.kind==="static-inspection"&&o.role==="required-check"&&o.status==="passed"&&i.push({ref:a,receipt:o})}catch{}if(i.length===0)return null;let n;try{if(n=await gw(e.paths,e.state),!(await SI({paths:e.paths,context:n})).matched)return null}catch{return null}let r=null;for(let{ref:a,receipt:o}of i)try{let s=await ud({paths:e.paths,state:e.state,receipt:o});if(s===null||!yI({receipt:o,checkReceipt:s,context:n}))continue;let c={receipt:o,ref:a,checkReceipt:s,checkReceiptRef:o.evidence.checkReceiptRef};(r===null||c.receipt.issuedAt>r.receipt.issuedAt||c.receipt.issuedAt===r.receipt.issuedAt&&c.ref>r.ref)&&(r=c)}catch{}return r}function NI(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}:{}}}var bI=20;function kI(e,t){let i=[],n=0,r=0,a=0;for(;r<e.entries.length||a<t.entries.length;){let o=e.entries[r],s=t.entries[a],c=o===void 0?1:s===void 0||o.path<s.path?-1:o.path>s.path?1:0,l=c<=0?o:void 0,u=c>=0?s:void 0;if(c<=0&&(r+=1),c>=0&&(a+=1),l&&u&&l.hash===u.hash&&l.size===u.size)continue;let d=l?.path??u?.path;d&&(n+=1,i.length<bI&&i.push({path:d,kind:l?u?"modified":"removed":"added"}))}return{changedPaths:i,changedPathCount:n,changedPathsTruncated:i.length!==n}}async function SI(e){let t=NI(e.context.scope.baseline),i=await Xt(e.paths,t,{origin:"explicit",now:e.now}),n=ai({baseline:t,current:i,contractHash:e.context.bindings.contractHash,declaredArtifacts:e.context.scope.scope.declaredArtifacts,noCodeReason:e.context.scope.scope.noCodeReason,gitChangedPaths:e.context.scope.authority.gitChangedPaths}),r=kI(e.context.scope.current,n.current);return{expectedScopeHash:e.context.bindings.scopeHash,actualScopeHash:n.scope.scopeHash,expectedSnapshotHash:e.context.bindings.snapshotHash,actualSnapshotHash:n.scope.currentProjectionHash,matched:n.scope.currentProjectionHash===e.context.bindings.snapshotHash&&n.scope.scopeHash===e.context.bindings.scopeHash,...r}}async function ud(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Hs(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 Ot=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 EI(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}:{}}}function CI(e){let t=Nw.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/");if(!t||t===".."||t.startsWith("../")||Nw.posix.isAbsolute(t))throw new Error("Native root is outside the project root");return t}async function RI(e){let t=EI(e.bundle.baseline),i=await Xt(e.paths,t,{origin:"explicit",now:e.now});return ai({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function fd(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await wt(e.paths,e.state.name,e.state.implementation_scope),i=await Te({changeDir:T(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await RI({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 oa(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await fd(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 kw(e){let t=await he({root:T(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:sv(t.text)}}function PI(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 AI(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:xs(e.implementationScope.scope.declaredArtifacts)}}async function bw(e){let t=await _n(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=ld(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 Ot([{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 ud({paths:e.paths,state:e.state,receipt:t});if(r){let a=PI({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 Sw(e){let t=AI({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await bw({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Ot)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 bw({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Ot)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 Ot(i)}async function hd(e){if(e.state.phase!=="verify")throw new Error(`Native verification evidence requires Verify, got ${e.state.phase}`);let t=await fd(e);if(t.findingCodes.length>0)return{ready:!1,findingCodes:t.findingCodes,envelope:null,evidenceRef:null,reportSnapshot:null};let i=e.preflight?.report??await kw(e);if(e.result==="pass"&&!e.receiptRef&&e.requireReceipt!==!1)throw new Error("Native passing verification requires a typed required-check receipt");let n=e.receiptRef?[e.receiptRef]:[],r=e.preflight?.trace??zv(t.contract.acceptance,i.entries,{nativeRootRef:CI(e.paths),allowMissing:e.result==="fail"});if(e.result==="pass"&&r.entries.some(c=>c.status==="failed"||c.status==="missing"))throw new Error("Native passing verification cannot include failed or missing acceptance criteria");try{await Sw({paths:e.paths,state:e.state,result:e.result,trace:r,requiredReceiptRefs:n,contractHash:t.contractHash,implementationScope:t.bundle})}catch(c){if(c instanceof Ot)return{ready:!1,findingCodes:["verification-receipt-binding-mismatch"],envelope:null,evidenceRef:null,reportSnapshot:null,...c.details.length>0?{receiptBindingFailures:c.details}:{}};throw c}let a=e.state.partial_allowance?await sd(e.paths,e.state.name,e.state.partial_allowance):null;if(e.preflightOnly)return{ready:!0,findingCodes:[],envelope:null,evidenceRef:null,reportSnapshot:{hash:i.hash,text:i.text},preflight:{report:i,trace:r},preflightOnly:!0};let o=Gv({change:e.state.name,sourceRevision:e.state.revision,result:e.result,contractHash:t.contractHash,acceptanceHash:t.acceptanceHash,implementationScope:{ref:e.state.implementation_scope,bundle:t.bundle},reportRef:i.ref,reportHash:i.hash,requiredReceiptRefs:n,acceptanceTrace:r,partialAllowance:e.state.partial_allowance&&a?{ref:e.state.partial_allowance,allowance:a}:null,now:e.now}),s=gt("verifications",o.envelopeHash);return{ready:!0,findingCodes:[],envelope:o,evidenceRef:s,reportSnapshot:{hash:i.hash,text:i.text},preflight:{report:i,trace:r}}}async function Ew(e){if(!e.preparation.ready||e.preparation.preflightOnly||e.preparation.envelope===null||e.preparation.evidenceRef===null||e.preparation.reportSnapshot===null)throw new Error("Native verification evidence is not ready to persist");if(await tw({paths:e.paths,name:e.state.name,...e.preparation.reportSnapshot}),await uw({paths:e.paths,name:e.state.name,evidence:e.preparation.envelope})!==e.preparation.evidenceRef)throw new Error("Native verification evidence persistence ref changed")}function dd(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function On(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:dd(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([fd(e),jn(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:dd(e.state.verification_result,"stale"),envelope:null};let n=await kw({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 Sw({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:dd(e.state.verification_result,"invalid"),envelope:null}}}function II(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Rw(e){try{return await xI.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function TI(e,t){try{return(await he({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _I(e,t,i){let n=gn(e,i.capability);if(!F(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=Cw.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await TI(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await he({root:T(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 jI(e,t){return Rw(ta(e,t))}async function pd(e){let t=e.now??new Date,i=await le(e.paths,e.name),n=await ei(e.paths,e.name),r=await Gt(e.paths.projectRoot),a=II(i.name,t),o=Cw.resolve(e.paths.nativeRoot,...a.split("/"));if(!F(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(m=>_I(e.paths,i.name,m))),On({paths:e.paths,state:i,now:t}),js(e.paths,i.name),Ii(e.paths,i.name),vu(e.paths,i.name),jI(e.paths,i.name),Rw(o)]);return Tg({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:h,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]})}function OI(e){if(e.phase!=="build"||e.verification_result!=="fail"||!e.implementation_scope||!e.verification_evidence)throw new Error("Native repair guard requires a failed Verify-to-Build state")}async function Pw(e,t){let i=T(e,t.name),n=await Be(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 qo(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 Le(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function md(e,t){let i=await Pw(e,t);return{committed:i,latest:ig(i),history:tg(i)}}function HI(e,t){let i=e.latest;if(!i)return null;let n=e.history.filter(l=>l.kind==="failure"),r=n.length===0?0:Kr({signatureHash:i.signatureHash,...i.contractHash===null?{}:{failedAcceptanceIds:i.failedAcceptanceIds,failedCheckIds:i.failedCheckIds}},n.slice(0,-1)),a=i.overrideSummaryHash!==null,o=e.history.some(l=>l.kind==="override"&&l.signatureHash===i.signatureHash),s=n.length>=t,c=i.disposition==="hard-stop"&&!s?"continue":i.disposition;return{disposition:s?"hard-stop":c,reasonCode:a?"override-accepted":o&&i.disposition==="manual-stop"?"override-already-used":s?"repair-iteration-limit":i.disposition==="manual-stop"?"repeated-failure-stop":i.disposition==="warn"?"repeated-failure-warning":"new-failure-signature",signatureHash:i.signatureHash,consecutiveFailures:r,totalRepairFailures:n.length,remainingIterations:Math.max(0,t-n.length),overrideAccepted:a}}async function Aw(e,t,i){return HI(await md(e,t),i)}function xw(e){return{disposition:e.decision.disposition,reasonCode:e.decision.reasonCode,signatureHash:e.decision.signature.signatureHash,consecutiveFailures:e.decision.consecutiveFailures,totalRepairFailures:e.decision.totalRepairFailures,remainingIterations:e.decision.remainingIterations,overrideAccepted:e.decision.overrideAccepted}}function $I(e){return Nn(e.filter(t=>t.status!=="passed").map(t=>Kg(t)))}async function Iw(e){if(!e.state.implementation_scope)throw new Error("Native repair failure has no implementation scope");let t=[...new Set([...e.envelope.requiredReceiptRefs,...e.envelope.receiptRefs])],[i,n,r]=await Promise.all([Pw(e.paths,e.state),wt(e.paths,e.state.name,e.state.implementation_scope),Promise.all(t.map(o=>_n(e.paths,e.state.name,o)))]),a=$I(r);return rg({...i,envelope:e.envelope,implementationScope:n,maxVerifyFailures:e.maxVerifyFailures,...a.length>0?{failedCheckIds:a}:{}})}async function Tw(e){let t=await md(e.paths,e.state),i=t.latest,n=tt(e.currentImplementationScope).scope.contractHash;if(i?.contractHash!==null&&i?.contractHash!==n){if(e.override)throw new Error("Native repair override cannot cross a confirmed contract change");return{disposition:"proceed",eventProjection:null}}let r=t.history.filter(u=>u.kind==="failure").length;if(i&&r>=e.maxVerifyFailures){if(e.override)throw new Error("Native repair hard stop cannot be overridden");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:t.history.some(u=>u.kind==="override"&&u.signatureHash===i.signatureHash)}}let a=i?.disposition==="hard-stop"&&r<e.maxVerifyFailures?"continue":i?.disposition;if(!i||a!=="manual-stop"&&a!=="hard-stop"){if(e.override)throw new Error("Native repair override requires the latest manual stop");return{disposition:"proceed",eventProjection:null}}let o=t.history.some(u=>u.kind==="override"&&u.signatureHash===i.signatureHash);if(!(e.state.phase==="build"&&e.state.verification_result==="fail"&&e.state.implementation_scope!==null&&e.state.verification_evidence!==null)){if(e.override)throw new Error("Native repair override requires an active failed Verify-to-Build state");return{disposition:"proceed",eventProjection:null}}OI(e.state);let[c,l]=await Promise.all([jn(e.paths,e.state.name,e.state.verification_evidence),wt(e.paths,e.state.name,e.state.implementation_scope)]);if(l.scope.scopeHash!==c.implementationScopeHash)throw new Error("Native repair verification evidence does not match its implementation scope");if(i.contractHash===null&&En(e.currentImplementationScope)!==En(l)){if(e.override)throw new Error("Native repair override is not valid after implementation scope progress");return{disposition:"proceed",eventProjection:null}}if(i.disposition==="hard-stop"){if(e.override)throw new Error("Native repair hard stop cannot be overridden without implementation progress");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}}return o?{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}:e.override?{disposition:"proceed",eventProjection:ng({...t.committed,override:e.override}).eventProjection}:{disposition:"manual-stop",signatureHash:i.signatureHash,overrideRecorded:!1}}async function _w(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await md(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 oM=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function FI(e){return(await gv(e))?.change??null}function DI(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 MI(e,t){let i=T(e,t.name),n=[...(await vn(i,t.brief)).findings,...(await wn(e,t)).findings,...await Xo(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await Qt(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 dn(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 Te({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 Cn(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 zr(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 jw(e,t,i){let n=await FI(e)===t,r;try{let w=await gu(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 Ag({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await _w(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 Te({changeDir:T(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 jn(e,r.name,r.verification_evidence);for(let j of E.acceptanceTrace.entries)v.set(j.acceptanceId,j.status==="failed"?"failed":j.status==="missing"?"missing":"satisfied")}c=Yo({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 js(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 ei(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let v=await Go({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 Jo({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 oa({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 h=null,m=[];if(r.phase==="archive")try{h=await pd({paths:e,name:r.name}),m.push(...h.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 p=[...await MI(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,v,E)=>E.findIndex(j=>j.code===w.code&&j.path===w.path)===v),g=it({paths:e,state:r,findings:p}),S=g.filter(w=>!hn(w.code)),k=r.phase==="archive"&&h?.ready===!0&&S.length===0,N=f||r.phase==="archive"&&(h?.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:DI(r,k,N,i?.clarificationMode),archiveReady:k,inspection:a.inspection,findingSummary:yg(g),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:We({state:r,findings:g,archiveReady:k,evidenceRetreat:N,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:Es,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{randomUUID as dT}from"crypto";import{createHash as BI}from"crypto";function Ow(e,t,i,n){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Hw(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Hw(e[t]);return Object.freeze(e)}function di(e){return Hw(structuredClone(e))}function vd(e,t,i,n){return e.resolveStep({pkg:di(t),state:di(i),context:di(n)})}function $w(e,t,i,n,r,a){return e.resolveNext({pkg:di(t),state:di(i),step:di(n),outcome:di(r),context:di(a)})}function LI(e,t,i){return BI("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function gd(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function wd(e,t,i,n,r){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=vd(n,e,t,r);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=gd(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:LI(s.runId,s.iteration,o.id),stepId:o.id};return qI(e,s,c,i)}function qI(e,t,i,n){let r=Ow(i,t,e.guardrails,n);return r.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:r.reason}}function yd(e,t,i,n,r){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?vd(n,e,t,r):void 0,o=a?gd(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?$w(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!gd(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as VI}from"fs";import Fw from"path";function WI(e){return{valid:e.length===0,findings:e}}async function zI(e,t){let i=[];if((t.noCodeReason??"").trim().length>0)return i;if(!t.artifacts||t.artifacts.length===0)return[{code:"build-evidence-missing",message:"Build requires an artifact reference or an explicit no-code reason"}];for(let n of t.artifacts){if(Fw.isAbsolute(n)||n.split(/[\\/]/u).includes("..")||/^(?:[A-Za-z]:|~|[\\/])/u.test(n)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}let r=Fw.resolve(e.projectRoot,...n.split(/[\\/]/u));if(!F(e.projectRoot,r)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}try{await VI.access(r)}catch{i.push({code:"build-artifact-missing",message:`Build artifact does not exist: ${n}`,path:n})}}return i}async function Dw(e){let t=[],i=T(e.paths,e.state.name);if(e.evidence.summary.trim().length===0&&t.push({code:"transition-summary-missing",message:"Phase transition requires a summary"}),e.evidence.confirmed&&e.state.phase!=="shape"&&e.state.phase!=="build"&&t.push({code:"confirmation-not-shape",message:"Explicit confirmation is only valid while leaving Shape or Build"}),t.push(...await Xo(e.paths,e.state)),e.state.phase==="shape"||e.state.phase==="build"){let n=await Qt(e.paths,e.state.name);if(n===null)t.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let r=await dn(e.paths,n);r.complete||t.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${r.omittedCount} omitted entries); resolve the omissions before advancing`})}}if(e.state.phase==="shape"){let n=await vn(i,e.state.brief),r=await wn(e.paths,e.state);t.push(...n.findings,...r.findings),t.length===0&&!e.evidence.confirmed&&t.push({code:"shape-confirmation-required",message:"Native clarification requires explicit user confirmation of the shared understanding before Build"})}else if(e.state.phase==="build")t.push(...(await vn(i,e.state.brief)).findings,...(await wn(e.paths,e.state)).findings),t.push(...await zI(e.paths,e.evidence)),t.length===0&&e.state.approval!=="confirmed"&&!e.evidence.confirmed&&t.push({code:"approval-confirmation-required",message:"Native approval is implicit; confirm the current shared understanding before leaving Build"});else if(e.state.phase==="verify"){let n=e.evidence.verificationReport??e.state.verification_report;n?t.push(...(await zr(i,n)).findings):t.push({code:"verification-report-missing",message:"Verify requires a report path"}),e.evidence.verificationResult||t.push({code:"verification-result-missing",message:"Verify requires pass or fail"}),t.push(...(await wn(e.paths,e.state)).findings)}else t.push({code:"archive-command-required",message:"Use comet native archive for the Archive phase"});return WI(t)}import{createHash as JI}from"node:crypto";import{constants as Nd,promises as at}from"node:fs";import zi from"node:path";import{TextDecoder as GI}from"node:util";var Mw={"conflict-marker":0,"trailing-whitespace":1,"space-before-tab":2,"scope-mismatch":3,"unsafe-file":4,"binary-skipped":5,"scan-limit":6},te=class extends Error{constructor(i,n){super(n);this.kind=i}kind};function UI(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 Bw(e){let t=UI(e.scope.baseline),[i,n]=await Promise.all([Te({changeDir:T(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),Xt(e.paths,t,{origin:"explicit"})]),r=ai({baseline:t,current:n,contractHash:e.scope.authority.contractHash,declaredArtifacts:e.scope.authority.declaredArtifacts,noCodeReason:e.scope.authority.noCodeReason,...e.scope.authority.gitChangedPaths?{gitChangedPaths:e.scope.authority.gitChangedPaths}:{}});return{contractHash:i.contract.contractHash,snapshotHash:r.scope.currentProjectionHash}}function Lw(e,t){let i=(e??(()=>new Date))();if(!(i instanceof Date)||!Number.isFinite(i.getTime()))throw new Error(`Native check ${t} time is invalid`);return i.toISOString()}function KI(e,t,i){let n=[],r=i.scope.contractHash,a=i.scope.currentProjectionHash;return e.contractHash!==r&&n.push("contract-before-does-not-match-scope"),e.snapshotHash!==a&&n.push("implementation-before-does-not-match-scope"),t.contractHash!==e.contractHash&&n.push("contract-changed-during-check"),t.snapshotHash!==e.snapshotHash&&n.push("implementation-changed-during-check"),t.contractHash===e.contractHash&&t.contractHash!==r&&n.push("contract-after-does-not-match-scope"),t.snapshotHash===e.snapshotHash&&t.snapshotHash!==a&&n.push("implementation-after-does-not-match-scope"),n}function YI(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function $s(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size&&M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}async function XI(e,t){let i=zi.resolve(e),n=zi.resolve(t);if(!F(i,n))throw new te("unsafe-file","Scoped file parent escapes the project root");let r=[],a=i;for(let o of["",...zi.relative(i,n).split(zi.sep).filter(Boolean)]){o&&(a=zi.join(a,o));let s;try{s=await at.lstat(a)}catch(l){throw l.code==="ENOENT"?new te("scope-mismatch","Scoped file parent no longer exists"):l}if(!s.isDirectory()||s.isSymbolicLink())throw new te("unsafe-file","Scoped file parent is not a real directory");let c=await at.realpath(a);if(r.length>0&&!F(r[0].realPath,c))throw new te("unsafe-file","Scoped file parent resolves outside the project");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs,ctimeMs:s.ctimeMs})}return{physicalRoot:r[0].realPath,chain:r}}async function qw(e){for(let t of e){let i;try{i=await at.lstat(t.path)}catch(n){throw n.code==="ENOENT"?new te("unsafe-file","Scoped file parent changed while reading"):n}if(!i.isDirectory()||i.isSymbolicLink()||!YI(t,i)||await at.realpath(t.path)!==t.realPath)throw new te("unsafe-file","Scoped file parent changed while reading")}}async function QI(e){let t=zi.resolve(e.projectRoot,...e.file.path.split("/"));if(!F(e.projectRoot,t))throw new te("unsafe-file","Scoped file path escapes the project root");let{physicalRoot:i,chain:n}=await XI(e.projectRoot,zi.dirname(t)),r;try{r=await at.lstat(t)}catch(c){throw c.code==="ENOENT"?new te("scope-mismatch","Scoped file no longer exists"):c}if(!r.isFile()||r.isSymbolicLink())throw new te("unsafe-file","Scoped file is not a real regular file");if(r.size!==e.file.expected.size)throw new te("scope-mismatch","Scoped file size no longer matches its projection");let a=await at.realpath(t);if(!F(i,a))throw new te("unsafe-file","Scoped file resolves outside the project root");let o=process.platform==="win32"?"r":Nd.O_RDONLY|Nd.O_NOFOLLOW|Nd.O_NONBLOCK,s=await at.open(t,o).catch(c=>{throw c.code==="ENOENT"?new te("scope-mismatch","Scoped file no longer exists"):c.code==="ELOOP"||c.code==="ENXIO"?new te("unsafe-file","Scoped file became unsafe while opening"):c});try{let[c,l,u]=await Promise.all([s.stat(),at.lstat(t),at.realpath(t)]);if(await qw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!$s(r,c)||!$s(c,l))throw new te("unsafe-file","Scoped file changed while opening");let d=[],f=JI("sha256"),h=Buffer.allocUnsafe(64*1024),m=0;for(;;){let N=e.file.expected.size+1-m;if(N<1)throw new te("scope-mismatch","Scoped file exceeds its projected size");let b=await s.read(h,0,Math.min(h.length,N),null);if(b.bytesRead===0)break;if(m+=b.bytesRead,m>e.file.expected.size)throw new te("scope-mismatch","Scoped file exceeds its projected size");let C=Buffer.from(h.subarray(0,b.bytesRead));d.push(C),f.update(C)}let[p,g,S]=await Promise.all([s.stat(),at.lstat(t),at.realpath(t)]);if(await qw(n),m!==e.file.expected.size||f.digest("hex")!==e.file.expected.hash)throw new te("scope-mismatch","Scoped file content no longer matches its projection");if(!p.isFile()||!g.isFile()||g.isSymbolicLink()||S!==a||!F(i,S)||!$s(c,p)||!$s(c,g))throw new te("unsafe-file","Scoped file changed while reading");let k=Buffer.concat(d,m);if(k.includes(0))return{bytes:m,text:null};try{return{bytes:m,text:new GI("utf-8",{fatal:!0}).decode(k)}}catch{return{bytes:m,text:null}}}finally{await s.close()}}function ZI(e){let t=new Map(e.current.entries.map(r=>[r.path,r])),i=[],n=[];for(let r of e.scope.changes){if(!r.after)continue;let a=t.get(r.path);if(!a||a.hash!==r.after.hash||a.size!==r.after.size||a.type!=="file"){n.push(r.path);continue}i.push({path:r.path,expected:r.after})}return i.sort((r,a)=>r.path.localeCompare(a.path,"en")),n.sort((r,a)=>r.localeCompare(a,"en")),{files:i,mismatches:n}}function eT(e,t,i){let n=t.split(`
|
|
177
|
-
`);for(let r=0;r<n.length;r+=1){let a=n[r].endsWith("\r")?n[r].slice(0,-1):n[r],o=r+1;/^(?:<{7}|={7}|>{7})(?: |$)/u.test(a)&&i({path:e,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&i({path:e,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&i({path:e,line:o,kind:"space-before-tab"})}}async function Vw(e){if(!e.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let t=await wt(e.paths,e.state.name,e.state.implementation_scope),i=await Bw({paths:e.paths,state:e.state,scope:t}),n=Lw(e.clock,"start"),r=ZI(t),a=[],o=0,s=N=>{o+=1,a.length<ae.maxIssues&&a.push(N)},c=r.files,l=r.files.length+r.mismatches.length;if(t.scope.unresolvedScopes.some(N=>N.kind==="scope-detail-overflow")){let N=t.scope.changes.at(-1)?.path??t.current.entries.at(-1)?.path??t.baseline.entries.at(-1)?.path;if(!N)throw new Error("Native implementation scope overflow has no bounded diagnostic path");s({path:N,line:1,kind:"scan-limit"}),c=[]}else if(l>ae.maxFiles){let N=[...r.files.map(b=>b.path),...r.mismatches].sort((b,C)=>b.localeCompare(C,"en"));s({path:N[ae.maxFiles],line:1,kind:"scan-limit"}),c=[]}else{let N=0;for(let b of r.files){if(b.expected.size>ae.maxFileBytes){s({path:b.path,line:1,kind:"scan-limit"}),c=[];break}if(N+=b.expected.size,N>ae.maxTotalBytes){s({path:b.path,line:1,kind:"scan-limit"}),c=[];break}}}for(let N of r.mismatches)s({path:N,line:1,kind:"scope-mismatch"});let d=0,f=0,h=0;for(let N of c)try{let b=await QI({projectRoot:e.paths.projectRoot,file:N});h+=b.bytes,b.text===null?(f+=1,s({path:N.path,line:1,kind:"binary-skipped"})):(d+=1,eT(N.path,b.text,s))}catch(b){if(!(b instanceof te))throw b;s({path:N.path,line:1,kind:b.kind})}let m=await Bw({paths:e.paths,state:e.state,scope:t}),p=Lw(e.clock,"end"),g=KI(i,m,t);a.sort((N,b)=>N.path.localeCompare(b.path,"en")||N.line-b.line||Mw[N.kind]-Mw[b.kind]);let S=zg({change:e.state.name,sourceRevision:e.state.revision,status:o===0&&g.length===0?"passed":"failed",startedAt:n,endedAt:p,contract:{expectedHash:t.scope.contractHash,beforeHash:i.contractHash,afterHash:m.contractHash},implementation:{scopeHash:t.scope.scopeHash,expectedSnapshotHash:t.scope.currentProjectionHash,beforeSnapshotHash:i.snapshotHash,afterSnapshotHash:m.snapshotHash},counts:{filesSelected:l,filesScanned:d,binaryFilesSkipped:f,bytesScanned:h,issueCount:o,recordedIssueCount:a.length},issues:a,issuesTruncated:o>a.length,stale:g.length>0,staleReasons:g}),k=await vw({paths:e.paths,name:e.state.name,receipt:S});return{receipt:Bi(S),ref:k}}async function Ww(e){await qi(e.paths,e.name);let t=await le(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native check requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native check requires an implementation scope");let i=await yw({paths:e.paths,state:t});if(i)return{change:t,receipt:i.checkReceipt,checkRef:i.checkReceiptRef,ref:i.ref};let n=await Vw({paths:e.paths,state:t}),r=await ww({paths:e.paths,state:t,checkReceipt:n.receipt,checkReceiptRef:n.ref});return{change:t,receipt:n.receipt,checkRef:n.ref,ref:r.ref}}import{promises as bd}from"node:fs";import kd from"node:path";var Jw={maxDeclaredArtifacts:128,maxArtifactPathBytes:512};function zw(e,t){if(e.omitted.some(i=>i.reason==="git-selection-changed"))throw new Error(`Native Git selection changed while capturing the ${t}; stabilize the Git index and retry Build evidence`);if(e.omitted.some(i=>i.reason==="physical-enumeration-limit"||i.reason==="physical-selection-changed"))throw new Error(`Native physical selection was incomplete or changed while capturing the ${t}; retry Build evidence with a stable bounded project tree`)}function tT(e,t){let i=t.omitted.slice(0,20).map(a=>a.path),n=t.omitted.reduce((a,o)=>(a[o.reason]=(a[o.reason]??0)+1,a),{}),r=t.omissionOverflow?.count??0;return r>0&&(n.overflow=r),new xi(e,t.omittedCount,n,i,t.omitted.length>i.length||r>0)}function iT(e,t,i){let n=new Set(i.entries.map(a=>a.path)),r=t.entries.filter(a=>!n.has(a.path)).slice(0,20).map(a=>a.path);return new xi(e,i.omittedCount,{"manifest-size":i.omittedCount},r,i.omittedCount>r.length)}function nT(e,t){let i=e.replaceAll("\\","/").trim();if(i.length===0||i!==e.replaceAll("\\","/")||kd.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(i)||i.split("/").includes("..")||kd.posix.normalize(i)!==i||i==="."||i.endsWith("/")||Buffer.byteLength(i,"utf8")>Jw.maxArtifactPathBytes||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127}))throw new Error(`${t} must be a normalized project-relative path`);return i}function rT(e,t){return e.entries.some(i=>i.path===t)?"file":e.entries.some(i=>i.path.startsWith(`${t}/`))?"directory":null}async function aT(e,t,i){let n=nT(i,"Native build artifact"),r=dr(e,n);if(r)throw new Error(`Native build artifact is excluded as ${r}: ${n}`);let a=kd.resolve(e.projectRoot,...n.split("/"));if(!F(e.projectRoot,a))throw new Error(`Native build artifact escapes the project: ${n}`);await O(e.projectRoot,a);try{let o=await bd.lstat(a);if(o.isSymbolicLink())throw new Error(`Native build artifact must not be a symlink or junction: ${n}`);let s=await bd.realpath(a),c=await bd.realpath(e.projectRoot);if(!F(c,s))throw new Error(`Native build artifact resolves outside the project: ${n}`);if(o.isFile())return{path:n,kind:"file"};if(o.isDirectory())return{path:n,kind:"directory"};throw new Error(`Native build artifact is not a file or directory: ${n}`)}catch(o){if(o.code!=="ENOENT")throw o;let s=rT(t,n);if(s===null)throw new Error(`Native build artifact does not exist: ${n}`,{cause:o});return{path:n,kind:s}}}async function oT(e){if(e.refs.length>Jw.maxDeclaredArtifacts)throw new Error("Native build evidence exceeds its declared-artifact budget");let t=await Promise.all(e.refs.map(i=>aT(e.paths,e.baseline,i)));if(t.sort((i,n)=>i.path.localeCompare(n.path)||i.kind.localeCompare(n.kind)),new Set(t.map(i=>i.path)).size!==t.length)throw new Error("Native build evidence contains duplicate or conflicting artifacts");return t}function sT(e){return e.map(t=>({code:"verification-scope-partial",message:`${t.id}: ${t.reason}`,...t.path===null?{}:{path:t.path}}))}function cT(e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error("Native partial allowance requires a scope hash");return e}async function Gw(e){if(e.state.phase!=="build")throw new Error(`Native build evidence requires Build, got ${e.state.phase}`);if((e.noCodeReason??"").trim().length>0&&e.artifactRefs.length>0)throw new Error("Native build evidence cannot combine artifacts with a no-code reason");let t=await Qt(e.paths,e.state.name);if(t===null)throw new Error("Native change has no baseline content snapshot");let i=await dn(e.paths,t);if(zw(i,"baseline projection"),!i.complete)throw tT(e.state.name,i);let n=await Te({changeDir:T(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await oT({paths:e.paths,baseline:i,refs:e.artifactRefs}),a=await Xt(e.paths,i,{origin:"explicit",now:e.now});zw(a,"current snapshot");let o=ai({baseline:i,current:a,contractHash:n.contract.contractHash,declaredArtifacts:r,noCodeReason:e.noCodeReason??null});if(!o.baseline.complete)throw iT(e.state.name,i,o.baseline);let s=gt("scopes",o.scope.scopeHash);if(o.scope.complete){if(e.allowPartialScopeHash!==void 0&&e.allowPartialScopeHash!==null||e.partialReason!==void 0&&e.partialReason!==null)throw new Error("Complete Native build evidence must not include a partial allowance");return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:[],unresolvedScopes:[]}}if(e.allowPartialScopeHash===void 0||e.allowPartialScopeHash===null)return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:sT(o.scope.unresolvedScopes),unresolvedScopes:o.scope.unresolvedScopes};if(!e.confirmed)throw new Error("Native partial verification requires explicit confirmation");if(cT(e.allowPartialScopeHash)!==o.scope.scopeHash)throw new Error("Native partial allowance does not match the current implementation scope");let l=Jv({change:e.state.name,scopeBundle:o,allowedScopeIds:o.scope.unresolvedScopes.map(d=>d.id),reason:e.partialReason??"",confirmedSummary:e.confirmedSummary??"",sourceRevision:e.state.revision,now:e.now}),u=gt("allowances",l.allowanceHash);return{contract:n,bundle:o,scopeRef:s,allowance:l,allowanceRef:u,findings:[],unresolvedScopes:o.scope.unresolvedScopes}}async function Fs(e){if(await ow({paths:e.paths,name:e.state.name,bundle:e.preparation.bundle})!==e.preparation.scopeRef)throw new Error("Native implementation scope persistence ref changed");if(e.includeAllowance===!1||e.preparation.allowance===null)return;if(await sw({paths:e.paths,name:e.state.name,allowance:e.preparation.allowance})!==e.preparation.allowanceRef)throw new Error("Native partial allowance persistence ref changed")}import{promises as Uw}from"fs";import Kw from"path";var Yw=Ti.maxSpecs*4;async function lT(e){try{return await Rr(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function uT(e,t){let i=Kw.join(T(e,t),"specs"),n;try{n=await xo({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 Uw.opendir(i);try{for await(let s of o){if(a+=1,a>Yw)throw new Error(`Native proposed specs directory exceeds ${Yw} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;mn(s.name);let c=Kw.join(i,s.name,"spec.md");await O(e.nativeRoot,c);let l;try{l=await Uw.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>Ti.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 Xw(e,t){let i=new Map(t.spec_changes.map(a=>[a.capability,a])),n=await uT(e,t.name),r=[];for(let a of n){let o=i.get(a);if(o?.operation==="remove")throw new Error(`Capability ${a} has both a proposed spec and a remove intent`);if(o){r.push({...o,source:`specs/${a}/spec.md`});continue}let s=gn(e,a);await O(e.nativeRoot,s);let c=await lT(s);r.push({capability:a,operation:c===null?"create":"replace",source:`specs/${a}/spec.md`,base_hash:c})}for(let a of t.spec_changes)a.operation==="remove"&&!n.includes(a.capability)&&r.push(a);return r.sort((a,o)=>a.capability.localeCompare(o.capability))}function fT(e){return`Native verification receipt binding is invalid: ${e.detail}. Re-issue the affected receipts with \`comet native receipt refresh ${e.change} --apply\`.`}function ey(e){return e.confirmed!==void 0||e.artifacts!==void 0||e.noCodeReason!==void 0||e.allowPartialScopeHash!==void 0||e.partialReason!==void 0||e.verificationResult!==void 0||e.verificationReport!==void 0||e.repairOverrideSignature!==void 0||e.repairOverrideSummary!==void 0}function Sd(e){return e.reasonCode==="override-already-used"?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${e.signatureHash}`}:e.disposition==="warn"?{code:"repair-stagnation-warning",message:`Native repair repeated the same failure signature: ${e.signatureHash}`}:e.disposition==="manual-stop"?{code:"repair-stagnation-stop",message:`Native repair stopped after repeated failure signature: ${e.signatureHash}`}:{code:"repair-iteration-limit",message:`Native repair reached its total iteration limit at signature: ${e.signatureHash}`}}function Qw(e){let t=it({paths:e.paths,state:e.state,findings:e.preparation.findingCodes.map(i=>{if(i==="verification-receipt-binding-mismatch"&&e.preparation.receiptBindingFailures&&e.preparation.receiptBindingFailures.length>0){let n=e.preparation.receiptBindingFailures.map(r=>`${r.acceptanceId?`${r.ref}[${r.acceptanceId}]`:r.ref} -> ${r.mismatches.join("; ")}`).join(" | ");return{code:i,message:fT({change:e.state.name,detail:n})}}return{code:i,message:`Native verification evidence is not current: ${i}`}})});return{change:e.state,previousPhase:e.previousPhase,next:"manual",nextCommand:null,findings:t,continuation:We({state:e.state,findings:t,clarificationMode:e.clarificationMode})}}function hT(e){if(Oi(e.summary,"Native transition summary"),e.noCodeReason!==void 0&&Oi(e.noCodeReason,"Native transition no-code reason"),e.repairOverrideSignature!==void 0&&!/^[a-f0-9]{64}$/u.test(e.repairOverrideSignature))throw new Error("Native repair override signature must be a SHA-256 hash");e.repairOverrideSummary!==void 0&&es(e.repairOverrideSummary)}function pT(e){return{...e,summary:ue(e.summary),...e.noCodeReason===void 0?{}:{noCodeReason:ue(e.noCodeReason)},...e.partialReason===void 0?{}:{partialReason:ue(e.partialReason)},...e.repairOverrideSummary===void 0?{}:{repairOverrideSummary:ue(e.repairOverrideSummary)}}}function mT(e,t){let i=t.repairOverrideSignature!==void 0,n=t.repairOverrideSummary!==void 0;if(i!==n)throw new Error("Native repair override signature and summary must be provided together");if((i||n)&&e.phase!=="build")throw new Error("Native repair override is only valid while leaving Build")}async function Zw(e){if(ey(e.transition.evidence))throw new Error("Native evidence retreat only accepts a transition summary");let t=e.state.phase;if(t!=="verify"&&t!=="archive"||e.run.currentStep!==t||e.run.pending!==null)throw new Error("Native Verify/Archive Run cannot retreat evidence safely");if(t==="archive"?["complete","partial"].includes((await On({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness):(await oa({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness==="fresh"){let c=it({paths:e.transition.paths,state:e.state,findings:[t==="archive"?{code:"archive-command-required",message:"Current verification evidence is fresh; use Native Archive preview"}:{code:"verification-result-missing",message:"Current implementation scope is fresh; complete Verify with a result and report"}]});return{change:e.state,previousPhase:t,next:"manual",nextCommand:t==="archive"?`comet native archive ${e.state.name} --dry-run`:null,findings:c,continuation:We({state:e.state,archiveReady:t==="archive",clarificationMode:e.transition.clarificationMode})}}let n={...e.state,revision:e.state.revision+1,phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},r={...e.run,currentStep:"build",iteration:e.run.iteration+1,pending:null,status:"running"},a={previousPhase:t,nextPhase:"build",evidenceHash:e.evidenceHash,summary:e.transition.evidence.summary,artifacts:[],noCodeReason:null,verificationResult:null},o=await ys({paths:e.transition.paths,previousState:e.state,nextState:n,previousRun:e.run,nextRun:r,evidenceHash:e.evidenceHash,eventData:a,operation:"evidence-retreat",now:e.transition.now,transitionId:e.transition.transitionId});await e.transition.hooks?.afterPrepared?.(o);let s=await $i(e.transition.paths,e.state.name,e.transition.hooks);if(!s)throw new Error("Native evidence retreat journal disappeared before completion");return{change:s,previousPhase:t,next:"auto",nextCommand:null,findings:[],continuation:We({state:s,clarificationMode:e.transition.clarificationMode})}}async function ty(e){let t={...e,maxVerifyFailures:e.maxVerifyFailures??Pp,evidence:pT(e.evidence)};return hT(t.evidence),Fe(e.paths,`advance ${e.name}`,()=>Hi(e.paths,e.name,`advance ${e.name}`,()=>vT(t)))}async function vT(e){await qi(e.paths,e.name);let t=await le(e.paths,e.name),i=t.phase,n=T(e.paths,e.name),r=vs(e.evidence),a=await Be(n);if(a){let E=(await Le(n,a.trajectoryRef)).at(-1);if(E?.type==="state_transitioned"&&E.data.evidenceHash===r&&E.data.nextPhase===t.phase&&(E.data.previousPhase==="verify"?["complete","partial"].includes((await On({paths:e.paths,state:t,now:e.now})).freshness):!0)){let V=Object.hasOwn(E.data,"repairStagnation")?await Aw(e.paths,t,e.maxVerifyFailures):null,L=V&&V.disposition!=="continue"?it({paths:e.paths,state:t,findings:[Sd(V)]}):[],J=V?.disposition==="manual-stop"||V?.disposition==="hard-stop";return{change:t,previousPhase:E.data.previousPhase??t.phase,next:J?"manual":"auto",nextCommand:J?null:t.phase==="archive"?`comet native archive ${t.name} --dry-run`:null,findings:L,continuation:We({state:t,findings:L,archiveReady:t.phase==="archive"&&t.verification_result==="pass",clarificationMode:e.clarificationMode}),...V?{repair:V}:{}}}}if(t.phase==="archive"){if(!a)throw new Error("Native Archive Run state is missing");return Zw({transition:e,state:t,run:a,evidenceHash:r})}if(t.phase==="verify"&&!ey(e.evidence)){if(!a)throw new Error("Native Verify Run state is missing");if((await oa({paths:e.paths,state:t,now:e.now})).freshness!=="fresh")return Zw({transition:e,state:t,run:a,evidenceHash:r})}let o={...t,spec_changes:await Xw(e.paths,t)};mT(t,e.evidence);let s=await Dw({paths:e.paths,state:o,evidence:e.evidence,clarificationMode:e.clarificationMode});if(!s.valid){let v=it({paths:e.paths,state:t,findings:s.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:v,continuation:We({state:t,findings:v,clarificationMode:e.clarificationMode})}}let c=t.phase==="shape"?await Te({changeDir:n,briefRef:o.brief,specChanges:o.spec_changes}):null;if(t.phase!=="build"&&(e.evidence.allowPartialScopeHash!==void 0||e.evidence.partialReason!==void 0))throw new Error("Native partial scope allowance is only valid while leaving Build");let l=t.phase==="build"?await Gw({paths:e.paths,state:o,artifactRefs:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,allowPartialScopeHash:e.evidence.allowPartialScopeHash??null,partialReason:e.evidence.partialReason??null,confirmedSummary:e.evidence.summary,confirmed:e.evidence.confirmed??!1,now:e.now}):null;if(l&&(t.approved_contract_hash??null)!==l.contract.contract.contractHash&&!e.evidence.confirmed){let v=it({paths:e.paths,state:t,findings:[{code:"contract-changed-after-approval",message:"Native contract changed after approval; re-confirm the current contract before leaving Build"}]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:v,continuation:We({state:t,findings:v,clarificationMode:e.clarificationMode})}}let u=l?{scopeHash:l.bundle.scope.scopeHash,scopeRef:l.scopeRef,complete:l.bundle.scope.complete,unresolvedScopeCount:l.unresolvedScopes.length,partialAllowanceRef:l.allowanceRef,acceptancePage:Yo({criteria:l.contract.contract.acceptance,acceptanceHash:l.contract.contract.acceptanceHash})}:void 0;if(l&&l.findings.length>0){await Fs({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let v=it({paths:e.paths,state:t,findings:l.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:v,continuation:We({state:t,findings:v,clarificationMode:e.clarificationMode}),preparedScope:u}}let d=null,f=l?En(l.bundle):null;if(t.phase==="build"&&l){let v=await Tw({paths:e.paths,state:t,currentImplementationScope:l.bundle,maxVerifyFailures:e.maxVerifyFailures,...e.evidence.repairOverrideSignature&&e.evidence.repairOverrideSummary?{override:{expectedSignatureHash:e.evidence.repairOverrideSignature,summary:e.evidence.repairOverrideSummary}}:{}});if(v.disposition!=="proceed"){await Fs({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let E=it({paths:e.paths,state:t,findings:[v.disposition==="hard-stop"&&v.overrideRecorded?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${v.signatureHash}`}:Sd({disposition:v.disposition,reasonCode:v.disposition==="hard-stop"?"repair-iteration-limit":"repeated-failure-stop",signatureHash:v.signatureHash})]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:E,continuation:We({state:t,findings:E,clarificationMode:e.clarificationMode}),preparedScope:u&&{...u,partialAllowanceRef:null}}}d=v.eventProjection}let h=t.phase==="verify"?await hd({paths:e.paths,state:o,result:e.evidence.verificationResult,reportRef:e.evidence.verificationReport,receiptRef:null,requireReceipt:!1,preflightOnly:e.evidence.verificationResult==="pass",now:e.now}):null;if(h&&!h.ready)return Qw({paths:e.paths,state:t,previousPhase:i,clarificationMode:e.clarificationMode,preparation:h});if(t.phase==="verify"&&e.evidence.verificationResult==="pass"){let v=(await Ww({paths:e.paths,name:t.name})).ref;h=await hd({paths:e.paths,state:o,result:e.evidence.verificationResult,reportRef:e.evidence.verificationReport,receiptRef:v,preflight:h?.preflight,now:e.now})}if(h&&!h.ready)return Qw({paths:e.paths,state:t,previousPhase:i,clarificationMode:e.clarificationMode,preparation:h});let m=null;if(t.phase==="verify"&&e.evidence.verificationResult==="fail"&&h?.ready&&h.envelope){let v=await Iw({paths:e.paths,state:t,envelope:h.envelope,maxVerifyFailures:e.maxVerifyFailures});d=v.eventProjection,f=v.facts.implementationScopeHash,m=xw(v)}let p=a;if(!p){if(t.run_id!==null||t.phase!=="shape")throw new Error("Native Run state is missing or inconsistent");p=Pm(mt,e.runId?.()??dT(),ea)}if(p.currentStep!==t.phase)throw new Error(`Native Run step ${p.currentStep??"(none)"} does not match ${t.phase}`);let g=wd(mt,p,new Set,ps,void 0);if(!g.action)throw new Error(g.reason??"Native runtime produced no action");let S=yd(mt,g.state,{actionId:g.action.id,status:"succeeded",summary:e.evidence.summary,state:e.evidence.verificationResult?{verification_result:e.evidence.verificationResult}:void 0},ps,void 0);if(!S.currentStep)throw new Error("Archive completion must use the archive command");let k={...o,revision:t.revision+1,phase:S.currentStep,approval:e.evidence.confirmed?"confirmed":t.approval,approved_contract_hash:t.phase==="shape"?c.contract.contractHash:t.phase==="build"&&e.evidence.confirmed?l.contract.contract.contractHash:t.approved_contract_hash??null,run_id:p.runId,...t.phase==="build"?{verification_result:"pending",verification_report:null,implementation_scope:l.scopeRef,partial_allowance:l.allowanceRef,verification_evidence:null}:{},...t.phase==="verify"?{verification_result:e.evidence.verificationResult,verification_report:h.envelope.reportRef,verification_evidence:h.evidenceRef}:{}},N={previousPhase:i,nextPhase:k.phase,evidenceHash:r,summary:e.evidence.summary,artifacts:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,verificationResult:e.evidence.verificationResult??null,...(t.phase==="build"||t.phase==="verify")&&(t.phase==="build"?l.bundle.scope.scopeHash:h.envelope.implementationScopeHash)?{implementationScopeHash:t.phase==="build"?l.bundle.scope.scopeHash:h.envelope.implementationScopeHash}:{},...f?{repairScopeHash:f}:{},...d?{repairStagnation:d}:{}};t.phase==="build"&&l&&await Fs({paths:e.paths,state:t,preparation:l}),t.phase==="verify"&&h&&await Ew({paths:e.paths,state:t,preparation:h});let b=await ys({paths:e.paths,previousState:t,nextState:k,previousRun:a,nextRun:S,evidenceHash:r,eventData:N,now:e.now,transitionId:e.transitionId});await e.hooks?.afterPrepared?.(b);let C=await $i(e.paths,e.name,e.hooks);if(!C)throw new Error("Native transition journal disappeared before completion");let y=m&&m.disposition!=="continue"?it({paths:e.paths,state:C,findings:[Sd(m)]}):[],w=m?.disposition==="manual-stop"||m?.disposition==="hard-stop";return{change:C,previousPhase:i,next:w?"manual":"auto",nextCommand:w?null:C.phase==="archive"?`comet native archive ${C.name} --dry-run`:null,findings:y,continuation:We({state:C,findings:y,archiveReady:C.phase==="archive"&&C.verification_result==="pass",clarificationMode:e.clarificationMode}),...u?{preparedScope:u}:{},...m?{repair:m}:{}}}import yT from"path";var zB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var eL=16*1024*1024,tL=256*1024,iL=16*1024;var FL=16*1024*1024,Ds=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"},Ms=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 GL=10*1024*1024,se=class extends Error{};function Bs(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new se(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function ot(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new se(`${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 se(`${t} requires a value`);return e.splice(n,2),r}function iy(e,t){let i=[];for(let n=0;n<e.length;){if(e[n]!==t){n+=1;continue}let r=e[n+1];if(r===void 0||r.startsWith("--"))throw new se(`${t} requires a value`);i.push(r),e.splice(n,2)}return i}function ny(e){if(e.length>0)throw new se(`Unexpected argument: ${e[0]}`)}function ry(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new se(`${t} is required`);return i}async function ay(e){return e?yT.resolve(e):ko(process.cwd())}async function oy(e){let t=await Ap({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function sy(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
147
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Ls(l,t);else if(i)ef(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Ls(l,null);if(d!==null)t=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!ef(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 tr(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Fs(e,t,i,r=[],n="content-hash"){let a=tr(i),o=t.replaceAll("\\","/").trim(),s=r.map(tr);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${te(gN,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Vs(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function wN(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of er(e)){n=s+1;let c=o?Ms(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function qs(e,t="brief.md",i=ir.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=wN(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:d}of er(e)){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 er(e)){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(),Vs(o.map(l=>Fs("brief-example",t,l.join(`
|
|
148
|
+
`),[],r)),"Brief",r)}function Ws(e,t="spec.md",i=ir.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(Fs("spec-scenario",t,[o.title,...o.body].join(`
|
|
149
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of er(e)){let f=l?Ms(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=tr(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(),Vs(n,"Specification",r)}function zs(e,t="spec.md",i=ir.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(Fs("spec-must",t,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 er(e)){let u=d?Ms(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||Ls(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 m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(f);if(m){c(),s={parts:[m[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(),Vs(n,"Specification mandatory requirements",r)}var yN=/^A[1-9]\d*$/u;function rf(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||tf.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||tf.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function NN(e,t){return e.localeCompare(t,"en")}function Xn(e){let t=rf(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>NN(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=qs(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=rf(a.source,`Native spec source for ${a.capability}`);r.push(...Ws(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...zs(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=tr(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 nf(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!yN.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function af(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}function bN(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function I(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(bN(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Ye="comet.native.v3",Le="comet.native.v2",Me="comet.native.v1";var Qn="comet.native.portable-migration.v1",SN=new Set(["schema","id","change","fromSchema","status","createdAt"]),EN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PN=/^[a-z0-9][a-z0-9-]{7,127}$/u,xN=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),RN=new Set([Me,Le,Ye]);function CN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function AN(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function _N(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function TN(e){return e.schema===Me?rr(e):e.schema===Le?nr(e):ar(e)}function IN(e){return kN.posix.normalize(e.replaceAll("\\","/"))}function jN(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:IN(t.source)})}function $N(e){return e==="shape"?"shape":"build"}function ON(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function HN(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function of(e){let t=TN(e.state);nf(e.acceptance);let i=$N(t.phase),r=i==="shape"?0:1,n=AN(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return P({schema:Zt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:jN(t),workspace:e.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:ON(t.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:I(HN(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:As(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Js(e){let t=CN(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!SN.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Qn)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!PN.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!EN.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!RN.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!xN.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Qn,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:_N(t.createdAt,"Native portable migration transaction createdAt")}}function sf(e){switch(Js(e).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 cf="comet.native.archive-transaction.v4",lf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",DN=new RegExp(`^portable-archive-(${lf})\\.json$`,"u"),BN=new RegExp(`^portable-migration-(${lf})\\.json$`,"u"),LN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,MN=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FN=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),VN=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),qN=new Set(["capability","operation","source","content"]),uf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function df(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ff(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function WN(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=df(e,i);if(ff(r,qN,i),typeof r.capability!="string"||!uf.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 zN(e){let t=df(e,"Native portable Archive transaction");if(ff(t,VN,"Native portable Archive transaction"),t.schema!==cf)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!LN.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!uf.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!MN.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!FN.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(WN);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(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:cf,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Zn(e){let t=DN.exec(e);if(t)return{kind:"archive",change:t[1]};let i=BN.exec(e);return i?{kind:"migration",change:i[1]}:null}function ea(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Zn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Gs.join(e.transactionsDir,i)}async function Us(e,t){let i=Zn(t);if(!i)return null;let r=await V({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Gs.join(e.transactionsDir,t);if(i.kind==="archive"){let s=zN(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=Js(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 hf(e,t){let i=ea(e,t);try{return await Us(e,Gs.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function pf(e){return e.kind==="archive"||e.journal.status!=="committed"}import Xe from"path";import{TextDecoder as ZN}from"util";import{createHash as JN}from"node:crypto";import{constants as ta,promises as Ae}from"node:fs";import _e from"node:path";function ra(e,t){let i=_e.relative(e,t);return i===""||!_e.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_e.sep}`)}function GN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function UN(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function KN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ia(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ks(e,t){let i=await Ae.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ae.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function YN(e,t,i){let r=_e.resolve(e),n=_e.resolve(t);if(!ra(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Ks(r,i)],o=r;for(let s of _e.relative(r,n).split(_e.sep).filter(Boolean)){await At(a,i),o=_e.join(o,s);let c=await Ks(o,i);if(!ra(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await At(a,i),a}async function At(e,t){for(let i of e){let r=await Ae.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!UN(i,r)||await Ae.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function XN(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ii(e){let t=GN(e.maxBytes),i=_e.resolve(e.file),r=await YN(e.root,_e.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Ks(_e.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await At(r,e.label);let a=await Ae.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=KN(a),s=await Ae.realpath(i);if(!ra(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>ra(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ta.O_RDONLY:ta.O_RDONLY|ta.O_NOFOLLOW|ta.O_NONBLOCK,l=await Ae.open(i,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Ae.lstat(i),Ae.realpath(i)]);if(await At(r,e.label),await At(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!ia(o,f)||!ia(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await XN(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await At(r,e.label),await At(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ia(o,m)||!ia(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:JN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var eb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),tb=new Set(["id","type","source","target","staged","backup"]),ib=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),rb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var gf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var nb=256*1024,ER=1024*1024,PR=16*1024;var xR=64*1024*1024;var ab=new ZN("utf-8",{fatal:!0});function aa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function oa(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function wf(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ys(e,t){if(typeof e!="string"||e.length===0||Xe.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function na(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function mf(e,t){if(Ys(e,t),e.includes("\\")||e!==Xe.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 ob(e,t){let i=aa(e,`transaction operations[${t}]`);if(oa(i,tb,`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`);Ys(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ys(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 yf(e){let t=aa(e,"Native Archive transaction journal");if(oa(t,ib,"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"||!gf.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(!wf(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(na(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=aa(s,`Archive transaction operations[${c}]`);if(oa(l,rb,`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`);mf(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&mf(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&na(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(na(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`);na(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/${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(`${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:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function sb(e){let t=aa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return yf(t);if(oa(t,eb,"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"||!gf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Xe.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Xe.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(!wf(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(ob),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: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 cb(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Xe.join(e.transactionsDir,t)}function Nf(e,t){let i=cb(e,t);return{directory:i,journal:Xe.join(i,"transaction.json"),events:Xe.join(i,"events.jsonl"),staged:Xe.join(i,"staged"),backups:Xe.join(i,"backups")}}async function Qs(e,t){let i=Nf(e,t);return await Promise.all(Object.values(i).map(r=>B(e.runtimeDir,r))),i}async function Zs(e,t,i={}){let r=await Qs(e,t),n=await ii({root:e.runtimeDir,file:r.journal,maxBytes:nb,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(ab.decode(n.bytes)),o=sb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function db(e,t,i){let r;try{r=await lb.readdir(e.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 Zs(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Zn(n.name))try{let a=await Us(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(pf(a))return!0}catch{return!0}return!1}async function fb(e,t){let i=Date.now()+5e3,r=ub.join(e.locksDir,"root-move.lock");for(;;)try{return await Kn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Zd(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 _(e,t,i,r){let n=await fb(e,t);try{if(await Fn(e.projectRoot),await db(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Yn(n)}}import{createHash as hb}from"crypto";function ge(e){return hb("sha256").update(e).digest("hex")}var GR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var UR=8*1024*1024;var KR=64*1024,YR=64*1024;var XR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},QR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var ZR=(1n<<256n)-1n;var Nb=di(Gt(),1);var mC=4*1024*1024;var bb=null;function kb(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function bf(e,t){return(...i)=>{let r=bb;if(r===null)return t(...i);let n=kb(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var NC=bf("hookWritePolicy",async e=>(await bs(e))?.hook??{allow_paths:[]});var mA=256*1024;var CA={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 ri from"node:path";var or=/^[a-f0-9]{64}$/u,Sf=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Pb=16*1024,WA=process.platform;function xb(e,t){let i=ri.relative(e,t);return ri.isAbsolute(i)||i===".."||i.startsWith(`..${ri.sep}`)?null:i.replaceAll("\\","/")||"."}function Ef(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Pf(e,t){if(e.length===0||Ef(e)||e.includes("\\")||ri.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=ri.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Rb(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 ec(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ef(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Cb(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ec(e.changeBranch,"Native workspace change branch"),ec(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 Ab(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Sf.test(t.baseCommit)||typeof t.targetCommit!="string"||!Sf.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");ec(t.targetBranch,"Native workspace Git target branch")}function _b(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","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.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"||!or.test(String(t.projectRootId))||!or.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Rb(t.capturedAt),Pf(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!or.test(String(t.projectRootPathId))||a&&!or.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!or.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Ab(t.git),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(Cb(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 Tb(e,t){return ri.join(Oe(e,t),"workspace.json")}function Ib(e,t){let i=Tb(e,t),r=He(e,i),n=xb(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Pf(n,"Native workspace file ref")}}async function jb(e,t){try{let i=Ib(e,t),r=await V({root:i.root,ref:i.ref,maxBytes:Pb});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function sr(e,t){let i=await jb(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(_b(i),i)}var Rf=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Ob=new Set(Rf),Cf=new Set([...Rf,"minimum_runtime_version","revision"]),Hb=new Set([...Cf,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Db=new Set(["capability","operation","source","base_hash"]),Bb=new Set(["shape","build","verify","archive"]),Lb=new Set(["implicit","confirmed"]),Mb=new Set(["pending","pass","fail"]),_t="comet-state.yaml",ic=/^[a-f0-9]{64}$/u,Af=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fb=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,rc=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"},ai=class extends Error{constructor(i,r){super(i!==Ye||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"},sa=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"},cr=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"},ca=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"},m_=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
150
|
+
`);function ur(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _f(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ac(e){if(!Af.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Vb(e){if(!Af.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Tf(e,t){if(e.length===0||ni.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function qb(e,t){let i=ur(e,`spec_changes[${t}]`);if(_f(i,Db,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Vb(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"&&Tf(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"||!ic.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"||!ic.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 Wb(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 oc(e,t){if(_f(e,t,_t),typeof e.name!="string")throw new Error("Native change name is required");if(ac(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"||!Bb.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&&!Lb.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(qb),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 e.verification_result!="string"||!Mb.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"&&Tf(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Wb(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 rr(e){let t=ur(e,_t);if(t.schema!==Me)throw new Error(`Expected ${Me}`);return{schema:Me,...oc(t,Ob)}}function lr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function tc(e,t,i){if(e===null)return null;let r=typeof e=="string"?Fb.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function zb(e){if(e==null)return null;if(typeof e!="string"||!ic.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Jb(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 nr(e){let t=ur(e,_t);if(t.schema!==Le)throw new Error(`Expected ${Le}`);if(lr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Le} minimum_runtime_version must be 2`);return{schema:Le,minimum_runtime_version:2,revision:lr(t.revision,"Native v2 revision"),...oc(t,Cf)}}function ar(e){let t=ur(e,_t);if(t.schema!==Ye){if(t.schema===Me||t.schema===Le){let o=t.schema===Me?rr(t):nr(t);throw new rc(o.name,o.schema)}throw new ai(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=lr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ai(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=lr(t.revision,"Native revision"),n=oc(t,Hb),a=zb(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:r,verification_protocol:Jb(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:tc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:tc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:tc(t.partial_allowance,"Native partial_allowance","allowances")}}function Gb(e){let t=ur(e,_t);if(t.schema===Me){let n=rr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema===Le){let n=nr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema!==Ye){let n=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:n,state:null,message:new ai(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=lr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ai(t.schema,i).message};let r=ar(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Fe(e,t){ac(t);let i=ni.join(e.changesDir,t);if(!X(e.changesDir,i))throw new Error("Native change path escaped");return i}var Ub=256*1024;async function Kb(e,t=ni.dirname(e)){let i=ni.relative(t,e).split(ni.sep).join("/"),r=await V({root:t,ref:i,maxBytes:Ub}),n=(0,nc.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function If(e,t){let i=ni.join(Fe(e,t),_t);await B(e.nativeRoot,i);let r=Gb(await Kb(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{randomUUID as ba}from"node:crypto";import{promises as wr}from"node:fs";import W from"node:path";import{createWriteStream as vk,promises as gk}from"node:fs";import se from"node:path";import{spawn as sc}from"node:child_process";import{existsSync as jf}from"node:fs";import Tt from"node:path";var Yb=new Set([".bat",".cmd",".ps1"]),Xb=new Set([".bat",".cmd"]),Qb=/[&|<>()^%"!\r\n]/u,Zb=["$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("; ");function cc(e,t){let i=t.toLowerCase();return Object.entries(e).find(([r,n])=>r.toLowerCase()===i&&n!==void 0)?.[1]}function ek(e){let t=(cc(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function tk(e,t,i){let n=Tt.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(cc(t,"PATH")??"").split(Tt.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Tt.win32.extname(e)?[e]:ek(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Tt.join(s,c):Tt.resolve(i,c)))}function ik(e,t,i){return tk(e,t,i).find(r=>jf(r))??e}function rk(e){let t=cc(e,"SystemRoot");if(t){let i=Tt.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(jf(i))return i}return"powershell.exe"}function nk(e){if(e.some(t=>Qb.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function ak(e,t,i){let r=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(Zb,"utf16le").toString("base64");return sc(rk(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:i.cwd,env:{...i.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function lc(e,t,i){let r=i.env??process.env;if(process.platform!=="win32")return sc(e,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=ik(e,r,i.cwd),a=Tt.win32.extname(n).toLowerCase();return Xb.has(a)&&nk(t),Yb.has(a)?ak(n,t,{cwd:i.cwd,env:r}):sc(n,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as ok}from"node:child_process";import uc from"node:path";var sk=1e3,ck=2;async function la(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,r=i&&uc.win32.isAbsolute(i)?uc.win32.resolve(i):"C:\\Windows",n=uc.win32.join(r,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(d,u=!1)=>{s||(s=!0,l&&clearTimeout(l),u&&c?.kill("SIGKILL"),o(d))};try{c=ok(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",d=>f(d===0)),l=setTimeout(()=>f(!1,!0),sk)}catch{f(!1)}});for(let o=0;o<ck;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}var lk=/\b(Bearer|Basic)\s+[^\s"']+/giu,uk=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,dk=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,fk=/\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,hk=/("(?:[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,pk=/(["'])((?:[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,mk=/\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 mt(e){return e.replace(lk,"$1 [REDACTED]").replace(uk,"[REDACTED PRIVATE KEY]").replace(dk,"$1[REDACTED]@").replace(fk,"[REDACTED TOKEN]").replace(hk,'$1"[REDACTED]"').replace(pk,"$1$2$1$3$4[REDACTED]$4").replace(mk,"$1$2[REDACTED]")}function $f(e,t){let i=se.relative(e,t);return i===""||!se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${se.sep}`)}function Of(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function ua(e,t){if(t.length===0||t.includes("\\")||se.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||se.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let i=se.resolve(e),r=se.resolve(i,...t.split("/"));if(!$f(i,r))throw new Error("Native check cwd escaped the project root");return r}function dr(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var wk=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function dc(e){let t=!1;return e.map(i=>{if(t)return t=!1,"[REDACTED]";let r=mt(i);return wk.test(i)&&(t=!0),r})}function da(e,t){if(Of(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return ua(e,t.cwdRef)}async function fc(e){let{plan:t}=e;Of(e.operationId,"Native check operation ID");let i=da(e.projectRoot,t),r=se.join(e.runtimeDir,"logs","checks"),n=se.join(r,`${e.operationId}-${t.id}.log`);if(!$f(se.resolve(e.runtimeDir),se.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await gk.mkdir(r,{recursive:!0});let a=(e.now??(()=>new Date))(),o=vk(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=lc(t.executable,t.argv,{cwd:i,env:process.env})}catch(p){o.destroy(),c(p);return}let f=!1,d=null,u=setTimeout(()=>{f=!0,la(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);u.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",p=>{d=p,o.write(`
|
|
151
|
+
[comet] failed to start check: ${mt(p.message)}
|
|
152
|
+
`)}),l.once("close",(p,m)=>{clearTimeout(u);let h=(e.now??(()=>new Date))();o.end(()=>{let v=f||d!==null||m!==null;s({id:t.id,name:t.name,argvDisplay:dc(t.argv),cwdRef:t.cwdRef,status:v?"interrupted":p===0?"passed":"failed",exitCode:p,signal:m,timedOut:f,durationMs:Math.max(0,h.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:h.toISOString(),repeatable:t.repeatable,logRef:se.relative(e.runtimeDir,n).split(se.sep).join("/")})})}),o.once("error",p=>{clearTimeout(u),la(l).catch(()=>l.kill("SIGKILL")),c(p)})})}import{randomUUID as kk}from"node:crypto";var Hf=Symbol("comet.native.trusted-execution-identity"),Df=Symbol("comet.native.trusted-verifier-envelope"),q="skill-coordinated";function hc(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function fr(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){hc(t.identityProvider,"Native identity provider");let i=Object.freeze({identityProvider:q,executionRef:hc(t.executionRef,"Native execution ref"),[Hf]:!0});return e.add(i),i},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:hc(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Df]:!0})}})}function fa(e){return typeof e=="object"&&e!==null&&e[Df]===!0}function Bf(e){return typeof e=="object"&&e!==null&&e[Hf]===!0}function ha(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function pr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function It(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function yk(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,i)=>{let r=ha(t,`Native Verifier acceptance ${i}`);hr(r,["id","result","reason"],`Native Verifier acceptance ${i}`);let n=It(r.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(r.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:r.result,reason:It(r.reason,`Native Verifier acceptance ${n} reason`)}})}function Nk(e){let t=ha(e,"Native Verifier final result");if(hr(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:pr(t.iteration,"Native Verifier iteration"),attempt:pr(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:yk(t.acceptance),risks:t.risks,summary:It(t.summary,"Native Verifier summary")}}function bk(e,t){let i=ha(e,`Native Verifier check request ${t}`);if(hr(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let r=pr(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(r<1)throw new Error("Native Verifier check timeout must be positive");return{id:It(i.id,`Native Verifier check request ${t} ID`),name:It(i.name,`Native Verifier check request ${t} name`),executable:It(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:It(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:r,repeatable:i.repeatable}}function pc(e){let t=ha(e,"Native Verifier response");if(t.kind==="final-result")return hr(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:Nk(t.result)};if(t.kind==="request-checks"){if(hr(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:pr(t.iteration,"Native Verifier iteration"),attempt:pr(t.attempt,"Native Verifier attempt"),checks:t.checks.map(bk)}}throw new Error("Native Verifier response kind is invalid")}function Lf(e){if(!fa(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:i}=e;if(t.candidateId!==i.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==i.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===i.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let r=pc(t.payload),n=r.kind==="final-result"?r.result.iteration:r.iteration,a=r.kind==="final-result"?r.result.attempt:r.attempt;if(n!==i.iteration||a!==i.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(r.kind==="request-checks")return r;let o=[...i.acceptanceIds],s=r.result.acceptance.map(({id:u})=>u),c=s.filter((u,p)=>s.indexOf(u)!==p),l=s.filter(u=>!o.includes(u)),f=o.filter(u=>!s.includes(u));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!i.requiredChecksPassed&&r.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=r.result.acceptance.map(({result:u})=>u);if(r.result.verdict==="pass"&&d.some(u=>u!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(r.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(r.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return r}var mr=3,mc=2;function ce(e){return e.state_version+1}function Sk(e,t,i){let r=[...e];if(new Set(r).size!==r.length)throw new Error(`${i} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${i} contains unknown IDs: ${a.join(", ")}`);return r}function vc(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Ek(e){return(e??[]).map(t=>({name:I(t.name),result:t.result,note:t.note?I(t.note):null}))}function jt(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:I(e.summary),completed_at:e.completedAt}}function Mf(e){let t=P(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let i=e.acceptance.map(({id:r})=>r);if(new Set(i).size!==i.length)throw new Error("Native acceptance IDs must be unique");return P({...t,phase:"build",state_version:ce(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(r=>({...r,result:"pending",reason:null}))})}function gc(e){let t=P(e.state),{input:i}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Bf(i.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");let r=Sk(i.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=(i.now??new Date).toISOString();return P({...t,phase:"verify",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:vc(t.acceptance),builder_handoff:{candidate_id:i.candidateId??kk(),identity_provider:i.identity.identityProvider,builder_execution_ref:i.identity.executionRef,iteration:t.loop.iteration,summary:I(i.summary),addressed_acceptance_ids:r,checks:Ek(i.checks),checks_truncated:!1,known_limits:(i.knownLimits??[]).map(a=>I(a)),known_limits_truncated:!1,submitted_at:n},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Ff(e){let t=P(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt is not ready to dispatch");return P({...t,state_version:ce(t),loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Pk(e,t){let i=e.loop.previous_unresolved_ids;if(i.length===0)return 0;let r=new Set(i),n=new Set(t);return n.size<r.size&&[...n].every(o=>r.has(o))?0:e.loop.no_progress_count+1}function xk(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===q?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:I(e.response.result.summary),risks:e.response.result.risks.map(t=>I(t)),risks_truncated:!1,completed_at:e.completedAt}}function Vf(e){let t=P(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let i=Lf({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:t.acceptance.map(({id:m})=>m),requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let r=(e.now??new Date).toISOString(),n=new Map(i.result.acceptance.map(m=>[m.id,m])),a=t.acceptance.map(m=>{let h=n.get(m.id);return{...m,result:h.result,reason:I(h.reason)}}),o=a.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),s=xk({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:r});if(i.result.verdict==="pass"){let m=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"pass",summary:i.result.summary,completedAt:r})),h=t.builder_handoff.identity_provider===q;return{response:i,state:P({...m,phase:h?"verify":"archive",status:h?"await-user":"active",state_version:ce(t),verification_result:"pass",verification_report:"verification.md",blockers:h?[{owner:"user",reason:I("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:h?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:h?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"blocked",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:P({...m,status:"await-user",state_version:ce(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:I(i.result.summary),acceptance_ids:o,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:o,next_action:"resolve-verifier-blocker"}})}}let c=t.loop.failed_iteration_count+1,l=Pk(t,o),f=c>=e.maxVerifyFailures,d=l>=3,u=f||d,p=he({...t,acceptance:a,verification:s},jt({state:t,outcome:"fail",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:P({...p,phase:u?"verify":"build",status:u?"await-user":"active",state_version:ce(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:u?[{owner:"user",reason:I(f?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:o,resolution_action:"await-user"}]:l>=2?[{owner:"builder",reason:I("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:o,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:u?"await-user":"repairing",iteration:u?t.loop.iteration:t.loop.iteration+1,attempt:u?t.loop.attempt:0,failed_iteration_count:c,no_progress_count:l,execution_failure_count:0,previous_unresolved_ids:o,next_action:u?"await-user":"repair-failed-acceptance"}})}}function qf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==q||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return P({...t,phase:"archive",status:"active",state_version:ce(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Wf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==q||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let i=(e.now??new Date).toISOString(),r=t.acceptance.map(({id:a})=>a),n=he(t,jt({state:t,outcome:"blocked",unresolvedIds:r,summary:e.summary,completedAt:i}));return P({...n,status:"await-user",state_version:ce(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:I(e.summary),risks:[I("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:i},blockers:[{owner:"user",reason:I("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:r,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:r,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function zf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let i=(e.now??new Date).toISOString(),r=I(e.summary),n=he(t,jt({state:t,outcome:"pass",summary:e.summary,completedAt:i}));return P({...n,phase:"archive",status:"active",state_version:ce(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:r,completed_at:i},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:I(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Jf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return P({...t,status:"active",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,acceptance:vc(t.acceptance),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Gf(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let i=(e.now??new Date).toISOString(),r=t.loop.execution_failure_count+1,n=r>=mr,a=he(t,jt({state:t,outcome:"execution-error",summary:e.summary,completedAt:i}));return P({...a,status:n?"blocked":"active",state_version:ce(t),blockers:n?[{owner:"runtime",reason:I(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:r,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Uf(e){let t=P(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return P({...t,status:"active",state_version:ce(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function vr(e){let t=P(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=he(t,jt({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return P({...r,phase:"build",status:"active",state_version:ce(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:vc(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as Yf}from"node:fs";import gr from"node:path";function pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ma(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ve(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Kf(e,t){return e===null?null:Ve(e,t)}function ga(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Rk(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function Ck(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function va(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function wc(e,t){if(e===null)return null;let i=Ve(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function yc(e,t){let i=Ve(e,t);if(!gr.isAbsolute(i))throw new Error(`${t} must be absolute`);return gr.resolve(i)}function Ak(e,t){let i=`Native local checks[${t}]`,r=pa(e,i);if(ma(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)=>Ve(l,`${i}.argv[${f}]`,!0)),a=va(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=wc(r.startedAt,`${i}.startedAt`),s=wc(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=ga(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ve(r.id,`${i}.id`),name:Ve(r.name,`${i}.name`),operationId:Ve(r.operationId,`${i}.operationId`),status:a,repeatable:Ck(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:ga(r.executionCount,`${i}.executionCount`),argv:n,cwd:yc(r.cwd,`${i}.cwd`),exitCode:Rk(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ve(r.log,`${i}.log`)}}function Nc(e){let t="Native local execution state",i=pa(e,t);if(ma(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Xi)throw new Error(`Native local execution schema must be ${Xi}`);let r=pa(i.workspace,"Native local workspace");ma(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=pa(i.execution,"Native local execution");ma(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=wc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ve(o.operationId,"Native local execution.operationId"),stage:va(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:va(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Kf(o.executionId,"Native local execution.executionId"),status:va(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ga(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(Ak);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:Xi,change:Ve(i.change,"Native local change"),basedOnStateVersion:ga(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:yc(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:yc(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Kf(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function U(e){return Nc({schema:Xi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:gr.resolve(e.projectRoot),worktreeRoot:gr.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function qe(e){let t;try{t=await Yf.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return Nc(i)}async function j(e,t,i={}){let r=Nc(t);await Yf.mkdir(gr.dirname(e),{recursive:!0}),await fe(e,r,i)}async function bc(e){let t=null,i=null;try{t=await qe(e.file),t===null&&(i="missing")}catch(n){if(n.code)throw n;i="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(i="version-mismatch"),t&&i===null)return{state:t,rebuilt:!1,reason:null};let r=U(e);return await j(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:r,rebuilt:!0,reason:i??"missing"}}import{promises as _k}from"node:fs";function vt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
153
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Qe(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function Tk(e){return e.verification?.assurance==="semantic-verification-unavailable"?"Semantic verification unavailable, user confirmation required":e.verification?.assurance==="user-confirmed-degraded"?"Passed with user-confirmed degraded assurance":e.verification_result==="pass"?e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?"Passed, user confirmation required":"Passed":e.verification_result==="blocked"?"Blocked":e.verification_result==="fail"?"Failed":"Pending"}function Ik(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===q?q:"host-attested")}function jk(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${Qe(o.id)} | ${Qe(o.result)} | ${Qe(o.source)} | ${Qe(o.text)} | ${Qe(vt(o.reason))} |`).join(`
|
|
154
|
+
`),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(vt).join(" ");return`| ${Qe(vt(o.name))} | ${Qe(s||"—")} | ${Qe(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(`
|
|
155
|
+
`),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${vt(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(`
|
|
156
|
+
`),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${vt(o)}`).join(`
|
|
157
|
+
`),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${Qe(vt(o.summary))} | ${o.completed_at} |`)].join(`
|
|
158
|
+
`);return`---
|
|
159
|
+
generated_from_state_version: ${e.state_version}
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
# Verification
|
|
163
|
+
|
|
164
|
+
## Current result
|
|
165
|
+
|
|
166
|
+
- Result: **${Tk(e)}**
|
|
167
|
+
- Assurance: **${Ik(e)}**
|
|
168
|
+
- Goal cycle: ${e.loop.goal_cycle}
|
|
169
|
+
- Iteration: ${e.verification.iteration}
|
|
170
|
+
- Verifier attempt: ${e.verification.attempt}
|
|
171
|
+
- Completed: ${e.verification.completed_at}
|
|
172
|
+
- Summary: ${vt(e.verification.summary)}
|
|
173
|
+
|
|
174
|
+
## Acceptance
|
|
175
|
+
|
|
176
|
+
| ID | Result | Source | Criterion | Reason |
|
|
177
|
+
| --- | --- | --- | --- | --- |
|
|
178
|
+
${t}
|
|
179
|
+
|
|
180
|
+
## Checks
|
|
181
|
+
|
|
182
|
+
${i}
|
|
183
|
+
|
|
184
|
+
## Blockers
|
|
185
|
+
|
|
186
|
+
${r}
|
|
187
|
+
|
|
188
|
+
## Risks and skipped work
|
|
189
|
+
|
|
190
|
+
${n}
|
|
191
|
+
|
|
192
|
+
## Previous iterations
|
|
193
|
+
|
|
194
|
+
${a}
|
|
195
|
+
|
|
196
|
+
${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summary: ${e.history_overflow.dropped_entries}.
|
|
197
|
+
|
|
198
|
+
`:""}## Conclusion
|
|
199
|
+
|
|
200
|
+
${vt(e.verification.summary)}
|
|
201
|
+
`}function $k(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function Xf(e){let t;try{t=await _k.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=$k(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function oi(e){await xe(e.file,jk(e.state))}var Zf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ok="comet-state.yaml",Hk="state.json";function ye(e,t){if(!Zf.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=W.join(e.changesDir,t);if(!X(e.changesDir,i))throw new Error("Native change path escaped");return i}function Te(e,t){return W.join(ye(e,t),Ok)}function T(e,t){return W.join(Ue(e,t),Hk)}async function yr(e,t){try{let i=await wr.readFile(Te(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function we(e){return ue(e).currentBranch}async function H(e,t){return Ce(Te(e,t))}async function ne(e){let t=await Qi({file:Te(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=W.join(ye(e.paths,t.name),"verification.md");await B(e.paths.nativeRoot,i),await wr.rm(i,{force:!0})}return t}async function eh(e){let t=ye(e.paths,e.state.name),i=W.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await wr.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Zf.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=W.join(t,...s.split("/")),l=await wr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=W.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await wr.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function th(e){let t=ye(e.paths,e.state.name),i=await V({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await V({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Xn({briefMarkdown:i.text,specs:r})}async function ih(e){return _(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await eh({paths:e.paths,state:t}),r=await th({paths:e.paths,state:t,specChanges:i}),n=await Zi({changeDir:ye(e.paths,t.name),acceptanceIds:r.map(({id:s})=>s)});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=Mf({state:{...t,spec_changes:i},acceptance:r.map(s=>({...s}))});if(delete a.children_contract_hash,n){a.children_contract_hash=Gn({acceptance:a.acceptance,children:n.contract});let s=[...t.history].reverse().find(({outcome:c})=>c==="pass"||c==="fail");if(s?.outcome==="fail"&&s.unresolved_ids.length>0){let c=await Ct({paths:e.paths,state:a}),l=new Set((c?.children??[]).filter(({status:d})=>d!=="done").flatMap(({covers:d})=>d)),f=s.unresolved_ids.filter(d=>!l.has(d));if(f.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${f.join(", ")}`)}}let o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),U({portableState:o,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}async function ka(e){let t=await eh(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await th({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!af(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Zi({changeDir:ye(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Gn({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Ze(e){let t=await ka(e);if(!t.drifted)return;let i=t.reason??"Native confirmed requirements changed";throw await gh({paths:e.paths,state:e.state,reason:i}),new Error(`${i}; Native change returned to Shape and requires confirmation`)}async function rh(e){return _(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),await Zi({changeDir:ye(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a)})||t.children_contract_hash)throw new Error("Native parent Build advances child changes instead of a parent Builder");let r=gc({state:t,input:e.input}),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),U({portableState:n,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function nh(e){return _(e.paths,`complete portable parent Build ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.phase!=="build"||t.status!=="active")throw new Error("Native parent integration can only complete from active Build");await Ze({paths:e.paths,state:t});let i=await Ct({paths:e.paths,state:t});if(!i||!t.children_contract_hash)throw new Error(`Native change ${t.name} has no confirmed child contract`);if(!i.confirmed)throw new Error("Native parent child declarations require Shape confirmation");if(!i.allDone)throw new Error("Native parent cannot enter Verify before every child is merged");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; add and confirm a repair child");let n=fr().captureExecutionIdentity({identityProvider:"skill-coordinated",executionRef:`native-parent-integration:${ba()}`}),a=gc({state:t,input:{identity:n,summary:e.summary,addressedAcceptanceIds:t.acceptance.map(({id:s})=>s),checks:[],knownLimits:[]}}),o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),U({portableState:o,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}function Sc(e,t,i){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:ua(i,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function ah(e,t,i,r){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Sc(t,i,r),executionCount:e.executionCount}}function oh(e,t){let i=W.relative(W.resolve(e),W.resolve(t));if(W.isAbsolute(i)||i===".."||i.startsWith(`..${W.sep}`))throw new Error("Native local check cwd escaped the project root");let r=i.length===0?".":i.split(W.sep).join("/");return ua(e,r),r}function kc(e,t){let[i,...r]=e.argv;if(!i)throw new Error(`Native local check ${e.id} has no executable`);return dr({id:e.id,name:e.id,executable:i,argv:r,cwdRef:oh(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Dk(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function si(e){let t=new Map;for(let i of e.supplied){if(t.has(i.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${i.id}`);t.set(i.id,i)}return e.local.checks.map(i=>{if(i.status==="planned"||i.status==="running")throw new Error(`Native Runtime check ${i.id} has not completed`);let r=e.requestedNames?.get(i.id)??i.name;return{id:i.id,name:I(r),argv_display:dc(i.argv.slice(1)).map(n=>I(n)),argv_truncated:!1,cwd_ref:oh(e.projectRoot,i.cwd),status:i.status,exit_code:i.exitCode,duration_ms:Dk(i)}})}function Bk(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Nr(e){if(e.local===null||e.local.change!==e.state.name)return U({portableState:e.state,projectRoot:e.projectRoot,branch:we(e.projectRoot)});let t=e.local.execution?.operationId??ba();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(i=>i.status==="running"||i.status==="planned"?{...i,operationId:t,status:"interrupted"}:{...i,operationId:t})}}async function ci(e){try{let t=await qe(T(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function sh(e){let{state:t,local:i,expected:r}=e;if(t.state_version!==r.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==r.iteration||t.loop.attempt!==r.attempt||t.builder_handoff===null||i===null||i.basedOnStateVersion!==t.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return i}function Lk(e){let{state:t,local:i,envelope:r}=e;if(!fa(r))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(r.candidateId!==t.builder_handoff.candidate_id||r.identityProvider!==t.builder_handoff.identity_provider||r.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(i===null||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==null&&i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return r}function Mk(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Na(e){let t=await ci({paths:e.paths,state:e.state}),i=Gf({state:e.state,summary:e.summary}),r=await ne({paths:e.paths,previous:e.state,next:i});return await j(T(e.paths,e.state.name),Nr({local:t,state:r,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),r}function Qf(e,t,i){return e.checks.length!==t.length?!1:e.checks.every((r,n)=>kc(r,i)===dr(t[n]))}async function Fk(e){return _(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let i=T(e.paths,t.name),r=(await bc({file:i,portableState:t,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(r.execution?.stage==="checking"&&r.execution.actor==="runtime"&&Qf(r,e.plans,e.paths.projectRoot)){let o=r.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=r.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:si({local:r,projectRoot:e.paths.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=vr({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await ne({paths:e.paths,previous:t,next:c});throw await j(T(e.paths,t.name),U({portableState:l,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(r.execution!==null&&r.checks.length>0){if(!(r.execution.stage==="checking"&&r.execution.actor==="runtime"&&r.checks.some(s=>s.status==="interrupted")&&Qf(r,e.plans,e.paths.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(r.execution!==null||r.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=ba(),a={...r,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=r.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?ah(s,o,n,e.paths.projectRoot):s?{...s,operationId:n}:Sc(o,n,e.paths.projectRoot)})};return await j(i,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=r.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function wa(e){return _(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let i=T(e.paths,t.name),r=await qe(i);if(r===null||r.basedOnStateVersion!==t.state_version||r.execution?.operationId!==e.operationId||r.execution.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(r);return await j(i,n,{containedRoot:e.paths.runtimeDir}),n})}async function ch(e){if(new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let t=[],i=new Set;for(let s of e.plans){da(e.paths.projectRoot,s);let c=dr(s);i.has(c)||(i.add(c),t.push(s))}let r=await Fk({...e,plans:t});if(r.kind==="reuse")return r;let n=r.local.execution.operationId,a=Ue(e.paths,r.state.name);try{for(let s of r.plans){let c=new Date().toISOString();await wa({paths:e.paths,state:r.state,operationId:n,update:f=>({...f,checks:f.checks.map(d=>d.id===s.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:c}:d)})});let l=await fc({projectRoot:e.paths.projectRoot,runtimeDir:a,operationId:n,plan:s});await wa({paths:e.paths,state:r.state,operationId:n,update:f=>({...f,checks:f.checks.map(d=>d.id===s.id?{...d,status:l.status,exitCode:l.exitCode,startedAt:l.startedAt,completedAt:l.completedAt,log:l.logRef}:d)})})}await wa({paths:e.paths,state:r.state,operationId:n,update:s=>({...s,execution:{...s.execution,status:"completed"}})})}catch(s){try{await wa({paths:e.paths,state:r.state,operationId:n,update:c=>({...c,execution:{...c.execution,status:"interrupted"},checks:c.checks.map(l=>l.status==="planned"||l.status==="running"?{...l,status:"interrupted"}:l)})})}catch{}throw s}let o=await qe(T(e.paths,r.state.name));if(o===null)throw new Error("Native Runtime check state disappeared after execution");return{state:r.state,checks:si({local:o,projectRoot:e.paths.projectRoot,supplied:[]})}}async function Vk(e){let t=T(e.paths,e.state.name),i=e.local;if(i===null||i.change!==e.state.name||i.basedOnStateVersion!==e.state.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(i.execution.executionId!==null&&i.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(i.execution.requestCheckRounds>=mc)throw new Error(`Native Verifier request-checks exceeded ${mc} rounds for this attempt`);let r=new Map,n=new Map,a=new Map;for(let p of i.checks){let m=kc(p,e.paths.projectRoot);n.set(m,p),p.status!=="interrupted"&&r.set(m,p),a.set(p.id,m)}let o=new Map,s=new Map;for(let p of e.response.checks){let m=Bk(p);da(e.paths.projectRoot,m);let h=dr(m),v=s.get(m.id);if(v!==void 0&&v!==h)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let g=a.get(m.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(h)||o.set(h,m)}let c=[...o.entries()],l=c.filter(([p])=>!r.has(p));if(i.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=i.execution.requestCheckRounds+1,d=new Map(c.map(([,p])=>[p.id,p.name])),u={...i,execution:{...i.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...i.checks.map(p=>{let m=kc(p,e.paths.projectRoot),h=o.get(m);return h&&p.status==="interrupted"?ah(p,h,i.execution.operationId,e.paths.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Sc(p,i.execution.operationId,e.paths.projectRoot))]};return await j(t,u,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:u,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,p])=>p),requestedNames:d,reusedCheckIds:c.filter(([p])=>r.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function ya(e){return _(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let i=T(e.paths,t.name),r=await qe(i),n=r?.execution;if(r===null||r.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(r);return await j(i,a,{containedRoot:e.paths.runtimeDir}),a})}async function qk(e){let t;try{for(let i of e.reservation.novelPlans){let r=new Date().toISOString();t=await ya({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:r}:o)})});let n=await fc({projectRoot:e.paths.projectRoot,runtimeDir:Ue(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:i});t=await ya({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await ya({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(i){try{await ya({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,status:"interrupted"},checks:r.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw i}return{checks:si({local:t,projectRoot:e.paths.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:i})=>i)}}}async function lh(e){return _(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=(await bc({file:T(e.paths,t.name),portableState:t,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");si({local:i,projectRoot:e.paths.projectRoot,supplied:e.checks});let r=Ff(t),n=await ne({paths:e.paths,previous:t,next:r}),a=T(e.paths,t.name),o=ba();return await j(a,{...i,basedOnStateVersion:n.state_version,execution:{operationId:o,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(s=>({...s,operationId:o}))},{containedRoot:e.paths.runtimeDir}),n})}async function uh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await _(e.paths,`apply portable verifier ${e.name}`,async()=>{let i=await H(e.paths,e.name);await Ze({paths:e.paths,state:i});let r=await ci({paths:e.paths,state:i}),n=Lk({state:i,local:r,envelope:e.envelope}),a;try{a=pc(n.payload)}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,u=await Na({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${u.loop.execution_failure_count}/${mr} was recorded`,{cause:f})}let o=Mk(a);if(o.iteration!==i.loop.iteration||o.attempt!==i.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let s=[],c;try{r!==null&&(s=si({local:r,projectRoot:e.paths.projectRoot,supplied:e.checks}));let f=Vf({state:i,envelope:n,checks:s,maxVerifyFailures:e.maxVerifyFailures});if(f.response.kind==="request-checks"){if(r===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Vk({paths:e.paths,state:i,local:r,envelope:n,response:f.response,suppliedChecks:s});return{kind:"request-checks",state:i,response:f.response,reservation:d}}if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==n.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");c=f}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,u=await Na({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${u.loop.execution_failure_count}/${mr} was recorded`,{cause:f})}let l=await ne({paths:e.paths,previous:i,next:c.state});return await j(T(e.paths,i.name),l.loop.next_action==="resolve-verifier-blocker"?Nr({local:r,state:l,projectRoot:e.paths.projectRoot}):U({portableState:l,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),l.verification!==null&&await oi({file:W.join(ye(e.paths,i.name),"verification.md"),state:l}),{kind:"final-result",result:{state:l,response:c.response,checks:s,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let i=await qk({paths:e.paths,reservation:t.reservation});return{state:t.state,response:t.response,checks:i.checks,requestChecks:i.requestChecks}}catch(i){let r=`Native Verifier response was invalid: ${i.message}`,n=await _(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Na({paths:e.paths,state:a,summary:r})});throw new Error(n?`${r}; execution error ${n.loop.execution_failure_count}/${mr} was recorded`:`${r}; the portable state changed before the execution error could be recorded`,{cause:i})}}async function dh(e){return _(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await ci({paths:e.paths,state:t});if(sh({state:t,local:i,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Na({paths:e.paths,state:t,summary:e.summary})})}async function fh(e){return _(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=await ci({paths:e.paths,state:t}),r=sh({state:t,local:i,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=si({local:r,projectRoot:e.paths.projectRoot,supplied:[]}),a=Wf({state:t,checks:n,verifierExecutionRef:r.execution.executionId,summary:e.summary}),o=await ne({paths:e.paths,previous:t,next:a});return await j(T(e.paths,t.name),Nr({local:r,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:o}),o})}async function hh(e){return _(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=qf(t),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:r}),r})}async function ph(e){return _(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=zf({state:t,summary:e.summary}),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await oi({file:W.join(ye(e.paths,t.name),"verification.md"),state:r}),r})}async function mh(e){return _(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let i=await ci({paths:e.paths,state:t}),r=Jf(t),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),Nr({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function vh(e){return _(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),i=await ci({paths:e.paths,state:t}),r=Uf(t),n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),Nr({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Sa(e){return _(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(t.phase==="build")return t;let i=vr({state:t,reason:e.reason}),r=await ne({paths:e.paths,previous:t,next:i});return await j(T(e.paths,t.name),U({portableState:r,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r})}async function Ec(e){return _(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);return t.phase==="shape"?t:gh({paths:e.paths,state:t,reason:e.reason})})}async function gh(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...he(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:I(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await ne({paths:e.paths,previous:t,next:r});return await j(T(e.paths,t.name),U({portableState:n,projectRoot:e.paths.projectRoot,branch:we(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ea(e){if(e.state.verification===null)return"not-applicable";let t=W.join(ye(e.paths,e.state.name),"verification.md");return await Xf({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await oi({file:t,state:e.state}),"rebuilt")}var Jk=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function Gk(e,t){let i=await hf(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function wh(e,t){await br.mkdir(e.transactionsDir,{recursive:!0}),await fe(ea(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function yh(e,t){await Promise.all([br.rm(Ue(e,t),{recursive:!0,force:!0}),br.rm(Cs(e,t),{recursive:!0,force:!0}),...Jk.map(i=>br.rm(zk.join(Fe(e,t),i),{force:!0}))])}async function Nh(e,t){await j(T(e,t.name),U({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function bh(e,t){try{let i=await sr(e,t);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 kh(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=ue(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function Uk(e){let t=Fe(e.paths,e.state.name),i=await V({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await V({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Xn({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Sh(e,t){let i=await If(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Eh(e){return _(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Gk(e.paths,e.name),i=await yr(e.paths,e.name)?await Ce(Te(e.paths,e.name)):null;if(!t&&i)return await yh(e.paths,e.name),await Nh(e.paths,i),i;let r=null,n=null;for(t||(r=await Sh(e.paths,e.name),n=await bh(e.paths,e.name),kh(e.paths,n),t={schema:Qn,id:Wk(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await wh(e.paths,t));;){let a=sf(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await Sh(e.paths,e.name),n??=await bh(e.paths,e.name),kh(e.paths,n),i=of({state:r,acceptance:await Uk({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Jn(Te(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await yh(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ce(Te(e.paths,e.name)),await Nh(e.paths,i)),t={...t,status:a.nextStatus},await wh(e.paths,t)}return await br.rm(ea(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ce(Te(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Ph}from"node:fs";import xh from"node:path";function Kk(e,t){let i=ue(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function Yk(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Xk(e,t){let i=new Date().toISOString(),r=e.verification===null?e:he(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:I(t),completed_at:i});return P({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:Yk(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function Qk(e){try{let t=await qe(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Pc(e){return _(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Ea({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=Kk(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=T(e.paths,e.name),n=await Qk(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await j(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Ea({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=vr({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Qi({file:Te(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await Ph.rm(xh.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=U({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await j(r,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=c||l;if(f){let u=Xk(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await Qi({file:Te(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let d=U({portableState:t,projectRoot:e.paths.projectRoot,branch:ue(e.paths.projectRoot).currentBranch});return await Ph.mkdir(xh.dirname(T(e.paths,t.name)),{recursive:!0}),await j(r,d,{containedRoot:e.paths.runtimeDir}),await Ea({paths:e.paths,state:t}),{state:t,local:d,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{randomUUID as Zk}from"node:crypto";import{promises as Rh}from"node:fs";import eS from"node:path";function Rc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $t(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function We(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Ch(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,r)=>We(i,`${t}[${r}]`))}function tS(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,i)=>{let r=Rc(t,`Native Builder check ${i}`);if($t(r,["name","result","note"],`Native Builder check ${i}`),!["passed","failed","not-run"].includes(String(r.result)))throw new Error(`Native Builder check ${i} result is invalid`);if(r.note!==null&&typeof r.note!="string")throw new Error(`Native Builder check ${i} note is invalid`);return{name:We(r.name,`Native Builder check ${i} name`),result:r.result,note:r.note}})}function iS(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,i)=>{let r=Rc(t,`Native Runtime check ${i}`);if($t(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${i}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${i} argv is invalid`);if(!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1)throw new Error(`Native Runtime check ${i} timeoutMs is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Runtime check ${i} repeatable is invalid`);return{id:We(r.id,`Native Runtime check ${i} id`),name:We(r.name,`Native Runtime check ${i} name`),executable:We(r.executable,`Native Runtime check ${i} executable`),argv:[...r.argv],cwdRef:We(r.cwdRef,`Native Runtime check ${i} cwdRef`),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function Ah(e,t){let i=e.stateVersion,r=e.iteration,n=e.attempt;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:i,iteration:r,attempt:n,verifierExecutionRef:We(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function rS(e){let t=Rc(e,"Native Runner input");if(t.kind==="builder-handoff")return $t(t,["kind","summary","addressed_acceptance_ids","checks","known_limits"],"Native Runner Builder input"),{kind:"builder-handoff",summary:We(t.summary,"Native Builder summary"),addressed_acceptance_ids:Ch(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:tS(t.checks),known_limits:Ch(t.known_limits,"Native Builder known limits")};if(t.kind==="dispatch-verifier")return $t(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:iS(t.checks)};if(t.kind==="verifier-response")return $t(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return $t(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:We(t.summary,"Native Verifier execution error summary"),...Ah(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return $t(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:We(t.summary,"Native unavailable Verifier summary"),...Ah(t,"Native Runner unavailable Verifier input")};throw new Error("Native Runner input kind is invalid")}async function Ih(e,t){let i=eS.resolve(t,e),r=await Rh.lstat(i);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Rh.readFile(i,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return rS(n)}function _h(e){return`${q}:${e}:${Zk()}`}function kr(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==q)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function nS(e){return{iteration:e.iteration,summary:e.summary,addressedAcceptanceIds:[...e.addressed_acceptance_ids],checks:e.checks.map(t=>({name:t.name,result:t.result,note:t.note})),checksTruncated:e.checks_truncated,knownLimits:e.known_limits.map(t=>({...t})),knownLimitsTruncated:e.known_limits_truncated,submittedAt:e.submitted_at}}function Th(e,t,i){let r=kr(e);return{coordination:q,change:e.name,candidateId:r.candidate_id,stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:i,briefRef:e.brief,specRefs:e.spec_changes.map(({capability:n,operation:a,source:o})=>({capability:n,operation:a,ref:o})),acceptance:e.acceptance.map(({id:n,source:a,text:o})=>({id:n,source:a,text:o})),builderHandoff:nS(r),runtimeChecks:t.map(n=>({...n}))}}async function xc(e){kr(e.state);let t=await qe(T(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function jh(e){if(e.input.kind==="builder-handoff"){let c=fr().captureExecutionIdentity({identityProvider:q,executionRef:_h("builder")}),l=await rh({paths:e.paths,name:e.name,input:{identity:c,summary:e.input.summary,addressedAcceptanceIds:e.input.addressed_acceptance_ids,checks:e.input.checks,knownLimits:e.input.known_limits}});return{state:l,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(l)}}if(e.input.kind==="dispatch-verifier"){let s=await H(e.paths,e.name);if(s.builder_handoff!==null&&s.builder_handoff.identity_provider!==q){let d=await Sa({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:d,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(d)}}kr(s);let c=await ch({paths:e.paths,name:e.name,plans:e.input.checks}),l=_h("verifier"),f=await lh({paths:e.paths,name:e.name,checks:c.checks,verifierExecutionId:l});return{state:f,checks:c.checks,requestChecks:null,verifierDispatch:Th(f,c.checks,l),continuation:me(f)}}if(e.input.kind==="verifier-execution-error"){let s=await H(e.paths,e.name);kr(s),await xc({paths:e.paths,state:s});let c=await dh({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:c,checks:[],requestChecks:null,verifierDispatch:null,continuation:me(c)}}if(e.input.kind==="verifier-unavailable"){let s=await fh({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:s,checks:s.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:me(s)}}let t=await H(e.paths,e.name),i=kr(t),r=await xc({paths:e.paths,state:t}),n=fr(),a=n.captureExecutionIdentity({identityProvider:q,executionRef:r}),o=await uh({paths:e.paths,name:e.name,envelope:n.envelopeVerifierResponse({candidateId:i.candidate_id,identity:a,payload:e.input.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures});return{...o,verifierDispatch:o.requestChecks===null?null:Th(o.state,o.checks,await xc({paths:e.paths,state:o.state})),continuation:me(o.state)}}import _c from"path";var oS=["Outcome","Scope","Non-goals","Acceptance examples"],fI=[...oS,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var sS=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 $h=1024*1024;var Hh="scoped-text-safety",cS=1,lS=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var uS="comet.native.checker-policy.v1";var CI=te(uS,{policy:Hh,version:cS,limits:lS,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var dS=["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"],AI=new Set(dS);var pS=$h,JI=3*pS;var Dh={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:[]},vS=ge("comet-native-runtime:v3:scope-reopen"),yj=[{skillVersion:"3",skillHash:ge("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ge("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ge("comet-native-runtime:v1")}];var Lh=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Zj=new Set(Lh),SS=new Set([...Lh,"minimum_runtime_version","revision"]),e$=new Set([...SS,"operation"]),t$=512*1024,ES=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),i$=new Set([...ES,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var o$={maxAcceptanceCriteria:ir.maxCriteria};var d$={maxSpecs:64,maxFileBytes:Rn,maxTotalBytes:4*1024*1024};import{execFile as jS}from"node:child_process";import{promisify as $S}from"node:util";var b$={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var V$=512*1024;var Sr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var dO=64*1024;var fO=3600*1e3;var hO=$S(jS);var Pa=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(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};var QO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var c0=16*1024*1024,l0=256*1024,u0=16*1024;var m0=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var w0=16*1024;var _0=16*1024;var NH=16*1024*1024,xa=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"},Ra=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 Ca=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Vh=["--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."],Ac=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:Vh,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]
|
|
202
|
+
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]
|
|
203
|
+
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 Cc(e,t){return`${e}:
|
|
204
|
+
${t.map(i=>` ${i}`).join(`
|
|
205
|
+
`)}`}function MS(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Ac[i]||t.length>1&&Ac[t[0]]?.subcommands?i:t[0]}function FS(e=[]){let t=MS(e),i=Ac[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Cc("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Vh];return n&&n.length>0&&r.push("",Cc("Options",n)),r.push("",`Output:
|
|
206
|
+
${i.output}`),i.examples&&r.push("",Cc("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
207
|
+
`)}
|
|
208
|
+
`}}var VS=FS().usage;var VH=10*1024*1024,Y=class extends Error{};function Ot(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Y(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Er(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Y(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new Y(`${t} requires a value`);return e.splice(r,2),n}function Wh(e){if(e.length>0)throw new Y(`Unexpected argument: ${e[0]}`)}function zh(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new Y(`${t} is required`);return i}function qh(e,t){let i=_c.normalize(e),r=_c.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function qS(e){let t=_c.resolve(e),i=ue(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=ue(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!qh(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||qh(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function Jh(e){return e?qS(e):Ln(process.cwd())}async function Gh(e){let t=await $d({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function et(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
209
|
+
`}}function Uh(e,t){if(t instanceof Y)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof xa)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Ra)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof sa)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof cr)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Ca)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ca)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Pa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Sr)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Kh(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
210
|
+
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function ui(e,t){let i=await Ct({paths:e,state:t});return{...i?{children:i.children,readyChildren:i.readyChildren}:{},continuation:me(t,i)}}async function Yh(e,t){let i=zh(e,"change name"),r=Er(e,"--summary"),n=Er(e,"--runner-input"),a=Ot(e,"--confirmed"),o=Ot(e,"--return-to-build"),s=Ot(e,"--retry-verifier"),c=Ot(e,"--resolve-verifier-blocker");if([a,o,s,c].filter(Boolean).length>1)throw new Y("--confirmed, --return-to-build, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");Wh(e);let l=await Gh(t);if(!await yr(l.paths,i)){if(n)throw new Y("--runner-input is only valid for portable Native changes");if(!r)throw new Y("--summary is required");let p=await Eh({paths:l.paths,name:i});return et("next",{state:p,migration:{completed:!0,summary:r},continuation:me(p)})}if(n){if(r||a||o||s||c)throw new Y("--runner-input cannot be combined with --summary or Agent transition flags");let p=await Pc({paths:l.paths,name:i,preserveRunningExecution:!0}),m=p.state;if(p.action==="await-user"||p.action==="done"||p.reason!=="available")return et("next",{state:m,recovery:p,...await ui(l.paths,m)});if(m.phase==="build"){let g=await ka({paths:l.paths,state:m});if(g.drifted){let w=await Ec({paths:l.paths,name:i,reason:g.reason??"Native confirmed requirements changed"});return et("next",{state:w,...await ui(l.paths,w)})}if(await Ct({paths:l.paths,state:m}))throw new Y("Native parent Build advances child changes and does not accept a Builder handoff")}let h=await Ih(n,t),v=await jh({paths:l.paths,name:i,input:h,maxVerifyFailures:l.config.native.max_verify_failures});return et("next",{...v,...await ui(l.paths,v.state),coordination:q})}let f=await Pc({paths:l.paths,name:i}),d=f.state;if(!r)throw new Y("--summary is required");let u;if(a)if(d.phase==="shape")u=await ih({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-skill-coordinated-pass")u=await hh({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-verifier-unavailable")u=await ph({paths:l.paths,name:i,summary:r});else throw new Y("--confirmed is only valid in Shape, for an accepted Skill-coordinated pass, or for a user-accepted degraded verification fallback");else if(o)u=await Sa({paths:l.paths,name:i,reason:r});else if(s)u=await vh({paths:l.paths,name:i});else if(c)u=await mh({paths:l.paths,name:i});else{if(f.reason!=="available")return et("next",{state:d,recovery:f,...await ui(l.paths,d)});if(d.phase==="build"){let p=await ka({paths:l.paths,state:d});if(p.drifted)u=await Ec({paths:l.paths,name:i,reason:p.reason??"Native confirmed requirements changed"});else{let m=await Ct({paths:l.paths,state:d});if(m)if(m.allDone&&!(d.loop.stage==="repairing"&&d.verification_result==="fail"))u=await nh({paths:l.paths,name:i,summary:r});else return et("next",{state:d,children:m.children,readyChildren:m.readyChildren,continuation:me(d,m)})}}return u?et("next",{state:u,...await ui(l.paths,u)}):{command:"next",exitCode:65,data:{state:d,continuation:me(d)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return et("next",{state:u,...await ui(l.paths,u)})}function WS(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
211
|
+
`}}async function Xh(e,t,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{Ot(n,"--json"),s=Er(n,"--project-root");let f=[...n,...a],d=await Jh(s);c=await t(f,d)}catch(f){c=Uh(e,f)}let l=o?WS(c):Kh(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
181
212
|
`)?"":`
|
|
182
|
-
`)),l.exitCode}process.exitCode=await
|
|
213
|
+
`)),l.exitCode}process.exitCode=await Xh("next",Yh);
|