@rpamis/comet 0.4.3 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +372 -332
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +113 -97
- package/assets/skills/comet/scripts/comet-check.mjs +117 -104
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +59 -59
- package/assets/skills/comet/scripts/comet-guard.mjs +170 -157
- package/assets/skills/comet/scripts/comet-handoff.mjs +110 -97
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +110 -97
- package/assets/skills/comet/scripts/comet-hook-router.mjs +272 -153
- package/assets/skills/comet/scripts/comet-intent.mjs +31 -31
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +104 -91
- package/assets/skills/comet/scripts/comet-runtime.mjs +311 -296
- package/assets/skills/comet/scripts/comet-state.mjs +221 -207
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +25 -25
- package/assets/skills/comet-archive/SKILL.md +13 -9
- package/assets/skills/comet-build/SKILL.md +4 -6
- package/assets/skills/comet-classic/SKILL.md +1 -1
- package/assets/skills/comet-classic/reference/scripts.md +9 -1
- package/assets/skills/comet-design/SKILL.md +0 -2
- package/assets/skills/comet-hotfix/SKILL.md +1 -3
- package/assets/skills/comet-native/SKILL.md +8 -7
- package/assets/skills/comet-native/reference/artifacts.md +51 -7
- package/assets/skills/comet-native/reference/clarification.md +5 -5
- package/assets/skills/comet-native/reference/commands.md +15 -13
- package/assets/skills/comet-native/reference/recovery.md +3 -3
- package/assets/skills/comet-native/reference/workspace.md +10 -4
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +257 -169
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +238 -153
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +241 -124
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +189 -108
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +220 -139
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +245 -160
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +210 -129
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +284 -196
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +212 -128
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +207 -126
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +203 -118
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +208 -124
- package/assets/skills/comet-open/SKILL.md +0 -2
- package/assets/skills/comet-tweak/SKILL.md +1 -1
- package/assets/skills/comet-verify/SKILL.md +0 -2
- package/assets/skills-zh/comet-archive/SKILL.md +13 -9
- package/assets/skills-zh/comet-build/SKILL.md +4 -6
- package/assets/skills-zh/comet-classic/SKILL.md +1 -1
- package/assets/skills-zh/comet-classic/reference/scripts.md +9 -1
- package/assets/skills-zh/comet-design/SKILL.md +0 -2
- package/assets/skills-zh/comet-hotfix/SKILL.md +1 -3
- package/assets/skills-zh/comet-native/SKILL.md +8 -7
- package/assets/skills-zh/comet-native/reference/artifacts.md +51 -7
- package/assets/skills-zh/comet-native/reference/clarification.md +5 -5
- package/assets/skills-zh/comet-native/reference/commands.md +16 -10
- package/assets/skills-zh/comet-native/reference/recovery.md +3 -3
- package/assets/skills-zh/comet-native/reference/workspace.md +10 -4
- package/assets/skills-zh/comet-open/SKILL.md +0 -2
- package/assets/skills-zh/comet-tweak/SKILL.md +1 -1
- package/assets/skills-zh/comet-verify/SKILL.md +0 -2
- package/bin/comet-daemon-router.js +23 -7
- package/bin/fast-runtime-router.js +1 -1
- package/dist/app/cli/index.js +1 -0
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/daemon-server.d.ts.map +1 -1
- package/dist/app/commands/daemon-server.js +13 -2
- package/dist/app/commands/daemon-server.js.map +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +17 -10
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/i18n.d.ts +1 -1
- package/dist/app/commands/i18n.d.ts.map +1 -1
- package/dist/app/commands/i18n.js +4 -0
- package/dist/app/commands/i18n.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts +2 -0
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +64 -7
- package/dist/app/commands/project-knowledge.js.map +1 -1
- package/dist/app/commands/uninstall.d.ts +1 -0
- package/dist/app/commands/uninstall.d.ts.map +1 -1
- package/dist/app/commands/uninstall.js +65 -10
- package/dist/app/commands/uninstall.js.map +1 -1
- package/dist/domains/agent-learning/coordinator.d.ts +8 -1
- package/dist/domains/agent-learning/coordinator.d.ts.map +1 -1
- package/dist/domains/agent-learning/coordinator.js +58 -0
- package/dist/domains/agent-learning/coordinator.js.map +1 -1
- package/dist/domains/agent-learning/experience-journal.d.ts +21 -1
- package/dist/domains/agent-learning/experience-journal.d.ts.map +1 -1
- package/dist/domains/agent-learning/experience-journal.js +190 -11
- package/dist/domains/agent-learning/experience-journal.js.map +1 -1
- package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
- package/dist/domains/bundle/bundle-platform.js +6 -1
- package/dist/domains/bundle/bundle-platform.js.map +1 -1
- package/dist/domains/comet-classic/classic-archive-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-archive-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-archive-entry.js +5 -2
- package/dist/domains/comet-classic/classic-archive-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-archive.js +5 -1
- package/dist/domains/comet-classic/classic-archive.js.map +1 -1
- package/dist/domains/comet-classic/classic-branch-binding.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-branch-binding.js +5 -4
- package/dist/domains/comet-classic/classic-branch-binding.js.map +1 -1
- package/dist/domains/comet-classic/classic-check-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-check-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-check-entry.js +5 -2
- package/dist/domains/comet-classic/classic-check-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.js +68 -26
- package/dist/domains/comet-classic/classic-check-snapshot.js.map +1 -1
- package/dist/domains/comet-classic/classic-design-readiness.d.ts +1 -1
- package/dist/domains/comet-classic/classic-guard-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-guard-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-guard-entry.js +5 -2
- package/dist/domains/comet-classic/classic-guard-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-handoff-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-handoff-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-handoff-entry.js +5 -2
- package/dist/domains/comet-classic/classic-handoff-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-progress.d.ts +60 -2
- package/dist/domains/comet-classic/classic-progress.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-progress.js +199 -22
- package/dist/domains/comet-classic/classic-progress.js.map +1 -1
- package/dist/domains/comet-classic/classic-recovery.d.ts +20 -1
- package/dist/domains/comet-classic/classic-recovery.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-resume-probe.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-resume-probe.js +3 -2
- package/dist/domains/comet-classic/classic-resume-probe.js.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.d.ts +3 -1
- package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.js +34 -3
- package/dist/domains/comet-classic/classic-script-entry.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 +3 -2
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-state-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-entry.js +5 -2
- package/dist/domains/comet-classic/classic-state-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-store.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-store.js +67 -1
- package/dist/domains/comet-classic/classic-store.js.map +1 -1
- package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
- package/dist/domains/comet-entry/resume-probe.js +3 -2
- package/dist/domains/comet-entry/resume-probe.js.map +1 -1
- package/dist/domains/comet-native/native-acceptance.d.ts +5 -1
- package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
- package/dist/domains/comet-native/native-acceptance.js +13 -2
- 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 +167 -37
- package/dist/domains/comet-native/native-archive-command.js.map +1 -1
- package/dist/domains/comet-native/native-artifact-language.d.ts +10 -1
- package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifact-language.js +65 -12
- package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
- package/dist/domains/comet-native/native-artifacts.d.ts +10 -1
- package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifacts.js +130 -21
- package/dist/domains/comet-native/native-artifacts.js.map +1 -1
- package/dist/domains/comet-native/native-builder-acceptance-review.d.ts +16 -0
- package/dist/domains/comet-native/native-builder-acceptance-review.d.ts.map +1 -0
- package/dist/domains/comet-native/native-builder-acceptance-review.js +65 -0
- package/dist/domains/comet-native/native-builder-acceptance-review.js.map +1 -0
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +8 -4
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.d.ts +4 -2
- package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.js +37 -9
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
- package/dist/domains/comet-native/native-cli.d.ts +4 -1
- package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli.js +9 -5
- package/dist/domains/comet-native/native-cli.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 +144 -3
- package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
- package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -1
- package/dist/domains/comet-native/native-git-provenance.js +3 -2
- package/dist/domains/comet-native/native-git-provenance.js.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.js +57 -26
- package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
- package/dist/domains/comet-native/native-local-execution.d.ts +1 -0
- package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -1
- package/dist/domains/comet-native/native-local-execution.js +7 -0
- package/dist/domains/comet-native/native-local-execution.js.map +1 -1
- package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
- package/dist/domains/comet-native/native-lock.js +12 -0
- package/dist/domains/comet-native/native-lock.js.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts +2 -0
- package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.js +6 -0
- package/dist/domains/comet-native/native-loop-runtime.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 +57 -28
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-output-language.js +7 -0
- package/dist/domains/comet-native/native-output-language.js.map +1 -1
- package/dist/domains/comet-native/native-portable-acceptance.d.ts +2 -0
- package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-acceptance.js +11 -1
- package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -1
- package/dist/domains/comet-native/native-portable-archive.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-archive.js +3 -0
- package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.d.ts +14 -4
- package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.js +159 -60
- package/dist/domains/comet-native/native-portable-checks.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts +2 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +121 -39
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-requirements.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-requirements.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-requirements.js +68 -18
- package/dist/domains/comet-native/native-portable-requirements.js.map +1 -1
- package/dist/domains/comet-native/native-portable-shape-coordination.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-shape-coordination.js +18 -5
- package/dist/domains/comet-native/native-portable-shape-coordination.js.map +1 -1
- package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-state.js +12 -3
- package/dist/domains/comet-native/native-portable-state.js.map +1 -1
- package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-status.js +10 -4
- package/dist/domains/comet-native/native-portable-status.js.map +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts +2 -1
- package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-types.js.map +1 -1
- package/dist/domains/comet-native/native-portable-verification.d.ts +3 -0
- package/dist/domains/comet-native/native-portable-verification.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-verification.js +28 -35
- package/dist/domains/comet-native/native-portable-verification.js.map +1 -1
- package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts +2 -0
- package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-verifier-coordination.js +9 -0
- package/dist/domains/comet-native/native-portable-verifier-coordination.js.map +1 -1
- package/dist/domains/comet-native/native-runner-input-artifacts.d.ts +9 -0
- package/dist/domains/comet-native/native-runner-input-artifacts.d.ts.map +1 -0
- package/dist/domains/comet-native/native-runner-input-artifacts.js +102 -0
- package/dist/domains/comet-native/native-runner-input-artifacts.js.map +1 -0
- package/dist/domains/comet-native/native-runner-input.d.ts +90 -64
- package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
- package/dist/domains/comet-native/native-runner-input.js +107 -22
- package/dist/domains/comet-native/native-runner-input.js.map +1 -1
- package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-native/native-script-entry.js +9 -3
- package/dist/domains/comet-native/native-script-entry.js.map +1 -1
- package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-native/native-snapshot.js +7 -2
- package/dist/domains/comet-native/native-snapshot.js.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 +5 -4
- package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.d.ts +26 -0
- package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.js +520 -15
- package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
- package/dist/domains/comet-plugin/integration.d.ts +1 -0
- package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.js +20 -10
- package/dist/domains/comet-plugin/integration.js.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.d.ts +8 -2
- package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.js +18 -4
- package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
- package/dist/domains/dashboard/project-directory.d.ts +4 -0
- package/dist/domains/dashboard/project-directory.d.ts.map +1 -1
- package/dist/domains/dashboard/project-directory.js +30 -2
- package/dist/domains/dashboard/project-directory.js.map +1 -1
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +28 -3
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-qlcciI25.js → abnfDiagram-VCTEODGH-m9_t3fwH.js} +1 -1
- package/dist/domains/dashboard/web/assets/{arc-KVm4k9kp.js → arc-CDiwRrMg.js} +1 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-ypJOsR2Y.js +1 -0
- package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-C366RdBK.js → architectureDiagram-5GKGNRK7-Xwj-hlQB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-DAuTc2OO.js → blockDiagram-I7D4REHJ-Cme6qNK_.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-CFB0RZmL.js → c4Diagram-7LVT6UL2-Cxs1dU7y.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-BFTjR7Ng.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-DTV6lyGQ.js → chunk-4HAMMTFA-DBQykIWE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-DgJm4cEX.js → chunk-75Z2AOVW-Dh-E6TAx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-NAtcgGZr.js → chunk-DU6HZSFF-W3lPaoVP.js} +2 -2
- package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-BcFXHZMJ.js → chunk-F27PBJKO-dzf1fpYi.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-wNemar9b.js → chunk-GMAD6QVW-CeuSGVHV.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-BiVCDO9d.js → chunk-GVQU2GXP-BrGrIBgk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-D9GDj4b6.js → chunk-IMKFNOWR-DXiTC1Xo.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-DkPl5vac.js → chunk-L3NEJ4N5-DnyD3Ocj.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-RbbxGqtJ.js → chunk-OSK3NFVY-6vxhPm51.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-B9_X57eT.js → chunk-P2QGCYS3-DChNsVqO.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DE4bOH0D.js → chunk-POPQ4Y6H-RBgha6dE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Bo-W1iA1.js → chunk-PWAF6VOD-CayoKmnh.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BhLxs4rZ.js → chunk-SHT3W25Y-sOkLJZoB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-BCXfn8uF.js → chunk-SVP7TREG-j0QRwmsq.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-DqSBgE5L.js → chunk-TICWLB2K-D7Re_d_T.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-Dbkt1xEZ.js → chunk-XXDRQBXY-BFV70fKF.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-gDSLbV2K.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-gDSLbV2K.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-DrwNpMyX.js → cose-bilkent-JH36ORCC-k7gqx2Br.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-BbDlivxs.js → cynefin-OW5HDTMX-CWI6FZT8.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DmLmRN42.js → cynefinDiagram-5FMLGOSQ-D-O3RrOu.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-Cgm5DNgI.js → dagre-GXQ25YYZ-BR1jxWfn.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-Bnht1X2m.js → diagram-S7CK7UJ4-B6gXFYBj.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-LELTI4PR.js → diagram-UQ7AKVKN-BBW6aRk8.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-Do0fZuNG.js → diagram-VSXAHHWV-BC0CZeyH.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-B0rZTUwt.js → diagram-VX7I27RA-BmwBIkwS.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-wn8xCc_j.js → diagram-Z3DM3KII-DTZgX9SF.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dist-CYwDKy2m.js → dist-brXLwleg.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CMDOpP2T.js → ebnfDiagram-PWID7BFC-CsMXo0C6.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-C2d43bdq.js → erDiagram-RLTQ6QDP-DQ9ewX94.js} +1 -1
- package/dist/domains/dashboard/web/assets/{es-BzaOcXwu.js → es-CgcAhzLf.js} +1 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-Ll12Q19y.js +1 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Bf2-9XUn.js +1 -0
- package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-hTH7TzhY.js → ganttDiagram-EL5Y4UJY-DIFkXe6G.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-C3CCywb-.js → gitGraph-4MIJSDKK-BHY8ZnpE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-DW6jDckj.js → gitGraphDiagram-WWUBYQGX-cBn9dMzs.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-CTZPz_mx.js → index-C_6nf1Fw.js} +3 -3
- package/dist/domains/dashboard/web/assets/{index-CWNqBYyI.css → index-Gaxnq6Jd.css} +1 -1
- package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-Bg3eKis8.js → info-A6RAGUB7-DtUaS9jN.js} +1 -1
- package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-7zk6ytVJ.js → infoDiagram-27XIBGKW-CIl0e_EN.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CGDCTmCQ.js → ishikawaDiagram-5VMMS53U-DAdtPZ_c.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-C8_L_e8a.js → journeyDiagram-3NMN7TZE-CBokRgde.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-D5x6qTgM.js → kanban-definition-UXKFOSKX-DrqCYJ-7.js} +1 -1
- package/dist/domains/dashboard/web/assets/katex-D29apahB.js +257 -0
- package/dist/domains/dashboard/web/assets/{line-DC93oja4.js → line-BDlVqlh4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-81TNubkB.js → linear-DTAzui9x.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid-parser.core-D60d8uy9.js → mermaid-parser.core-CFw-xbYY.js} +3 -3
- package/dist/domains/dashboard/web/assets/{mermaid.core-l4Wgjz2Q.js → mermaid.core-Ck7fB8UD.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-Dfqu1201.js → mindmap-definition-YA3MSWOX-C7kb9KL9.js} +1 -1
- package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CsFZBhTs.js → packet-AYTQ26CC-P8Mtt0tp.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-myFMaA7n.js → pegDiagram-XKGWAZYB-DUDD9qv5.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-FMuCTNSk.js → pie-WAS4IAKB-dEmLxiDR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-CSR4B4Z1.js → pieDiagram-E7YTZNPT-BUssAcqk.js} +1 -1
- package/dist/domains/dashboard/web/assets/purify.es-Bvo9QlJ8.js +3 -0
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-BiE4kEeP.js → quadrantDiagram-AXDQQJYC-BzaAWdQL.js} +1 -1
- package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-BZ-n7JtG.js → radar-RG4KPBEZ-mqtvaz9w.js} +1 -1
- package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CWVtRfHu.js → railroad-74A4TZTK-7tTnGpoz.js} +1 -1
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CpJvyBJM.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-BJ5g77l6.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-BslCK-Gr.js +1 -0
- package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-CBj7v1de.js → railroadDiagram-O6MQD6OU-DM1AKXm0.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-DSDgb54n.js → requirementDiagram-BXWQKSXE--H5KiPSc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-1-oXLUAP.js → sankeyDiagram-P5KCCOFB-JweUq_u2.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DAF4nGs_.js → sequenceDiagram-WJ2MYXX4-pxb1iTGb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{src-CTWLVUqE.js → src-joFOxopw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-DzENBaJT.js → stateDiagram-D77RDMKH-CDu5crd8.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-wV5AqWaM.js +1 -0
- package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-CnxFUZJc.js → swimlanes-42K2YHIH-ioSqowJ4.js} +1 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DOPLn-V5.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-KtvPzpZM.js → timeline-definition-24CTP7MA-2YXSYkS3.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bdu3P9iY.js → treeView-Q6P3EWNA-DEGims38.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-DFnn23JR.js → treemap-WGGIJYW6-CJvBhTlR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-BjpviP26.js → vennDiagram-4TSXK5OY-CHdNWhBK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-CEo4a-j4.js → wardley-WFR3VGLG-CVO9PCjo.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-Bf54n6im.js → wardleyDiagram-VM6X3IG4-RToPmij6.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-CU-hI0Cm.js → xychartDiagram-S5SC5T6Z-DaWHnpHE.js} +1 -1
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/project-knowledge/host-review.d.ts +15 -2
- package/dist/domains/project-knowledge/host-review.d.ts.map +1 -1
- package/dist/domains/project-knowledge/host-review.js +65 -25
- package/dist/domains/project-knowledge/host-review.js.map +1 -1
- package/dist/domains/project-knowledge/index.d.ts +1 -0
- package/dist/domains/project-knowledge/index.d.ts.map +1 -1
- package/dist/domains/project-knowledge/index.js +1 -0
- package/dist/domains/project-knowledge/index.js.map +1 -1
- package/dist/domains/project-knowledge/learning.d.ts +2 -1
- package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
- package/dist/domains/project-knowledge/learning.js +6 -0
- package/dist/domains/project-knowledge/learning.js.map +1 -1
- package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
- package/dist/domains/project-knowledge/plugin.js +3 -1
- package/dist/domains/project-knowledge/plugin.js.map +1 -1
- package/dist/domains/skill/dsh-adapter.d.ts +5 -1
- package/dist/domains/skill/dsh-adapter.d.ts.map +1 -1
- package/dist/domains/skill/dsh-adapter.js +222 -87
- package/dist/domains/skill/dsh-adapter.js.map +1 -1
- package/dist/domains/skill/platform-inspect.d.ts +1 -0
- package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
- package/dist/domains/skill/platform-inspect.js +8 -4
- package/dist/domains/skill/platform-inspect.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +7 -7
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/workflow-contract/hook-target-scope.d.ts.map +1 -1
- package/dist/domains/workflow-contract/hook-target-scope.js +2 -1
- package/dist/domains/workflow-contract/hook-target-scope.js.map +1 -1
- package/dist/platform/fs/file-system.d.ts +2 -0
- package/dist/platform/fs/file-system.d.ts.map +1 -1
- package/dist/platform/fs/file-system.js +11 -0
- package/dist/platform/fs/file-system.js.map +1 -1
- package/dist/platform/install/dsh-profiles.d.ts +3 -0
- package/dist/platform/install/dsh-profiles.d.ts.map +1 -0
- package/dist/platform/install/dsh-profiles.js +40 -0
- package/dist/platform/install/dsh-profiles.js.map +1 -0
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +1 -0
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/install/project-registry.d.ts +7 -1
- package/dist/platform/install/project-registry.d.ts.map +1 -1
- package/dist/platform/install/project-registry.js +49 -5
- package/dist/platform/install/project-registry.js.map +1 -1
- package/dist/platform/paths/git-worktree-cache.d.ts +3 -0
- package/dist/platform/paths/git-worktree-cache.d.ts.map +1 -0
- package/dist/platform/paths/git-worktree-cache.js +109 -0
- package/dist/platform/paths/git-worktree-cache.js.map +1 -0
- package/dist/platform/paths/git-worktree.d.ts +6 -0
- package/dist/platform/paths/git-worktree.d.ts.map +1 -1
- package/dist/platform/paths/git-worktree.js +191 -30
- package/dist/platform/paths/git-worktree.js.map +1 -1
- package/dist/platform/paths/project-worktree-root.d.ts +3 -0
- package/dist/platform/paths/project-worktree-root.d.ts.map +1 -0
- package/dist/platform/paths/project-worktree-root.js +14 -0
- package/dist/platform/paths/project-worktree-root.js.map +1 -0
- package/dist/platform/process/comet-daemon.d.ts +3 -0
- package/dist/platform/process/comet-daemon.d.ts.map +1 -1
- package/dist/platform/process/comet-daemon.js +8 -6
- package/dist/platform/process/comet-daemon.js.map +1 -1
- package/dist/platform/process/external-command.d.ts +3 -0
- package/dist/platform/process/external-command.d.ts.map +1 -1
- package/dist/platform/process/external-command.js +69 -2
- package/dist/platform/process/external-command.js.map +1 -1
- package/dist/platform/process/git.d.ts.map +1 -1
- package/dist/platform/process/git.js +3 -4
- package/dist/platform/process/git.js.map +1 -1
- package/dist/platform/process/hook-adapter.d.ts +2 -0
- package/dist/platform/process/hook-adapter.d.ts.map +1 -1
- package/dist/platform/process/hook-adapter.js +45 -3
- package/dist/platform/process/hook-adapter.js.map +1 -1
- package/dist/platform/process/hook-read-cache.d.ts +2 -0
- package/dist/platform/process/hook-read-cache.d.ts.map +1 -1
- package/dist/platform/process/hook-read-cache.js +25 -13
- package/dist/platform/process/hook-read-cache.js.map +1 -1
- package/dist/platform/process/process-identity.d.ts.map +1 -1
- package/dist/platform/process/process-identity.js +18 -51
- package/dist/platform/process/process-identity.js.map +1 -1
- package/dist/platform/process/runtime-metrics.d.ts +10 -1
- package/dist/platform/process/runtime-metrics.d.ts.map +1 -1
- package/dist/platform/process/runtime-metrics.js +37 -2
- package/dist/platform/process/runtime-metrics.js.map +1 -1
- package/dist/platform/process/windows-process-broker.d.ts +1 -0
- package/dist/platform/process/windows-process-broker.d.ts.map +1 -1
- package/dist/platform/process/windows-process-broker.js +70 -11
- package/dist/platform/process/windows-process-broker.js.map +1 -1
- package/dist/platform/process/windows-process-identity.d.ts +6 -0
- package/dist/platform/process/windows-process-identity.d.ts.map +1 -0
- package/dist/platform/process/windows-process-identity.js +190 -0
- package/dist/platform/process/windows-process-identity.js.map +1 -0
- package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +11 -3
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +11 -3
- package/eval/local/tests/scaffold/test_task_resolution.py +6 -2
- package/package.json +14 -8
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-QeljAKq2.js +0 -1
- package/dist/domains/dashboard/web/assets/channel-_AqwP0KA.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-CRo4aB_7.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-CRo4aB_7.js +0 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-KYANo3DQ.js +0 -1
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-CSROlLuj.js +0 -1
- package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +0 -257
- package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +0 -3
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CkHwwI2i.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-8xzEHL6v.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-nSHBw0tH.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-CNw52Fkn.js +0 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-6TRvbqqI.js +0 -8
|
@@ -1,77 +1,77 @@
|
|
|
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 Vw=Object.create;var Js=Object.defineProperty;var qw=Object.getOwnPropertyDescriptor;var Ww=Object.getOwnPropertyNames;var zw=Object.getPrototypeOf,Gw=Object.prototype.hasOwnProperty;var aa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var S=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var N=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Kw=(e,t)=>{for(var r in t)Js(e,r,{get:t[r],enumerable:!0})},Jw=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ww(t))!Gw.call(e,i)&&i!==r&&Js(e,i,{get:()=>t[i],enumerable:!(n=qw(t,i))||n.enumerable});return e};var At=(e,t,r)=>(r=e!=null?Vw(zw(e)):{},Jw(t||!e||!e.__esModule?Js(r,"default",{value:e,enumerable:!0}):r,e));var A=N(Q=>{"use strict";var Us=Symbol.for("yaml.alias"),Md=Symbol.for("yaml.document"),oa=Symbol.for("yaml.map"),Fd=Symbol.for("yaml.pair"),Ys=Symbol.for("yaml.scalar"),sa=Symbol.for("yaml.seq"),pt=Symbol.for("yaml.node.type"),Uw=e=>!!e&&typeof e=="object"&&e[pt]===Us,Yw=e=>!!e&&typeof e=="object"&&e[pt]===Md,Xw=e=>!!e&&typeof e=="object"&&e[pt]===oa,Qw=e=>!!e&&typeof e=="object"&&e[pt]===Fd,Vd=e=>!!e&&typeof e=="object"&&e[pt]===Ys,Zw=e=>!!e&&typeof e=="object"&&e[pt]===sa;function qd(e){if(e&&typeof e=="object")switch(e[pt]){case oa:case sa:return!0}return!1}function ey(e){if(e&&typeof e=="object")switch(e[pt]){case Us:case oa:case Ys:case sa:return!0}return!1}var ty=e=>(Vd(e)||qd(e))&&!!e.anchor;Q.ALIAS=Us;Q.DOC=Md;Q.MAP=oa;Q.NODE_TYPE=pt;Q.PAIR=Fd;Q.SCALAR=Ys;Q.SEQ=sa;Q.hasAnchor=ty;Q.isAlias=Uw;Q.isCollection=qd;Q.isDocument=Yw;Q.isMap=Xw;Q.isNode=ey;Q.isPair=Qw;Q.isScalar=Vd;Q.isSeq=Zw});var Pn=N(Xs=>{"use strict";var z=A(),he=Symbol("break visit"),Wd=Symbol("skip children"),Qe=Symbol("remove node");function ca(e,t){let r=zd(t);z.isDocument(e)?jr(null,e.contents,r,Object.freeze([e]))===Qe&&(e.contents=null):jr(null,e,r,Object.freeze([]))}ca.BREAK=he;ca.SKIP=Wd;ca.REMOVE=Qe;function jr(e,t,r,n){let i=Gd(e,t,r,n);if(z.isNode(i)||z.isPair(i))return Kd(e,n,i),jr(e,i,r,n);if(typeof i!="symbol"){if(z.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=jr(a,t.items[a],r,n);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Qe&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){n=Object.freeze(n.concat(t));let a=jr("key",t.key,r,n);if(a===he)return he;a===Qe&&(t.key=null);let o=jr("value",t.value,r,n);if(o===he)return he;o===Qe&&(t.value=null)}}return i}async function la(e,t){let r=zd(t);z.isDocument(e)?await $r(null,e.contents,r,Object.freeze([e]))===Qe&&(e.contents=null):await $r(null,e,r,Object.freeze([]))}la.BREAK=he;la.SKIP=Wd;la.REMOVE=Qe;async function $r(e,t,r,n){let i=await Gd(e,t,r,n);if(z.isNode(i)||z.isPair(i))return Kd(e,n,i),$r(e,i,r,n);if(typeof i!="symbol"){if(z.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=await $r(a,t.items[a],r,n);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Qe&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){n=Object.freeze(n.concat(t));let a=await $r("key",t.key,r,n);if(a===he)return he;a===Qe&&(t.key=null);let o=await $r("value",t.value,r,n);if(o===he)return he;o===Qe&&(t.value=null)}}return i}function zd(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 Gd(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(z.isMap(t))return r.Map?.(e,t,n);if(z.isSeq(t))return r.Seq?.(e,t,n);if(z.isPair(t))return r.Pair?.(e,t,n);if(z.isScalar(t))return r.Scalar?.(e,t,n);if(z.isAlias(t))return r.Alias?.(e,t,n)}function Kd(e,t,r){let n=t[t.length-1];if(z.isCollection(n))n.items[e]=r;else if(z.isPair(n))e==="key"?n.key=r:n.value=r;else if(z.isDocument(n))n.contents=r;else{let i=z.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Xs.visit=ca;Xs.visitAsync=la});var Qs=N(Ud=>{"use strict";var Jd=A(),ry=Pn(),ny={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},iy=e=>e.replace(/[!,[\]{}]/g,t=>ny[t]),Rn=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}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,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+iy(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(t&&n.length>0&&Jd.isNode(t.contents)){let a={};ry.visit(t.contents,(o,s)=>{Jd.isNode(s)&&s.tag&&(a[s.tag]=!0)}),i=Object.keys(a)}else i=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
5
|
+
`)}};Rn.defaultYaml={explicit:!1,version:"1.2"};Rn.defaultTags={"!!":"tag:yaml.org,2002:"};Ud.Directives=Rn});var ua=N(_n=>{"use strict";var Yd=A(),ay=Pn();function oy(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Xd(e){let t=new Set;return ay.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function Qd(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function sy(e,t){let r=[],n=new Map,i=null;return{onAnchor:a=>{r.push(a),i??(i=Xd(e));let o=Qd(t,i);return i.add(o),o},setAnchors:()=>{for(let a of r){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Yd.isScalar(o.node)||Yd.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:n}}_n.anchorIsValid=oy;_n.anchorNames=Xd;_n.createNodeAnchors=sy;_n.findNewAnchor=Qd});var Zs=N(Zd=>{"use strict";function An(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,a=n.length;i<a;++i){let o=n[i],s=An(e,n,String(i),o);s===void 0?delete n[i]:s!==o&&(n[i]=s)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let a=n.get(i),o=An(e,n,i,a);o===void 0?n.delete(i):o!==a&&n.set(i,o)}else if(n instanceof Set)for(let i of Array.from(n)){let a=An(e,n,i,i);a===void 0?n.delete(i):a!==i&&(n.delete(i),n.add(a))}else for(let[i,a]of Object.entries(n)){let o=An(e,n,i,a);o===void 0?delete n[i]:o!==a&&(n[i]=o)}return e.call(t,r,n)}Zd.applyReviver=An});var It=N(tf=>{"use strict";var cy=A();function ef(e,t,r){if(Array.isArray(e))return e.map((n,i)=>ef(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!cy.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=a=>{n.res=a,delete r.onCreate};let i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}tf.toJS=ef});var da=N(nf=>{"use strict";var ly=Zs(),rf=A(),uy=It(),ec=class{constructor(t){Object.defineProperty(this,rf.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:r,maxAliasCount:n,onAnchor:i,reviver:a}={}){if(!rf.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=uy.toJS(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof a=="function"?ly.applyReviver(a,{"":s},"",s):s}};nf.NodeBase=ec});var In=N(af=>{"use strict";var dy=ua(),fy=Pn(),Or=A(),py=da(),hy=It(),tc=class extends py.NodeBase{constructor(t){super(Or.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],fy.visit(t,{Node:(a,o)=>{(Or.isAlias(o)||Or.hasAnchor(o))&&n.push(o)}}),r&&(r.aliasResolveCache=n));let i;for(let a of n){if(a===this)break;a.anchor===this.source&&(i=a)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:a}=r,o=this.resolve(i,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(hy.toJS(o,null,r),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=fa(i,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(dy.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`${i} `}return i}};function fa(e,t,r){if(Or.isAlias(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(Or.isCollection(t)){let n=0;for(let i of t.items){let a=fa(e,i,r);a>n&&(n=a)}return n}else if(Or.isPair(t)){let n=fa(e,t.key,r),i=fa(e,t.value,r);return Math.max(n,i)}return 1}af.Alias=tc});var V=N(rc=>{"use strict";var my=A(),vy=da(),gy=It(),wy=e=>!e||typeof e!="function"&&typeof e!="object",Tt=class extends vy.NodeBase{constructor(t){super(my.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:gy.toJS(this.value,t,r)}toString(){return String(this.value)}};Tt.BLOCK_FOLDED="BLOCK_FOLDED";Tt.BLOCK_LITERAL="BLOCK_LITERAL";Tt.PLAIN="PLAIN";Tt.QUOTE_DOUBLE="QUOTE_DOUBLE";Tt.QUOTE_SINGLE="QUOTE_SINGLE";rc.Scalar=Tt;rc.isScalarValue=wy});var Tn=N(sf=>{"use strict";var yy=In(),ir=A(),of=V(),by="tag:yaml.org,2002:";function Ny(e,t,r){if(t){let n=r.filter(a=>a.tag===t),i=n.find(a=>!a.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function ky(e,t,r){if(ir.isDocument(e)&&(e=e.contents),ir.isNode(e))return e;if(ir.isPair(e)){let d=r.schema[ir.MAP].createNode?.(r.schema,null,r);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:n,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new yy.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=by+t.slice(2));let l=Ny(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new of.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[ir.MAP]:Symbol.iterator in Object(e)?o[ir.SEQ]:o[ir.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new of.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}sf.createNode=ky});var ha=N(pa=>{"use strict";var Sy=Tn(),Ze=A(),Ey=da();function nc(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let a=t[i];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return Sy.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var cf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ic=class extends Ey.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(n=>Ze.isNode(n)||Ze.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(cf(t))this.add(r);else{let[n,...i]=t,a=this.get(n,!0);if(Ze.isCollection(a))a.addIn(i,r);else if(a===void 0&&this.schema)this.set(n,nc(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(Ze.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,a=this.get(n,!0);return i.length===0?!r&&Ze.isScalar(a)?a.value:a:Ze.isCollection(a)?a.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ze.isPair(r))return!1;let n=r.value;return n==null||t&&Ze.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let i=this.get(r,!0);return Ze.isCollection(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let a=this.get(n,!0);if(Ze.isCollection(a))a.setIn(i,r);else if(a===void 0&&this.schema)this.set(n,nc(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};pa.Collection=ic;pa.collectionFromPath=nc;pa.isEmptyPath=cf});var jn=N(ma=>{"use strict";var xy=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ac(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Cy=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?ac(r,t):r.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)r===
|
|
8
|
+
`+ac(r,t):(e.endsWith(" ")?"":" ")+r;ma.indentComment=ac;ma.lineComment=Cy;ma.stringifyComment=xy});var uf=N($n=>{"use strict";var Py="flow",oc="block",va="quoted";function Ry(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof n=="number"&&(n>i-Math.max(2,a)?l.push(0):d=i-n);let f,p,m=!1,h=-1,v=-1,w=-1;r===oc&&(h=lf(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===va&&k==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(k===`
|
|
9
|
+
`)r===oc&&(h=lf(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
|
|
10
10
|
`&&p!==" "){let E=e[h+1];E&&E!==" "&&E!==`
|
|
11
|
-
`&&E!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===
|
|
12
|
-
${t}${e.slice(0,x)}`:(r===
|
|
13
|
-
${t}${e.slice(E+1,x)}`)}return y}function
|
|
14
|
-
`);
|
|
15
|
-
`){if(a-o>
|
|
11
|
+
`&&E!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===va){for(;p===" "||p===" ";)p=k,k=e[h+=1],m=!0;let E=h>w+1?h-2:v-1;if(u[E])return e;l.push(E),u[E]=!0,d=E+c,f=void 0}else m=!0}p=k}if(m&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let E=l[k],x=l[k+1]||e.length;E===0?y=`
|
|
12
|
+
${t}${e.slice(0,x)}`:(r===va&&u[E]&&(y+=`${e[E]}\\`),y+=`
|
|
13
|
+
${t}${e.slice(E+1,x)}`)}return y}function lf(e,t,r){let n=t,i=t+1,a=e[i];for(;a===" "||a===" ";)if(t<i+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);n=t,i=t+1,a=e[i]}return n}$n.FOLD_BLOCK=oc;$n.FOLD_FLOW=Py;$n.FOLD_QUOTED=va;$n.foldFlowLines=Ry});var Hn=N(df=>{"use strict";var De=V(),jt=uf(),wa=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ya=e=>/^(%|---|\.\.\.)/m.test(e);function _y(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let a=0,o=0;a<i;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>n)return!0;if(o=a+1,i-o<=n)return!1}return!0}function On(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(ya(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){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:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(o+=r.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${r}`)+"'";return t.implicitKey?
|
|
18
|
+
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,n?o:jt.foldFlowLines(o,a,jt.FOLD_QUOTED,wa(t,!1))}function sc(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return On(e,t);let r=t.indent||(ya(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?n:jt.foldFlowLines(n,r,jt.FOLD_FLOW,wa(t,!1))}function Hr(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=On;else{let i=e.includes('"'),a=e.includes("'");i&&!a?n=sc:a&&!i?n=On:n=r?sc:On}return n(e,t)}var cc;try{cc=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{cc=/\n+(?!\n|$)/g}function ga({comment:e,type:t,value:r},n,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return Hr(r,n);let l=n.indent||(n.forceBlockIndent||ya(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===De.Scalar.BLOCK_FOLDED?!1:t===De.Scalar.BLOCK_LITERAL?!0:!_y(r,c,l.length);if(!r)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=r.length;f>0;--f){let x=r[f-1];if(x!==`
|
|
26
26
|
`&&x!==" "&&x!==" ")break}let p=r.substring(f),m=p.indexOf(`
|
|
27
27
|
`);m===-1?d="-":r===p||m!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
|
|
28
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
29
|
-
`)w=v;else break}let y=r.substring(0,w<v?w+1:v);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let E=(h?l?"2":"1":"")+d;if(e&&(E+=" "+s(e.replace(/ ?[\r\n]+/g," ")),
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,
|
|
31
|
-
${l}${
|
|
32
|
-
${l}${y}${r}${p}`}function
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(f)||p?.some(f))return
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(v=`${v}:`,f&&(v+=
|
|
39
|
-
`:"",y){let
|
|
40
|
-
${
|
|
28
|
+
`&&(p=p.slice(0,-1)),p=p.replace(cc,`$&${l}`));let h=!1,v,w=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
|
|
29
|
+
`)w=v;else break}let y=r.substring(0,w<v?w+1:v);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let E=(h?l?"2":"1":"")+d;if(e&&(E+=" "+s(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let x=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,_=wa(n,!0);o!=="folded"&&t!==De.Scalar.BLOCK_FOLDED&&(_.onOverflow=()=>{g=!0});let b=jt.foldFlowLines(`${y}${x}${p}`,l,jt.FOLD_BLOCK,_);if(!g)return`>${E}
|
|
31
|
+
${l}${b}`}return r=r.replace(/\n+/g,`$&${l}`),`|${E}
|
|
32
|
+
${l}${y}${r}${p}`}function Ay(e,t,r,n){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return Hr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?Hr(a,t):ga(e,t,r,n);if(!s&&!u&&i!==De.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return ga(e,t,r,n);if(ya(a)){if(c==="")return t.forceBlockIndent=!0,ga(e,t,r,n);if(s&&c===l)return Hr(a,t)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(f)||p?.some(f))return Hr(a,t)}return s?d:jt.foldFlowLines(d,c,jt.FOLD_FLOW,wa(t,!1))}function Iy(e,t,r,n){let{implicitKey:i,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==De.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=De.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case De.Scalar.BLOCK_FOLDED:case De.Scalar.BLOCK_LITERAL:return i||a?Hr(o.value,t):ga(o,t,r,n);case De.Scalar.QUOTE_DOUBLE:return On(o.value,t);case De.Scalar.QUOTE_SINGLE:return sc(o.value,t);case De.Scalar.PLAIN:return Ay(o,t,r,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}df.stringifyString=Iy});var Dn=N(lc=>{"use strict";var Ty=ua(),$t=A(),jy=jn(),$y=Hn();function Oy(e,t){let r=Object.assign({blockQuote:!0,commentString:jy.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function Hy(e,t){if(t.tag){let i=e.filter(a=>a.tag===t.tag);if(i.length>0)return i.find(a=>a.format===t.format)??i[0]}let r,n;if($t.isScalar(t)){n=t.value;let i=e.filter(a=>a.identify?.(n));if(i.length>1){let a=i.filter(o=>o.test);a.length>0&&(i=a)}r=i.find(a=>a.format===t.format)??i.find(a=>!a.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function Dy(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],a=($t.isScalar(e)||$t.isCollection(e))&&e.anchor;a&&Ty.anchorIsValid(a)&&(r.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Ly(e,t,r,n){if($t.isPair(e))return e.toString(t,r,n);if($t.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=$t.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=Hy(t.doc.schema.tags,a));let o=Dy(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify=="function"?i.stringify(a,t,r,n):$t.isScalar(a)?$y.stringifyString(a,t,r,n):a.toString(t,r,n);return o?$t.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}lc.createStringifyContext=Oy;lc.stringify=Ly});var mf=N(hf=>{"use strict";var ht=A(),ff=V(),pf=Dn(),Ln=jn();function By({key:e,value:t},r,n,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=ht.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ht.isCollection(e)||!ht.isNode(e)&&typeof e=="object"){let _="With simple keys, collection cannot be used as a key value";throw new Error(_)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||ht.isCollection(e)||(ht.isScalar(e)?e.type===ff.Scalar.BLOCK_FOLDED||e.type===ff.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,v=pf.stringify(e,r,()=>m=!0,()=>h=!0);if(!p&&!r.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(r.inFlow){if(a||t==null)return m&&n&&n(),v===""?"?":p?`? ${v}`:v}else if(a&&!d||t==null&&p)return v=`? ${v}`,f&&!m?v+=Ln.lineComment(v,r.indent,l(f)):h&&i&&i(),v;m&&(f=null),p?(f&&(v+=Ln.lineComment(v,r.indent,l(f))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,f&&(v+=Ln.lineComment(v,r.indent,l(f))));let w,y,k;ht.isNode(t)?(w=!!t.spaceBefore,y=t.commentBefore,k=t.comment):(w=!1,y=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&ht.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&ht.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let E=!1,x=pf.stringify(t,r,()=>E=!0,()=>h=!0),g=" ";if(f||w||y){if(g=w?`
|
|
39
|
+
`:"",y){let _=l(y);g+=`
|
|
40
|
+
${Ln.indentComment(_,r.indent)}`}x===""&&!r.inFlow?g===`
|
|
41
41
|
`&&k&&(g=`
|
|
42
42
|
|
|
43
43
|
`):g+=`
|
|
44
|
-
${r.indent}`}else if(!p&&
|
|
45
|
-
`),
|
|
44
|
+
${r.indent}`}else if(!p&&ht.isCollection(t)){let _=x[0],b=x.indexOf(`
|
|
45
|
+
`),T=b!==-1,ie=r.inFlow??t.flow??t.items.length===0;if(T||!ie){let Tr=!1;if(T&&(_==="&"||_==="!")){let W=x.indexOf(" ");_==="&"&&W!==-1&&W<b&&x[W+1]==="!"&&(W=x.indexOf(" ",W+1)),(W===-1||b<W)&&(Tr=!0)}Tr||(g=`
|
|
46
46
|
${r.indent}`)}}else(x===""||x[0]===`
|
|
47
|
-
`)&&(g="");return v+=g+x,r.inFlow?E&&
|
|
47
|
+
`)&&(g="");return v+=g+x,r.inFlow?E&&n&&n():k&&!E?v+=Ln.lineComment(v,r.indent,l(k)):h&&i&&i(),v}hf.stringifyPair=By});var dc=N(uc=>{"use strict";var vf=aa("process");function My(e,...t){e==="debug"&&console.log(...t)}function Fy(e,t){(e==="debug"||e==="warn")&&(typeof vf.emitWarning=="function"?vf.emitWarning(t):console.warn(t))}uc.debug=My;uc.warn=Fy});var Ea=N(Sa=>{"use strict";var ka=A(),gf=V(),ba="<<",Na={identify:e=>e===ba||typeof e=="symbol"&&e.description===ba,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new gf.Scalar(Symbol(ba)),{addToJSMap:wf}),stringify:()=>ba},Vy=(e,t)=>(Na.identify(t)||ka.isScalar(t)&&(!t.type||t.type===gf.Scalar.PLAIN)&&Na.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Na.tag&&r.default);function wf(e,t,r){let n=yf(e,r);if(ka.isSeq(n))for(let i of n.items)fc(e,t,i);else if(Array.isArray(n))for(let i of n)fc(e,t,i);else fc(e,t,n)}function fc(e,t,r){let n=yf(e,r);if(!ka.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,e,Map);for(let[a,o]of i)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function yf(e,t){return e&&ka.isAlias(t)?t.resolve(e.doc,e):t}Sa.addMergeToJSMap=wf;Sa.isMergeKey=Vy;Sa.merge=Na});var hc=N(kf=>{"use strict";var qy=dc(),bf=Ea(),Wy=Dn(),Nf=A(),pc=It();function zy(e,t,{key:r,value:n}){if(Nf.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(bf.isMergeKey(e,r))bf.addMergeToJSMap(e,t,n);else{let i=pc.toJS(r,"",e);if(t instanceof Map)t.set(i,pc.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let a=Gy(r,i,e),o=pc.toJS(n,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Gy(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Nf.isNode(e)&&r?.doc){let n=Wy.createStringifyContext(r.doc,{});n.anchors=new Set;for(let a of r.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let a=JSON.stringify(i);a.length>40&&(a=a.substring(0,36)+'..."'),qy.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}kf.addPairToJSMap=zy});var Ot=N(mc=>{"use strict";var Sf=Tn(),Ky=mf(),Jy=hc(),xa=A();function Uy(e,t,r){let n=Sf.createNode(e,void 0,r),i=Sf.createNode(t,void 0,r);return new Ca(n,i)}var Ca=class e{constructor(t,r=null){Object.defineProperty(this,xa.NODE_TYPE,{value:xa.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return xa.isNode(r)&&(r=r.clone(t)),xa.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return Jy.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?Ky.stringifyPair(this,t,r,n):JSON.stringify(this)}};mc.Pair=Ca;mc.createPair=Uy});var vc=N(xf=>{"use strict";var ar=A(),Ef=Dn(),Pa=jn();function Yy(e,t,r){return(t.inFlow??e.flow?Qy:Xy)(e,t,r)}function Xy({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(ar.isNode(h))!d&&h.spaceBefore&&f.push(""),Ra(r,f,h.commentBefore,d),h.comment&&(v=h.comment);else if(ar.isPair(h)){let y=ar.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),Ra(r,f,y.commentBefore,d))}d=!1;let w=Ef.stringify(h,u,()=>v=null,()=>d=!0);v&&(w+=Pa.lineComment(w,a,l(v))),d&&v&&(d=!1),f.push(n+w)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
49
|
`}}return e?(p+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),m<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,k)=>y+k.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),v&&(w+=
|
|
52
|
-
${a}${
|
|
50
|
+
`+Pa.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function Qy({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;n+=a;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(ar.isNode(h))h.spaceBefore&&d.push(""),Ra(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(ar.isPair(h)){let y=ar.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Ra(t,d,y.commentBefore,!1),y.comment&&(l=!0));let k=ar.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(v=y.comment)}v&&(l=!0);let w=Ef.stringify(h,c,()=>v=null);l||(l=d.length>u||w.includes(`
|
|
51
|
+
`)),m<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,k)=>y+k.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),v&&(w+=Pa.lineComment(w,n,s(v))),d.push(w),u=d.length}let{start:f,end:p}=r;if(d.length===0)return f+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=f;for(let h of d)m+=h?`
|
|
52
|
+
${a}${i}${h}`:`
|
|
53
53
|
`;return`${m}
|
|
54
|
-
${
|
|
55
|
-
`:" ")}return
|
|
56
|
-
${
|
|
57
|
-
${a.comment}`:i.comment}i=n}e.items[r]=aa.isPair(i)?i:new Ws.Pair(i)}}else t("Expected a sequence for this tag");return e}function zd(e,t,r){let{replacer:i}=r,n=new fy.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 i=="function"&&(o=i.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(Ws.createPair(s,c,r))}return n}var py={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Wd,createNode:zd};oa.createPairs=zd;oa.pairs=py;oa.resolvePairs=Wd});var Gs=b(Ks=>{"use strict";var Kd=_(),zs=bt(),Ni=Pt(),hy=Rt(),Gd=sa(),Jt=class e extends hy.YAMLSeq{constructor(){super(),this.add=Ni.YAMLMap.prototype.add.bind(this),this.delete=Ni.YAMLMap.prototype.delete.bind(this),this.get=Ni.YAMLMap.prototype.get.bind(this),this.has=Ni.YAMLMap.prototype.has.bind(this),this.set=Ni.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Kd.isPair(n)?(a=zs.toJS(n.key,"",r),o=zs.toJS(n.value,a,r)):a=zs.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Gd.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Jt.tag="tag:yaml.org,2002:omap";var my={collection:"seq",identify:e=>e instanceof Map,nodeClass:Jt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Gd.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Kd.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Jt,r)},createNode:(e,t,r)=>Jt.from(e,t,r)};Ks.YAMLOMap=Jt;Ks.omap=my});var Qd=b(Js=>{"use strict";var Jd=M();function Ud({value:e,source:t},r){return t&&(e?Yd:Xd).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Yd={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Jd.Scalar(!0),stringify:Ud},Xd={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Jd.Scalar(!1),stringify:Ud};Js.falseTag=Xd;Js.trueTag=Yd});var Zd=b(ca=>{"use strict";var vy=M(),Us=kr(),gy={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:Us.stringifyNumber},wy={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():Us.stringifyNumber(e)}},yy={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 vy.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Us.stringifyNumber};ca.float=yy;ca.floatExp=wy;ca.floatNaN=gy});var tf=b(ki=>{"use strict";var ef=kr(),bi=e=>typeof e=="bigint"||Number.isInteger(e);function la(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){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,r);return n==="-"?-1*a:a}function Ys(e,t,r){let{value:i}=e;if(bi(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return ef.stringifyNumber(e)}var Ny={identify:bi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>la(e,2,2,r),stringify:e=>Ys(e,2,"0b")},by={identify:bi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>la(e,1,8,r),stringify:e=>Ys(e,8,"0")},ky={identify:bi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>la(e,0,10,r),stringify:ef.stringifyNumber},Sy={identify:bi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>la(e,2,16,r),stringify:e=>Ys(e,16,"0x")};ki.int=ky;ki.intBin=Ny;ki.intHex=Sy;ki.intOct=by});var Qs=b(Xs=>{"use strict";var fa=_(),ua=xt(),da=Pt(),Ut=class e extends da.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;fa.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new ua.Pair(t.key,null):r=new ua.Pair(t,null),da.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=da.findPair(this.items,t);return!r&&fa.isPair(i)?fa.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=da.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new ua.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(ua.createPair(o,null,i));return a}};Ut.tag="tag:yaml.org,2002:set";var Ey={collection:"map",identify:e=>e instanceof Set,nodeClass:Ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Ut.from(e,t,r),resolve(e,t){if(fa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ut,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Xs.YAMLSet=Ut;Xs.set=Ey});var ec=b(pa=>{"use strict";var xy=kr();function Zs(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function rf(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return xy.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(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))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Cy={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:r})=>Zs(e,r),stringify:rf},Py={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=>Zs(e,!1),stringify:rf},nf={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(nf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Zs(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$/,"")??""};pa.floatTime=Py;pa.intTime=Cy;pa.timestamp=nf});var sf=b(of=>{"use strict";var Ry=Nr(),_y=ea(),Ay=br(),Iy=wi(),Ty=qs(),af=Qd(),tc=Zd(),ha=tf(),jy=Kn(),$y=Gs(),Oy=sa(),Hy=Qs(),rc=ec(),Dy=[Ry.map,Ay.seq,Iy.string,_y.nullTag,af.trueTag,af.falseTag,ha.intBin,ha.intOct,ha.int,ha.intHex,tc.floatNaN,tc.floatExp,tc.float,Ty.binary,jy.merge,$y.omap,Oy.pairs,Hy.set,rc.intTime,rc.floatTime,rc.timestamp];of.schema=Dy});var gf=b(ac=>{"use strict";var df=Nr(),Ly=ea(),ff=br(),By=wi(),My=Os(),ic=Ds(),nc=Bs(),Fy=Bd(),Vy=Vd(),pf=qs(),Si=Kn(),hf=Gs(),mf=sa(),cf=sf(),vf=Qs(),ma=ec(),lf=new Map([["core",Fy.schema],["failsafe",[df.map,ff.seq,By.string]],["json",Vy.schema],["yaml11",cf.schema],["yaml-1.1",cf.schema]]),uf={binary:pf.binary,bool:My.boolTag,float:ic.float,floatExp:ic.floatExp,floatNaN:ic.floatNaN,floatTime:ma.floatTime,int:nc.int,intHex:nc.intHex,intOct:nc.intOct,intTime:ma.intTime,map:df.map,merge:Si.merge,null:Ly.nullTag,omap:hf.omap,pairs:mf.pairs,seq:ff.seq,set:vf.set,timestamp:ma.timestamp},qy={"tag:yaml.org,2002:binary":pf.binary,"tag:yaml.org,2002:merge":Si.merge,"tag:yaml.org,2002:omap":hf.omap,"tag:yaml.org,2002:pairs":mf.pairs,"tag:yaml.org,2002:set":vf.set,"tag:yaml.org,2002:timestamp":ma.timestamp};function Wy(e,t,r){let i=lf.get(t);if(i&&!e)return r&&!i.includes(Si.merge)?i.concat(Si.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(lf.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 r&&(n=n.concat(Si.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?uf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(uf).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},[])}ac.coreKnownTags=qy;ac.getTags=Wy});var cc=b(wf=>{"use strict";var oc=_(),zy=Nr(),Ky=br(),Gy=wi(),va=gf(),Jy=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,sc=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?va.getTags(t,"compat"):t?va.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?va.coreKnownTags:{},this.tags=va.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,oc.MAP,{value:zy.map}),Object.defineProperty(this,oc.SCALAR,{value:Gy.string}),Object.defineProperty(this,oc.SEQ,{value:Ky.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Jy:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};wf.Schema=sc});var Nf=b(yf=>{"use strict";var Uy=_(),lc=mi(),Ei=di();function Yy(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=lc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Ei.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Uy.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Ei.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=lc.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ei.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(lc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(r.push("..."),r.push(
|
|
54
|
+
${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Ra({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let a=Pa.indentComment(t(n),e);r.push(a.trimStart())}}xf.stringifyCollection=Yy});var Dt=N(wc=>{"use strict";var Zy=vc(),eb=hc(),tb=ha(),Ht=A(),_a=Ot(),rb=V();function Bn(e,t){let r=Ht.isScalar(t)?t.value:t;for(let n of e)if(Ht.isPair(n)&&(n.key===t||n.key===r||Ht.isScalar(n.key)&&n.key.value===r))return n}var gc=class extends tb.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ht.MAP,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:a}=n,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||i)&&o.items.push(_a.createPair(c,l,n))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let n;Ht.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new _a.Pair(t,t?.value):n=new _a.Pair(t.key,t.value);let i=Bn(this.items,n.key),a=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Ht.isScalar(i.value)&&rb.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(t){let r=Bn(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=Bn(this.items,t)?.value;return(!r&&Ht.isScalar(i)?i.value:i)??void 0}has(t){return!!Bn(this.items,t)}set(t,r){this.add(new _a.Pair(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let a of this.items)eb.addPairToJSMap(r,i,a);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Ht.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Zy.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};wc.YAMLMap=gc;wc.findPair=Bn});var Dr=N(Pf=>{"use strict";var nb=A(),Cf=Dt(),ib={collection:"map",default:!0,nodeClass:Cf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return nb.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Cf.YAMLMap.from(e,t,r)};Pf.map=ib});var Lt=N(Rf=>{"use strict";var ab=Tn(),ob=vc(),sb=ha(),Ia=A(),cb=V(),lb=It(),yc=class extends sb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ia.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Aa(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=Aa(t);if(typeof n!="number")return;let i=this.items[n];return!r&&Ia.isScalar(i)?i.value:i}has(t){let r=Aa(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=Aa(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];Ia.isScalar(i)&&cb.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let a of this.items)n.push(lb.toJS(a,String(i++),r));return n}toString(t,r,n){return t?ob.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){let{replacer:i}=n,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof i=="function"){let c=r instanceof Set?s:String(o++);s=i.call(r,c,s)}a.items.push(ab.createNode(s,void 0,n))}}return a}};function Aa(e){let t=Ia.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Rf.YAMLSeq=yc});var Lr=N(Af=>{"use strict";var ub=A(),_f=Lt(),db={collection:"seq",default:!0,nodeClass:_f.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return ub.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>_f.YAMLSeq.from(e,t,r)};Af.seq=db});var Mn=N(If=>{"use strict";var fb=Hn(),pb={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,n){return t=Object.assign({actualString:!0},t),fb.stringifyString(e,t,r,n)}};If.string=pb});var Ta=N($f=>{"use strict";var Tf=V(),jf={identify:e=>e==null,createNode:()=>new Tf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Tf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&jf.test.test(e)?e:t.options.nullStr};$f.nullTag=jf});var bc=N(Hf=>{"use strict";var hb=V(),Of={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new hb.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Of.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};Hf.boolTag=Of});var Br=N(Df=>{"use strict";function mb({format:e,minFractionDigits:t,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="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}Df.stringifyNumber=mb});var kc=N(ja=>{"use strict";var vb=V(),Nc=Br(),gb={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:Nc.stringifyNumber},wb={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():Nc.stringifyNumber(e)}},yb={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 vb.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Nc.stringifyNumber};ja.float=yb;ja.floatExp=wb;ja.floatNaN=gb});var Ec=N(Oa=>{"use strict";var Lf=Br(),$a=e=>typeof e=="bigint"||Number.isInteger(e),Sc=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function Bf(e,t,r){let{value:n}=e;return $a(n)&&n>=0?r+n.toString(t):Lf.stringifyNumber(e)}var bb={identify:e=>$a(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Sc(e,2,8,r),stringify:e=>Bf(e,8,"0o")},Nb={identify:$a,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Sc(e,0,10,r),stringify:Lf.stringifyNumber},kb={identify:e=>$a(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Sc(e,2,16,r),stringify:e=>Bf(e,16,"0x")};Oa.int=Nb;Oa.intHex=kb;Oa.intOct=bb});var Ff=N(Mf=>{"use strict";var Sb=Dr(),Eb=Ta(),xb=Lr(),Cb=Mn(),Pb=bc(),xc=kc(),Cc=Ec(),Rb=[Sb.map,xb.seq,Cb.string,Eb.nullTag,Pb.boolTag,Cc.intOct,Cc.int,Cc.intHex,xc.floatNaN,xc.floatExp,xc.float];Mf.schema=Rb});var Wf=N(qf=>{"use strict";var _b=V(),Ab=Dr(),Ib=Lr();function Vf(e){return typeof e=="bigint"||Number.isInteger(e)}var Ha=({value:e})=>JSON.stringify(e),Tb=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ha},{identify:e=>e==null,createNode:()=>new _b.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ha},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ha},{identify:Vf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Vf(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:Ha}],jb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},$b=[Ab.map,Ib.seq].concat(Tb,jb);qf.schema=$b});var Rc=N(zf=>{"use strict";var Fn=aa("buffer"),Pc=V(),Ob=Hn(),Hb={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Fn.Buffer=="function")return Fn.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},n,i,a){if(!r)return"";let o=r,s;if(typeof Fn.Buffer=="function")s=o instanceof Fn.Buffer?o.toString("base64"):Fn.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=Pc.Scalar.BLOCK_LITERAL),t!==Pc.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===Pc.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return Ob.stringifyString({comment:e,type:t,value:s},n,i,a)}};zf.binary=Hb});var Ba=N(La=>{"use strict";var Da=A(),_c=Ot(),Db=V(),Lb=Lt();function Gf(e,t){if(Da.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!Da.isPair(n)){if(Da.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new _c.Pair(new Db.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
|
|
56
|
+
${i.key.commentBefore}`:n.commentBefore),n.comment){let a=i.value??i.key;a.comment=a.comment?`${n.comment}
|
|
57
|
+
${a.comment}`:n.comment}n=i}e.items[r]=Da.isPair(n)?n:new _c.Pair(n)}}else t("Expected a sequence for this tag");return e}function Kf(e,t,r){let{replacer:n}=r,i=new Lb.YAMLSeq(e);i.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;i.items.push(_c.createPair(s,c,r))}return i}var Bb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Gf,createNode:Kf};La.createPairs=Kf;La.pairs=Bb;La.resolvePairs=Gf});var Tc=N(Ic=>{"use strict";var Jf=A(),Ac=It(),Vn=Dt(),Mb=Lt(),Uf=Ba(),or=class e extends Mb.YAMLSeq{constructor(){super(),this.add=Vn.YAMLMap.prototype.add.bind(this),this.delete=Vn.YAMLMap.prototype.delete.bind(this),this.get=Vn.YAMLMap.prototype.get.bind(this),this.has=Vn.YAMLMap.prototype.has.bind(this),this.set=Vn.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let a,o;if(Jf.isPair(i)?(a=Ac.toJS(i.key,"",r),o=Ac.toJS(i.value,a,r)):a=Ac.toJS(i,"",r),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(t,r,n){let i=Uf.createPairs(t,r,n),a=new this;return a.items=i.items,a}};or.tag="tag:yaml.org,2002:omap";var Fb={collection:"seq",identify:e=>e instanceof Map,nodeClass:or,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Uf.resolvePairs(e,t),n=[];for(let{key:i}of r.items)Jf.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new or,r)},createNode:(e,t,r)=>or.from(e,t,r)};Ic.YAMLOMap=or;Ic.omap=Fb});var ep=N(jc=>{"use strict";var Yf=V();function Xf({value:e,source:t},r){return t&&(e?Qf:Zf).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Qf={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Yf.Scalar(!0),stringify:Xf},Zf={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Yf.Scalar(!1),stringify:Xf};jc.falseTag=Zf;jc.trueTag=Qf});var tp=N(Ma=>{"use strict";var Vb=V(),$c=Br(),qb={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:$c.stringifyNumber},Wb={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():$c.stringifyNumber(e)}},zb={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 Vb.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let n=e.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:$c.stringifyNumber};Ma.float=zb;Ma.floatExp=Wb;Ma.floatNaN=qb});var np=N(Wn=>{"use strict";var rp=Br(),qn=e=>typeof e=="bigint"||Number.isInteger(e);function Fa(e,t,r,{intAsBigInt:n}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return i==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return i==="-"?-1*a:a}function Oc(e,t,r){let{value:n}=e;if(qn(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return rp.stringifyNumber(e)}var Gb={identify:qn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Fa(e,2,2,r),stringify:e=>Oc(e,2,"0b")},Kb={identify:qn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Fa(e,1,8,r),stringify:e=>Oc(e,8,"0")},Jb={identify:qn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Fa(e,0,10,r),stringify:rp.stringifyNumber},Ub={identify:qn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Fa(e,2,16,r),stringify:e=>Oc(e,16,"0x")};Wn.int=Jb;Wn.intBin=Gb;Wn.intHex=Ub;Wn.intOct=Kb});var Dc=N(Hc=>{"use strict";var Wa=A(),Va=Ot(),qa=Dt(),sr=class e extends qa.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Wa.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Va.Pair(t.key,null):r=new Va.Pair(t,null),qa.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=qa.findPair(this.items,t);return!r&&Wa.isPair(n)?Wa.isScalar(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=qa.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new Va.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){let{replacer:i}=n,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),a.items.push(Va.createPair(o,null,n));return a}};sr.tag="tag:yaml.org,2002:set";var Yb={collection:"map",identify:e=>e instanceof Set,nodeClass:sr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>sr.from(e,t,r),resolve(e,t){if(Wa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new sr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Hc.YAMLSet=sr;Hc.set=Yb});var Bc=N(za=>{"use strict";var Xb=Br();function Lc(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=o=>t?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*i(60)+i(s),i(0));return r==="-"?i(-1)*a:a}function ip(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Xb.stringifyNumber(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Qb={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:r})=>Lc(e,r),stringify:ip},Zb={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=>Lc(e,!1),stringify:ip},ap={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(ap.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Lc(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$/,"")??""};za.floatTime=Zb;za.intTime=Qb;za.timestamp=ap});var cp=N(sp=>{"use strict";var eN=Dr(),tN=Ta(),rN=Lr(),nN=Mn(),iN=Rc(),op=ep(),Mc=tp(),Ga=np(),aN=Ea(),oN=Tc(),sN=Ba(),cN=Dc(),Fc=Bc(),lN=[eN.map,rN.seq,nN.string,tN.nullTag,op.trueTag,op.falseTag,Ga.intBin,Ga.intOct,Ga.int,Ga.intHex,Mc.floatNaN,Mc.floatExp,Mc.float,iN.binary,aN.merge,oN.omap,sN.pairs,cN.set,Fc.intTime,Fc.floatTime,Fc.timestamp];sp.schema=lN});var wp=N(Wc=>{"use strict";var fp=Dr(),uN=Ta(),pp=Lr(),dN=Mn(),fN=bc(),Vc=kc(),qc=Ec(),pN=Ff(),hN=Wf(),hp=Rc(),zn=Ea(),mp=Tc(),vp=Ba(),lp=cp(),gp=Dc(),Ka=Bc(),up=new Map([["core",pN.schema],["failsafe",[fp.map,pp.seq,dN.string]],["json",hN.schema],["yaml11",lp.schema],["yaml-1.1",lp.schema]]),dp={binary:hp.binary,bool:fN.boolTag,float:Vc.float,floatExp:Vc.floatExp,floatNaN:Vc.floatNaN,floatTime:Ka.floatTime,int:qc.int,intHex:qc.intHex,intOct:qc.intOct,intTime:Ka.intTime,map:fp.map,merge:zn.merge,null:uN.nullTag,omap:mp.omap,pairs:vp.pairs,seq:pp.seq,set:gp.set,timestamp:Ka.timestamp},mN={"tag:yaml.org,2002:binary":hp.binary,"tag:yaml.org,2002:merge":zn.merge,"tag:yaml.org,2002:omap":mp.omap,"tag:yaml.org,2002:pairs":vp.pairs,"tag:yaml.org,2002:set":gp.set,"tag:yaml.org,2002:timestamp":Ka.timestamp};function vN(e,t,r){let n=up.get(t);if(n&&!e)return r&&!n.includes(zn.merge)?n.concat(zn.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let a=Array.from(up.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)i=i.concat(a);else typeof e=="function"&&(i=e(i.slice()));return r&&(i=i.concat(zn.merge)),i.reduce((a,o)=>{let s=typeof o=="string"?dp[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(dp).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},[])}Wc.coreKnownTags=mN;Wc.getTags=vN});var Kc=N(yp=>{"use strict";var zc=A(),gN=Dr(),wN=Lr(),yN=Mn(),Ja=wp(),bN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Gc=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ja.getTags(t,"compat"):t?Ja.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=i?Ja.coreKnownTags:{},this.tags=Ja.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,zc.MAP,{value:gN.map}),Object.defineProperty(this,zc.SCALAR,{value:yN.string}),Object.defineProperty(this,zc.SEQ,{value:wN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?bN:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};yp.Schema=Gc});var Np=N(bp=>{"use strict";var NN=A(),Jc=Dn(),Gn=jn();function kN(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=Jc.createStringifyContext(e,t),{commentString:a}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Gn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(NN.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Gn.indentComment(u,""))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Jc.stringify(e.contents,i,()=>s=null,c);s&&(l+=Gn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Jc.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(Gn.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Gn.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
61
|
-
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===
|
|
60
|
+
`}bp.stringifyDocument=kN});var Kn=N(kp=>{"use strict";var SN=In(),Mr=ha(),Re=A(),EN=Ot(),xN=It(),CN=Kc(),PN=Np(),Uc=ua(),RN=Zs(),_N=Tn(),Yc=Qs(),Xc=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Re.NODE_TYPE,{value:Re.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Yc.Directives({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[Re.NODE_TYPE]:{value:Re.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=Re.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Fr(this.contents)&&this.contents.add(t)}addIn(t,r){Fr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=Uc.anchorNames(this);t.anchor=!r||n.has(r)?Uc.findNewAnchor(r||"a",n):r}return new SN.Alias(t.anchor)}createNode(t,r,n){let i;if(typeof r=="function")t=r.call({"":t},"",t),i=r;else if(Array.isArray(r)){let v=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=r.filter(v).map(String);w.length>0&&(r=r.concat(w)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Uc.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=_N.createNode(t,u,m);return s&&Re.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,r,n={}){let i=this.createNode(t,null,n),a=this.createNode(r,null,n);return new EN.Pair(i,a)}delete(t){return Fr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Mr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Fr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Re.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return Mr.isEmptyPath(t)?!r&&Re.isScalar(this.contents)?this.contents.value:this.contents:Re.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Re.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Mr.isEmptyPath(t)?this.contents!==void 0:Re.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=Mr.collectionFromPath(this.schema,[t],r):Fr(this.contents)&&this.contents.set(t,r)}setIn(t,r){Mr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=Mr.collectionFromPath(this.schema,Array.from(t),r):Fr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Yc.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Yc.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new CN.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=xN.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?RN.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}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 r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return PN.stringifyDocument(this,t)}};function Fr(e){if(Re.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}kp.Document=Xc});var Yn=N(Un=>{"use strict";var Jn=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},Qc=class extends Jn{constructor(t,r,n){super("YAMLParseError",t,r,n)}},Zc=class extends Jn{constructor(t,r,n){super("YAMLWarning",t,r,n)}},AN=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
|
+
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===n&&c.col>i&&(s=Math.max(1,Math.min(c.col-i,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.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 r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(
|
|
67
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
68
|
-
`+k.comment:y.comment=k.comment);let E=new
|
|
69
|
-
`+g.comment:l.comment=g.comment),d=g.end;continue}!o&&r.options.strict&&
|
|
70
|
-
`+
|
|
71
|
-
`+
|
|
72
|
-
`+v.comment:l.comment=v.comment),l.range=[
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",v=i
|
|
74
|
-
`;for(let h=u;h<s;++h){let[v,w]=o[h];l+=v.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&v.length<c){let E=`Block scalar lines must not be less indented than their ${
|
|
65
|
+
`}};Un.YAMLError=Jn;Un.YAMLParseError=Qc;Un.YAMLWarning=Zc;Un.prettifyError=AN});var Xn=N(Sp=>{"use strict";function IN(e,{flow:t,indicator:r,next:n,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,m=!1,h=null,v=null,w=null,y=null,k=null,E=null,x=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&&(r!=="doc-start"||n?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),u=!0;break;case"comment":{u||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=b.source.substring(1)||" ";d?d+=f+T:d=T,f="",l=!1;break}case"newline":l?d?d+=b.source:(!E||r!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,p=!0,(v||w)&&(y=b),u=!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,x??(x=b.offset),l=!1,u=!1,m=!0;break;case"tag":{w&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),w=b,x??(x=b.offset),l=!1,u=!1,m=!0;break}case r:(v||w)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),E&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),E=b,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=b,l=!1,u=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,u=!1}let g=e[e.length-1],_=g?g.offset+g.source.length:i;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:E,spaceBefore:c,comment:d,hasNewline:p,anchor:v,tag:w,newlineAfterProp:y,end:_,start:x??_}}Sp.resolveProps=IN});var Ua=N(Ep=>{"use strict";function el(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 r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(el(t.key)||el(t.value))return!0}return!1;default:return!0}}Ep.containsNewline=el});var tl=N(xp=>{"use strict";var TN=Ua();function jN(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&TN.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}xp.flowIndentCheck=jN});var rl=N(Pp=>{"use strict";var Cp=A();function $N(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(a,o)=>a===o||Cp.isScalar(a)&&Cp.isScalar(o)&&a.value===o.value;return t.some(a=>i(a.key,r))}Pp.mapIncludes=$N});var jp=N(Tp=>{"use strict";var Rp=Ot(),ON=Dt(),_p=Xn(),HN=Ua(),Ap=tl(),DN=rl(),Ip="All mapping items must start at the same column";function LN({composeNode:e,composeEmptyNode:t},r,n,i,a){let o=a?.nodeClass??ON.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:p,value:m}=u,h=_p.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),v=!h.found;if(v){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(c,"BAD_INDENT",Ip)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||HN.containsNewline(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",Ip);r.atKey=!0;let w=h.end,y=f?e(r,f,h,i):t(r,w,d,null,h,i);r.schema.compat&&Ap.flowIndentCheck(n.indent,f,i),r.atKey=!1,DN.mapIncludes(r,s.items,y)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let k=_p.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&i(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=m?e(r,m,k,i):t(r,c,p,null,k,i);r.schema.compat&&Ap.flowIndentCheck(n.indent,m,i),c=E.range[2];let x=new Rp.Pair(y,E);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&i(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(y.comment?y.comment+=`
|
|
68
|
+
`+k.comment:y.comment=k.comment);let E=new Rp.Pair(y);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}Tp.resolveBlockMap=LN});var Op=N($p=>{"use strict";var BN=Lt(),MN=Xn(),FN=tl();function VN({composeNode:e,composeEmptyNode:t},r,n,i,a){let o=a?.nodeClass??BN.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:d}of n.items){let f=MN.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?i(f.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(r,d,f,i):t(r,f.end,u,null,f,i);r.schema.compat&&FN.flowIndentCheck(n.indent,d,i),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}$p.resolveBlockSeq=VN});var Vr=N(Hp=>{"use strict";function qN(e,t,r,n){let i="";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":{r&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";i?i+=o+u:i=u,o="";break}case"newline":i&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:i,offset:t}}Hp.resolveEnd=qN});var Mp=N(Bp=>{"use strict";var WN=A(),zN=Ot(),Dp=Dt(),GN=Lt(),KN=Vr(),Lp=Xn(),JN=Ua(),UN=rl(),nl="Block collections are not allowed within flow collections",il=e=>e&&(e.type==="block-map"||e.type==="block-seq");function YN({composeNode:e,composeEmptyNode:t},r,n,i,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Dp.YAMLMap:GN.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=n.offset+n.start.source.length;for(let v=0;v<n.items.length;++v){let w=n.items[v],{start:y,key:k,sep:E,value:x}=w,g=Lp.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:k??E?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!E&&!x){v===0&&g.comma?i(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<n.items.length-1&&i(g.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),g.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+g.comment:l.comment=g.comment),d=g.end;continue}!o&&r.options.strict&&JN.containsNewline(k)&&i(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)g.comma&&i(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(g.comma||i(g.start,"MISSING_CHAR",`Missing , between ${s} items`),g.comment){let _="";e:for(let b of y)switch(b.type){case"comma":case"space":break;case"comment":_=b.source.substring(1);break e;default:break e}if(_){let b=l.items[l.items.length-1];WN.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
|
|
70
|
+
`+_:b.comment=_,g.comment=g.comment.substring(_.length+1)}}if(!o&&!E&&!g.found){let _=x?e(r,x,g,i):t(r,g.end,E,null,g,i);l.items.push(_),d=_.range[2],il(x)&&i(_.range,"BLOCK_IN_FLOW",nl)}else{r.atKey=!0;let _=g.end,b=k?e(r,k,g,i):t(r,_,y,null,g,i);il(k)&&i(b.range,"BLOCK_IN_FLOW",nl),r.atKey=!1;let T=Lp.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:x,offset:b.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(T.found){if(!o&&!g.found&&r.options.strict){if(E)for(let W of E){if(W===T.found)break;if(W.type==="newline"){i(W,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<T.found.offset-1024&&i(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?i(x,"MISSING_CHAR",`Missing space after : in ${s}`):i(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ie=x?e(r,x,T,i):T.found?t(r,T.end,E,null,T,i):null;ie?il(x)&&i(ie.range,"BLOCK_IN_FLOW",nl):T.comment&&(b.comment?b.comment+=`
|
|
71
|
+
`+T.comment:b.comment=T.comment);let Tr=new zN.Pair(b,ie);if(r.options.keepSourceTokens&&(Tr.srcToken=w),o){let W=l;UN.mapIncludes(r,W.items,b)&&i(_,"DUPLICATE_KEY","Map keys must be unique"),W.items.push(Tr)}else{let W=new Dp.YAMLMap(r.schema);W.flow=!0,W.items.push(Tr);let Bd=(ie??b).range;W.range=[b.range[0],Bd[1],Bd[2]],l.items.push(W)}d=ie?ie.range[2]:T.end}}let f=o?"}":"]",[p,...m]=n.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let v=s[0].toUpperCase()+s.substring(1),w=u?`${v} must end with a ${f}`:`${v} in block collection must be sufficiently indented and end with a ${f}`;i(d,u?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=KN.resolveEnd(m,h,r.options.strict,i);v.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+v.comment:l.comment=v.comment),l.range=[n.offset,h,v.offset]}else l.range=[n.offset,h,h];return l}Bp.resolveFlowCollection=YN});var Vp=N(Fp=>{"use strict";var XN=A(),QN=V(),ZN=Dt(),ek=Lt(),tk=jp(),rk=Op(),nk=Mp();function al(e,t,r,n,i,a){let o=r.type==="block-map"?tk.resolveBlockMap(e,t,r,n,a):r.type==="block-seq"?rk.resolveBlockSeq(e,t,r,n,a):nk.resolveFlowCollection(e,t,r,n,a),s=o.constructor;return i==="!"||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function ik(e,t,r,n,i){let a=n.tag,o=a?t.directives.tagName(a.source,f=>i(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!p||p.offset<m.offset)&&i(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===ZN.YAMLMap.tagName&&s==="map"||o===ek.YAMLSeq.tagName&&s==="seq")return al(e,t,r,i,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):i(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),al(e,t,r,i,o)}let l=al(e,t,r,i,o,c),u=c.resolve?.(l,f=>i(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=XN.isNode(u)?u:new QN.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Fp.composeCollection=ik});var sl=N(qp=>{"use strict";var ol=V();function ak(e,t,r){let n=t.offset,i=ok(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let a=i.mode===">"?ol.Scalar.BLOCK_FOLDED:ol.Scalar.BLOCK_LITERAL,o=t.source?sk(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=i.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",v=n+i.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:i.comment,range:[n,v,v]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let h=0;h<s;++h){let[v,w]=o[h];if(w===""||w==="\r")i.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
|
|
74
|
+
`;for(let h=u;h<s;++h){let[v,w]=o[h];l+=v.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&v.length<c){let E=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(y?2:1),"BAD_INDENT",E),v=""}a===ol.Scalar.BLOCK_LITERAL?(d+=f+v.slice(c)+w,f=`
|
|
75
75
|
`):v.length>c||w[0]===" "?(f===" "?f=`
|
|
76
76
|
`:!p&&f===`
|
|
77
77
|
`&&(f=`
|
|
@@ -80,69 +80,69 @@ ${l}
|
|
|
80
80
|
`,p=!0):w===""?f===`
|
|
81
81
|
`?d+=`
|
|
82
82
|
`:f=`
|
|
83
|
-
`:(d+=f+w,f=" ",p=!1)}switch(
|
|
83
|
+
`:(d+=f+w,f=" ",p=!1)}switch(i.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
|
|
84
84
|
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let m=i
|
|
87
|
+
`}let m=n+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[n,m,m]}}function ok({offset:e,props:t},r,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],a=i[0],o=0,s="",c=-1;for(let f=1;f<i.length;++f){let p=i[f];if(!s&&(p==="-"||p==="+"))s=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=e+f)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",d=i.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":r&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function sk(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),a=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}qp.resolveBlockScalar=ak});var ll=N(zp=>{"use strict";var cl=V(),ck=Vr();function lk(e,t,r){let{offset:n,type:i,source:a,end:o}=e,s,c,l=(f,p,m)=>r(n+f,p,m);switch(i){case"scalar":s=cl.Scalar.PLAIN,c=uk(a,l);break;case"single-quoted-scalar":s=cl.Scalar.QUOTE_SINGLE,c=dk(a,l);break;case"double-quoted-scalar":s=cl.Scalar.QUOTE_DOUBLE,c=fk(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let u=n+a.length,d=ck.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function uk(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Wp(e)}function dk(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Wp(e.slice(1,-1)).replace(/''/g,"'")}function Wp(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
-
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \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
|
-
`)&&(r+=
|
|
98
|
-
`||
|
|
99
|
-
`);)
|
|
89
|
+
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;n=r.exec(e);)n[1]===""?a===`
|
|
90
|
+
`?i+=a:a=`
|
|
91
|
+
`:(i+=a+n[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(e),i+a+(n?.[1]??"")}function fk(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
|
|
92
|
+
`))if(i===`
|
|
93
|
+
`){let{fold:a,offset:o}=pk(e,n);r+=a,n=o}else if(i==="\\"){let a=e[++n],o=hk[a];if(o)r+=o;else if(a===`
|
|
94
|
+
`)for(a=e[n+1];a===" "||a===" ";)a=e[++n+1];else if(a==="\r"&&e[n+1]===`
|
|
95
|
+
`)for(a=e[++n+1];a===" "||a===" ";)a=e[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=mk(e,n+1,s,t),n+=s}else{let s=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(i===" "||i===" "){let a=n,o=e[n+1];for(;o===" "||o===" ";)o=e[++n+1];o!==`
|
|
96
|
+
`&&!(o==="\r"&&e[n+2]===`
|
|
97
|
+
`)&&(r+=n>a?e.slice(a,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function pk(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
|
|
98
|
+
`||n==="\r")&&!(n==="\r"&&e[t+2]!==`
|
|
99
|
+
`);)n===`
|
|
100
100
|
`&&(r+=`
|
|
101
|
-
`),t+=1,
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var hk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function mk(e,t,r,n){let i=e.substr(t,r),o=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}zp.resolveFlowScalar=lk});var Jp=N(Kp=>{"use strict";var cr=A(),Gp=V(),vk=sl(),gk=ll();function wk(e,t,r,n){let{value:i,type:a,comment:o,range:s}=t.type==="block-scalar"?vk.resolveBlockScalar(e,t,n):gk.resolveFlowScalar(t,e.options.strict,n),c=r?e.directives.tagName(r.source,d=>n(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[cr.SCALAR]:c?l=yk(e.schema,i,c,r,n):t.type==="scalar"?l=bk(e,i,t,n):l=e.schema[cr.SCALAR];let u;try{let d=l.resolve(i,f=>n(r??t,"TAG_RESOLVE_FAILED",f),e.options);u=cr.isScalar(d)?d:new Gp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(r??t,"TAG_RESOLVE_FAILED",f),u=new Gp.Scalar(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function yk(e,t,r,n,i){if(r==="!")return e[cr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)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[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[cr.SCALAR])}function bk({atKey:e,directives:t,schema:r},n,i,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||r[cr.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(n))??r[cr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}Kp.composeScalar=wk});var Yp=N(Up=>{"use strict";function Nk(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let i=t[n];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++n];i?.type==="space";)e+=i.source.length,i=t[++n];break}}return e}Up.emptyScalarPosition=Nk});var Zp=N(dl=>{"use strict";var kk=In(),Sk=A(),Ek=Vp(),Xp=Jp(),xk=Vr(),Ck=Yp(),Pk={composeNode:Qp,composeEmptyNode:ul};function Qp(e,t,r,n){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=Rk(e,t,n),(s||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Xp.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Ek.composeCollection(Pk,e,t,r,n),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=ul(e,t.offset,void 0,null,r,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!Sk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function ul(e,t,r,n,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Ck.emptyScalarPosition(t,r,n),indent:-1,source:""},d=Xp.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Rk({options:e},{offset:t,source:r,end:n},i){let a=new kk.Alias(r.substring(1));a.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=xk.resolveEnd(n,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}dl.composeEmptyNode=ul;dl.composeNode=Qp});var rh=N(th=>{"use strict";var _k=Kn(),eh=Zp(),Ak=Vr(),Ik=Xn();function Tk(e,t,{offset:r,start:n,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new _k.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Ik.resolveProps(n,{indicator:"doc-start",next:i??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?eh.composeNode(l,i,u,o):eh.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Ak.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[r,d,f.offset],c}th.composeDoc=Tk});var pl=N(ah=>{"use strict";var jk=aa("process"),$k=Qs(),Ok=Kn(),Qn=Yn(),nh=A(),Hk=rh(),Dk=Vr();function Zn(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:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function ih(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case"#":t+=(t===""?"":n?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),r=!0,
|
|
106
|
-
${
|
|
107
|
-
${s}`:
|
|
108
|
-
${o}`:
|
|
109
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
105
|
+
`)+(a.substring(1)||" "),r=!0,n=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}var fl=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,a)=>{let o=Zn(r);a?this.warnings.push(new Qn.YAMLWarning(o,n,i)):this.errors.push(new Qn.YAMLParseError(o,n,i))},this.directives=new $k.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=ih(this.prelude);if(n){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${n}`:n;else if(i||t.directives.docStart||!a)t.commentBefore=n;else if(nh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];nh.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n}
|
|
107
|
+
${s}`:n}else{let o=a.commentBefore;a.commentBefore=o?`${n}
|
|
108
|
+
${o}`:n}}if(r){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:ih(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,n=-1){for(let i of t)yield*this.next(i);yield*this.end(r,n)}*next(t){switch(jk.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let a=Zn(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=Hk.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new Qn.YAMLParseError(Zn(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Qn.YAMLParseError(Zn(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=Dk.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Qn.YAMLParseError(Zn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),i=new Ok.Document(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};ah.Composer=fl});var ch=N(Ya=>{"use strict";var Lk=sl(),Bk=ll(),Mk=Yn(),oh=Hn();function Fk(e,t=!0,r){if(e){let n=(i,a,o)=>{let s=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(s,a,o);else throw new Mk.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Bk.resolveFlowScalar(e,t,n);case"block-scalar":return Lk.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function Vk(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:a=-1,type:o="PLAIN"}=t,s=oh.stringifyString({type:o,value:e},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:
|
|
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:r,source:t,end:[
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return sh(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:n,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function qk(e,t,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=oh.stringifyString({type:o,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Wk(e,c);break;case'"':hl(e,c,"double-quoted-scalar");break;case"'":hl(e,c,"single-quoted-scalar");break;default:hl(e,c,"scalar")}}function Wk(e,t){let r=t.indexOf(`
|
|
114
|
+
`),n=t.substring(0,r),i=t.substring(r+1)+`
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,e.source=i}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];sh(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:i})}}function sh(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function hl(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let a of n)a.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[i]});break}default:{let n="indent"in e?e.indent:-1,i="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:r,indent:n,source:t,end:i})}}}Ya.createScalarToken=Vk;Ya.resolveAsScalar=Fk;Ya.setScalarValue=qk});var uh=N(lh=>{"use strict";var zk=e=>"type"in e?Qa(e):Xa(e);function Qa(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Qa(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Xa(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Xa(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Xa(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Xa({start:e,key:t,sep:r,value:n}){let i="";for(let a of e)i+=a.source;if(t&&(i+=Qa(t)),r)for(let a of r)i+=a.source;return n&&(i+=Qa(n)),i}lh.stringify=zk});var hh=N(ph=>{"use strict";var ml=Symbol("break visit"),Gk=Symbol("skip children"),dh=Symbol("remove item");function lr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),fh(Object.freeze([]),e,t)}lr.BREAK=ml;lr.SKIP=Gk;lr.REMOVE=dh;lr.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let a=r?.[n];if(a&&"items"in a)r=a.items[i];else return}return r};lr.parentCollection=(e,t)=>{let r=lr.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function fh(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let a=t[i];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=fh(Object.freeze(e.concat([[i,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===ml)return ml;s===dh&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}ph.visit=lr});var Za=N(me=>{"use strict";var vl=ch(),Kk=uh(),Jk=hh(),gl="\uFEFF",wl="",yl="",bl="",Uk=e=>!!e&&"items"in e,Yk=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Xk(e){switch(e){case gl:return"<BOM>";case wl:return"<DOC>";case yl:return"<FLOW_END>";case bl:return"<SCALAR>";default:return JSON.stringify(e)}}function Qk(e){switch(e){case gl:return"byte-order-mark";case wl:return"doc-mode";case yl:return"flow-error-end";case bl: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}me.createScalarToken=vl.createScalarToken;me.resolveAsScalar=vl.resolveAsScalar;me.setScalarValue=vl.setScalarValue;me.stringify=Kk.stringify;me.visit=Jk.visit;me.BOM=gl;me.DOCUMENT=wl;me.FLOW_END=yl;me.SCALAR=bl;me.isCollection=Uk;me.isScalar=Yk;me.prettyToken=Xk;me.tokenType=Qk});var Sl=N(vh=>{"use strict";var ei=Za();function Le(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var mh=new Set("0123456789ABCDEFabcdef"),Zk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),eo=new Set(",[]{}"),eS=new Set(` ,[]{}
|
|
121
|
+
\r `),Nl=e=>!e||eS.has(e),kl=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,r=!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=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
122
122
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
123
|
-
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=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 r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`
|
|
124
|
+
`||!i&&!this.atEnd)return t+n+1}return r===`
|
|
125
|
+
`||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&Le(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]===ei.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let a=t[n-1];if(a===" "||a===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield ei.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 r=this.peek(3);if((r==="---"||r==="...")&&Le(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Le(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Le(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);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(Nl),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,n=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&Le(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield ei.FLOW_END,yield*this.parseLineStart();let a=0;for(;i[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),i[a]){case void 0:return"flow";case"#":return yield*this.pushCount(i.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(Nl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Le(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
|
|
127
|
+
`,this.pos);if(i!==-1){for(;i!==-1;){let a=this.continueScalar(i+1);if(a===-1)break;i=n.indexOf(`
|
|
128
|
+
`,a)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Le(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let a=this.pos;n=this.buffer[a];++a)switch(n){case" ":r+=1;break;case`
|
|
129
129
|
`:t=a,r=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+r>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(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r: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 i=t+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
132
|
+
`;)n=this.buffer[++i];t=i-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+r>s)t=a;else break}while(!0);return yield ei.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let a=this.buffer[n+1];if(Le(a)||t&&eo.has(a))break;r=n}else if(Le(i)){let a=this.buffer[n+1];if(i==="\r"&&(a===`
|
|
134
|
+
`?(n+=1,i=`
|
|
135
|
+
`,a=this.buffer[n+1]):r=n),a==="#"||t&&eo.has(a))break;if(i===`
|
|
136
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&eo.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield ei.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(r&&(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(Nl),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(Le(n)||r&&eo.has(n)){r?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,r=this.buffer[t];for(;!Le(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(Zk.has(r))r=this.buffer[++t];else if(r==="%"&&mh.has(this.buffer[t+1])&&mh.has(this.buffer[t+2]))r=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 r=this.pos-1,
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};vh.Lexer=kl});var xl=N(gh=>{"use strict";var El=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,n=this.lineStarts.length;for(;r<n;){let a=r+n>>1;this.lineStarts[a]<t?r=a+1:n=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let i=this.lineStarts[r-1];return{line:r,col:t-i+1}}}};gh.LineCounter=El});var Pl=N(kh=>{"use strict";var tS=aa("process"),wh=Za(),rS=Sl();function Bt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function yh(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Nh(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 to(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 qr(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 ro(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function bh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Bt(t.start,"explicit-key-ind")&&!Bt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Nh(t.value)?t.value.end?ro(t.value.end,t.sep):t.value.end=t.sep:ro(t.start,t.sep),delete t.sep)}var Cl=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 rS.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,r))yield*this.next(n);r||(yield*this.end())}*next(t){if(this.source=t,tS.env.LOG_TOKENS&&console.log("|",wh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=wh.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&bh(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&yh(i.start)===-1&&(r.indent===0||i.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{yh(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):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 r=to(this.peek(2)),n=qr(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:i}]};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 r=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
-
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){ro(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(i&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.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=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):i||r.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(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Bt(r.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(Nh(r.key)&&!Bt(r.sep,"newline")){let o=qr(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Bt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=qr(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||i?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Bt(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{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);i||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Bt(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){ro(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Bt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=to(n),a=qr(i);bh(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 r=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
-
`,r)+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 r=
|
|
143
|
-
`)){let s=
|
|
144
|
-
`))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?
|
|
145
|
-
`)}function tk(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||It.posix.isAbsolute(r)||It.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Qt(e){let t=tk(e,"native.artifact_root");return t.length===0?".":t.join("/")}function $p(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function _a(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||It.posix.isAbsolute(i)||It.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.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(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function at(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Op(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Aa(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Ca)throw new Error(`${t} exceeds ${Ca} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Pa)throw new Error(`${t} contains more than ${Pa} wildcard tokens`);return e}function Ip(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Aa(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Oi(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Tp(e,t,r){let i=Oi(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function rk(e){if(e===void 0)return{...pe,include:[...pe.include],exclude:[...pe.exclude]};let t=at(e,"native.snapshot");return{include:Ip(t.include,"native.snapshot.include",pe.include),exclude:Ip(t.exclude,"native.snapshot.exclude",pe.exclude),max_files:Oi(t.max_files,pe.max_files,"native.snapshot.max_files"),max_total_bytes:Oi(t.max_total_bytes,pe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Oi(t.max_duration_ms,pe.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Oi(t.max_selection_records,pe.max_selection_records,"native.snapshot.max_selection_records")}}function ik(e){if(e===void 0)return;let t=at(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="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=at(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:r,fromArtifactRoot:Qt(i),toArtifactRoot:Qt(n),stage:a,...o?{cleanup:o}:{}}}function nk(e){if(e===void 0)return;let t=at(e,"native.finish");if(t.pull_request===void 0)return{};let r=at(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(It.posix.isAbsolute(i[0])||It.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??Yb;if(!Number.isSafeInteger(n)||n<1||n>Ap)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ap}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function ak(e,t={}){let r=at(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Wc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=ik(r.pending_root_move),l=nk(r.finish);return{artifact_root:Qt(i),language:Op(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:rk(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function ok(e){let t=at(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="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");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:$p(t.artifact_layout),language:Op(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function sk(e){let r=at(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>_a(i,`hook.allow_paths[${n}]`)))]}}function ck(e){if(e===void 0)return{...Hi};let t=at(e,"memory"),r=t.learning??Hi.learning,i=t.retrieval??Hi.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function Kc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function lk(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||It.posix.isAbsolute(r)||It.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Rp)throw new Error(`${t} exceeds ${Rp} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>_p)throw new Error(`${t} contains more than ${_p} wildcard tokens`);return r}function uk(e){let t=Kc(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>lk(n,`knowledge.local.include[${a}]`)))],max_file_mb:Tp(t.max_file_mb,Ra.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Tp(t.max_total_mb,Ra.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function dk(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function fk(e){let t=Kc(e,"knowledge.remote"),r=dk(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function pk(e){if(e===void 0)return{...zc};let t=Kc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:uk(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:fk(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function hk(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function mk(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)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 u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Rr(e,t={}){let r=(0,Di.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=hk(n.ambient_resume),o=n.hook===void 0?void 0:sk(n.hook),s=ck(n.memory),c=pk(n.knowledge),l=n.native===void 0?void 0:ak(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:ok(n.classic),d=mk(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Hp(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Dp(e){let t=e.knowledge??{...zc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Hi},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??Ra.max_file_mb,max_total_mb:t.local.max_total_mb??Ra.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Hp(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function ve(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Mi(e,t){let r=Dp(t),i=Rr((0,Di.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...ve(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=ve(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=ve(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...ve(a.local),include:[...i.knowledge.local.include],max_file_mb:i.knowledge.local.max_file_mb,max_total_mb:i.knowledge.local.max_total_mb}:delete o.local,i.knowledge.remote){let c={...ve(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=ve(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures,...i.native.document_writes?{document_writes:i.native.document_writes}:{}};if(i.native.finish?.pull_request){let s=ve(a.finish);o.finish={...s,pull_request:{...ve(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...ve(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=ve(a.pending_root_move),c=Hp(i.native.pending_root_move),l=ve(s.cleanup),u=ve(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...ve(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition,...i.classic.document_evidence?{document_evidence:i.classic.document_evidence}:{}}),n}function Ia(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Hi},knowledge:{...zc},native:{artifact_root:Qt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Wc,snapshot:{...pe,include:[...pe.include],exclude:[...pe.exclude]}}}}var Di,Li,Ca,Pa,Rp,_p,Wc,Hi,Ra,zc,Yb,Ap,Xb,Qb,Zb,pe,Pr,Tt=S(()=>{"use strict";Di=Nt(nt(),1),Li=Number.MAX_SAFE_INTEGER,Ca=1024,Pa=64,Rp=1024,_p=64,Wc=5,Hi={learning:!0,retrieval:!0},Ra={include:[],max_file_mb:1,max_total_mb:32},zc={provider:"local"},Yb=12e4,Ap=6e5,Xb=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Qb=["**/.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"],Zb=[...Xb,...Qb].sort((e,t)=>e.localeCompare(t,"en")),pe={include:["**/*"],exclude:[...Zb],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},Pr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
142
|
+
`,r)+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 r=to(t),n=qr(r);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 r=to(t),n=qr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!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())}}};kh.Parser=Cl});var Ph=N(ri=>{"use strict";var Sh=pl(),nS=Kn(),ti=Yn(),iS=dc(),aS=A(),oS=xl(),Eh=Pl();function xh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new oS.LineCounter||null,prettyErrors:t}}function sS(e,t={}){let{lineCounter:r,prettyErrors:n}=xh(t),i=new Eh.Parser(r?.addNewLine),a=new Sh.Composer(t),o=Array.from(a.compose(i.parse(e)));if(n&&r)for(let s of o)s.errors.forEach(ti.prettifyError(e,r)),s.warnings.forEach(ti.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Ch(e,t={}){let{lineCounter:r,prettyErrors:n}=xh(t),i=new Eh.Parser(r?.addNewLine),a=new Sh.Composer(t),o=null;for(let s of a.compose(i.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new ti.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(ti.prettifyError(e,r)),o.warnings.forEach(ti.prettifyError(e,r))),o}function cS(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=Ch(e,r);if(!i)return null;if(i.warnings.forEach(a=>iS.warn(i.options.logLevel,a)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function lS(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=r??t??{};if(!i)return}return aS.isDocument(e)&&!n?e.toString(r):new nS.Document(e,n,r).toString(r)}ri.parse=cS;ri.parseAllDocuments=sS;ri.parseDocument=Ch;ri.stringify=lS});var mt=N($=>{"use strict";var uS=pl(),dS=Kn(),fS=Kc(),Rl=Yn(),pS=In(),Mt=A(),hS=Ot(),mS=V(),vS=Dt(),gS=Lt(),wS=Za(),yS=Sl(),bS=xl(),NS=Pl(),no=Ph(),Rh=Pn();$.Composer=uS.Composer;$.Document=dS.Document;$.Schema=fS.Schema;$.YAMLError=Rl.YAMLError;$.YAMLParseError=Rl.YAMLParseError;$.YAMLWarning=Rl.YAMLWarning;$.Alias=pS.Alias;$.isAlias=Mt.isAlias;$.isCollection=Mt.isCollection;$.isDocument=Mt.isDocument;$.isMap=Mt.isMap;$.isNode=Mt.isNode;$.isPair=Mt.isPair;$.isScalar=Mt.isScalar;$.isSeq=Mt.isSeq;$.Pair=hS.Pair;$.Scalar=mS.Scalar;$.YAMLMap=vS.YAMLMap;$.YAMLSeq=gS.YAMLSeq;$.CST=wS;$.Lexer=yS.Lexer;$.LineCounter=bS.LineCounter;$.Parser=NS.Parser;$.parse=no.parse;$.parseAllDocuments=no.parseAllDocuments;$.parseDocument=no.parseDocument;$.stringify=no.stringify;$.visit=Rh.visit;$.visitAsync=Rh.visitAsync});import Ft from"path";function $h(e,t){return Wr[t][e]}function CS(e,t,r,n){let i=/^(\s*)([a-z_]+):/u.exec(e);if(!i)return null;let a=i[1].length,o=i[2];if(a===0&&o in Wr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Wr.en)return s}if(a===4&&t==="knowledge"&&n==="remote"){let s=`knowledge.remote.${o}`;if(s in Wr.en)return s}if(a===4&&t==="knowledge"&&n==="local"){let s=`knowledge.local.${o}`;if(s in Wr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Wr.en)return s}return null}function si(e,t){let r=[],n=null,i=null,a=null;for(let o of(0,ai.stringify)(e).trimEnd().split(`
|
|
143
|
+
`)){let s=CS(o,n,i,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of $h(s,t).split(`
|
|
144
|
+
`))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?n="native":o.startsWith("classic:")?n="classic":o.startsWith("hook:")?n="hook":o.startsWith("memory:")?n="memory":o.startsWith("knowledge:")?n="knowledge":n=null,i=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(n==="native"&&(i=o.startsWith(" snapshot:")?"snapshot":null),n==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
|
|
145
|
+
`)}function PS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ft.posix.isAbsolute(r)||Ft.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function ur(e){let t=PS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Oh(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function so(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||Ft.posix.isAbsolute(n)||Ft.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let i=n.split("/");if(i.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return i.join("/")}function vt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hh(e,t,r){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function co(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>io)throw new Error(`${t} exceeds ${io} characters`);let r=0;for(let n=0;n<e.length;n+=1)e[n]==="?"?r+=1:e[n]==="*"&&(r+=1,e[n+1]==="*"&&(n+=1));if(r>ao)throw new Error(`${t} contains more than ${ao} wildcard tokens`);return e}function Th(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(n=>co(n,t)))].sort((n,i)=>n.localeCompare(i,"en"))}function ni(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function jh(e,t,r){let n=ni(e,t,r);if(n>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return n}function RS(e){if(e===void 0)return{...ve,include:[...ve.include],exclude:[...ve.exclude]};let t=vt(e,"native.snapshot");return{include:Th(t.include,"native.snapshot.include",ve.include),exclude:Th(t.exclude,"native.snapshot.exclude",ve.exclude),max_files:ni(t.max_files,ve.max_files,"native.snapshot.max_files"),max_total_bytes:ni(t.max_total_bytes,ve.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ni(t.max_duration_ms,ve.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:ni(t.max_selection_records,ve.max_selection_records,"native.snapshot.max_selection_records")}}function _S(e){if(e===void 0)return;let t=vt(e,"native.pending_root_move"),r=t.id,n=t.from_artifact_root,i=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof i!="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=vt(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:r,fromArtifactRoot:ur(n),toArtifactRoot:ur(i),stage:a,...o?{cleanup:o}:{}}}function AS(e){if(e===void 0)return;let t=vt(e,"native.finish");if(t.pull_request===void 0)return{};let r=vt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let n=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Ft.posix.isAbsolute(n[0])||Ft.win32.isAbsolute(n[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=r.timeout_ms??kS;if(!Number.isSafeInteger(i)||i<1||i>Ih)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ih}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function IS(e,t={}){let r=vt(e,"native"),n=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let i=r.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??_l;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=_S(r.pending_root_move),l=AS(r.finish);return{artifact_root:ur(n),language:Hh(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:RS(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function TS(e){let t=vt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="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 i=t.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Oh(t.artifact_layout),language:Hh(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i,...a==="strict"?{document_evidence:a}:{}}}function jS(e){let r=vt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((n,i)=>so(n,`hook.allow_paths[${i}]`)))]}}function $S(e){if(e===void 0)return{...ii};let t=vt(e,"memory"),r=t.learning??ii.learning,n=t.retrieval??ii.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof n!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:n}}function Il(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function OS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ft.posix.isAbsolute(r)||Ft.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>_h)throw new Error(`${t} exceeds ${_h} characters`);let n=0;for(let i=0;i<r.length;i+=1)r[i]==="?"?n+=1:r[i]==="*"&&(n+=1,r[i+1]==="*"&&(i+=1));if(n>Ah)throw new Error(`${t} contains more than ${Ah} wildcard tokens`);return r}function HS(e){let t=Il(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let n={include:[...new Set(r.map((i,a)=>OS(i,`knowledge.local.include[${a}]`)))],max_file_mb:jh(t.max_file_mb,oo.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:jh(t.max_total_mb,oo.max_total_mb,"knowledge.local.max_total_mb")};if(n.max_file_mb>n.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return n}function DS(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),n=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function LS(e){let t=Il(e,"knowledge.remote"),r=DS(t.endpoint),n=t.token_env;if(n!==void 0&&(typeof n!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(n)))throw new Error("knowledge.remote.token_env must be an environment variable name");let i=t.scope;if(i!==void 0&&(typeof i!="string"||i.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...n===void 0?{}:{token_env:n},...i===void 0?{}:{scope:i},timeout_ms:a}}function BS(e){if(e===void 0)return{...Al};let t=Il(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let n=t.local===void 0?void 0:HS(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:LS(t.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...n?{local:n}:{},remote:i}}function MS(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function FS(e,t,r,n,i,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)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 u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:n,...i?{native:i}:{},...a?{classic:a}:{}}}function zr(e,t={}){let r=(0,ai.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let n=r.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 i=n,a=MS(i.ambient_resume),o=i.hook===void 0?void 0:jS(i.hook),s=$S(i.memory),c=BS(i.knowledge),l=i.native===void 0?void 0:IS(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=i.classic===void 0?void 0:TS(i.classic),d=FS(i,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Dh(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Lh(e){let t=e.knowledge??{...Al};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...ii},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??oo.max_file_mb,max_total_mb:t.local.max_total_mb??oo.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Dh(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ci(e,t){let r=Lh(t),n=zr((0,ai.stringify)(r)).config;if(!n)throw new Error("Unsupported Comet project schema");let i={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume};if(n.hook&&(i.hook={...be(e.hook),allow_paths:[...n.hook.allow_paths]}),n.memory){let a=be(e.memory);i.memory={...a,learning:n.memory.learning,retrieval:n.memory.retrieval}}if(n.knowledge){let a=be(e.knowledge),o={...a,provider:n.knowledge.provider};if(n.knowledge.local?o.local={...be(a.local),include:[...n.knowledge.local.include],max_file_mb:n.knowledge.local.max_file_mb,max_total_mb:n.knowledge.local.max_total_mb}:delete o.local,n.knowledge.remote){let c={...be(a.remote),endpoint:n.knowledge.remote.endpoint,timeout_ms:n.knowledge.remote.timeout_ms,...n.knowledge.remote.token_env===void 0?{}:{token_env:n.knowledge.remote.token_env},...n.knowledge.remote.scope===void 0?{}:{scope:n.knowledge.remote.scope}};n.knowledge.remote.token_env===void 0&&delete c.token_env,n.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;i.knowledge=o}if(n.native){let a=be(e.native),o={...a,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,...n.native.document_writes?{document_writes:n.native.document_writes}:{}};if(n.native.finish?.pull_request){let s=be(a.finish);o.finish={...s,pull_request:{...be(s.pull_request),provider:n.native.finish.pull_request.provider,command:[...n.native.finish.pull_request.command],timeout_ms:n.native.finish.pull_request.timeout_ms}}}else{let s={...be(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,n.native.pending_root_move){let s=be(a.pending_root_move),c=Dh(n.native.pending_root_move),l=be(s.cleanup),u=be(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;i.native=o}return n.classic&&(i.classic={...be(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition,...n.classic.document_evidence?{document_evidence:n.classic.document_evidence}:{}}),i}function lo(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ii},knowledge:{...Al},native:{artifact_root:ur(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:_l,snapshot:{...ve,include:[...ve.include],exclude:[...ve.exclude]}}}}var ai,oi,io,ao,_h,Ah,_l,ii,oo,Al,kS,Ih,SS,ES,xS,ve,Wr,Vt=S(()=>{"use strict";ai=At(mt(),1),oi=Number.MAX_SAFE_INTEGER,io=1024,ao=64,_h=1024,Ah=64,_l=5,ii={learning:!0,retrieval:!0},oo={include:[],max_file_mb:1,max_total_mb:32},Al={provider:"local"},kS=12e4,Ih=6e5,SS=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],ES=["**/.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"],xS=[...SS,...ES].sort((e,t)=>e.localeCompare(t,"en")),ve={include:["**/*"],exclude:[...xS],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},Wr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
146
146
|
# ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
|
|
147
147
|
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
148
148
|
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
@@ -170,65 +170,146 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
170
170
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
171
171
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
172
172
|
# 可选值:true | false`,"classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
|
|
173
|
-
# 可选值:neutral | strict`}}});function jt(e){return e!==0&&e!==0n&&e!=="0"}function Ke(e,t){return jt(e.dev)&&jt(t.dev)&&jt(e.ino)&&jt(t.ino)}function $(e,t){let r=jt(e.dev)&&jt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=jt(e.ino)&&jt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Fi=S(()=>{"use strict"});import{constants as Ta,promises as Zt}from"fs";function Gc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Lp(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Vi(e){return{dev:e.dev,ino:e.ino,birthtime:Gc(e)}}function ja(e,t){let r=Vi(e),i=Vi(t);return Ke(r,i)?$(r,i):$(r,i)&&Gc(e)===Gc(t)&&Lp(e)===Lp(t)&&e.size===t.size}async function _r(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Zt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Te("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Te("too-large",`${i} exceeds ${t} bytes`);let o=await Zt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Vi(a)});let s=process.platform==="win32"?Ta.O_RDONLY:Ta.O_RDONLY|Ta.O_NOFOLLOW|Ta.O_NONBLOCK,c;try{c=await Zt.open(e,s)}catch(l){throw l.code==="ELOOP"?new Te("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Zt.lstat(e,{bigint:n}),Zt.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ja(a,l)||!ja(a,u))throw new Te("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Vi(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:k}=await c.read(m,0,Math.min(m.length,y),null);if(k===0)break;if(p+=k,p>t)throw new Te("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:n}),Zt.lstat(e,{bigint:n}),Zt.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!ja(a,h)||!ja(a,v))throw new Te("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:Vi(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:w}}finally{await c.close()}}var Te,qi=S(()=>{"use strict";Fi();Te=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as $a}from"fs";import $t from"path";function vk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Jc(e,t){let r=$t.relative(e,t);return r===""||!$t.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${$t.sep}`)}async function Bp(e,t){let r=$t.resolve(e),i=await $a.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return $a.realpath(r)}async function Mp(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=$t.join(n,r[a]);let o;try{o=await $a.lstat(n)}catch(u){if(vk(u))return{exists:!1,kind:"missing"};throw u}let s=$t.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await $a.realpath(n);if(!Jc(t,l))throw new Error(`${i.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 ot(e,t,r){let i=_a(t,r.label),n=$t.resolve(e),a=await Bp(n,r.label),o=i.split("/"),s=$t.resolve(n,...o);if(!Jc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Mp(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function ee(e,t,r,i){let n=await ot(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Bp(n.projectRoot,i.label);return _r(n.target,r,{...i,verify:async(o,s)=>{if(!Jc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Mp(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var st=S(()=>{"use strict";qi();Tt()});import{createHash as gk}from"crypto";function Uc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function wk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Oa(e,t={}){return(await zi(e,t)).document}async function Fp(e){try{return(await ee(e,Wi,Li,{label:Wi})).bytes}catch(t){if(wk(t))return null;throw t}}function Vp(e){return e?{exists:!0,sha256:gk("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Ha(e){return Vp(await Fp(e))}async function zi(e,t={}){let r=await Fp(e);return{document:r?Rr(r.toString("utf8"),t):null,identity:Vp(r)}}async function er(e){return(await Oa(e))?.config??null}var Wi,tr=S(()=>{"use strict";Tt();st();Wi=".comet/config.yaml"});import{promises as Xc}from"node:fs";async function Qc(e,t){let r;for(let i=0;i<=Yc.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Yc.length||!yk.has(a??""))throw n;await new Promise(o=>setTimeout(o,Yc[i]))}throw r}async function Da(e,t){await Qc(()=>Xc.rename(e,t),`rename ${t}`)}async function Zc(e){await Qc(()=>Xc.unlink(e),`unlink ${e}`)}async function La(e,t){await Qc(()=>Xc.link(e,t),`link ${t}`)}var yk,Yc,el=S(()=>{"use strict";yk=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Yc=[50,100,200]});import{randomUUID as Nk}from"crypto";import{constants as bk,promises as ie}from"fs";import je from"path";async function tl(e,t){try{return await La(e,t),{linked:!0}}catch(r){let i=r.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw r}return await ie.copyFile(e,t,bk.COPYFILE_EXCL),{linked:!1}}function Ba(e,t){let r=je.relative(e,t);return r===""||!je.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${je.sep}`)}function Ma(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function kk(e,t){return $(e,Ma(t))}function Fa(e,t){return $(Ma(e),Ma(t))}function Sk(e,t){return Fa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function qp(e){let t=await ie.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ie.realpath(e),...Ma(t)}}async function Ar(e){for(let t of e){let r=await ie.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!kk(t,r)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function Ek(e,t,r){let[i,n]=await Promise.all([ie.lstat(e),ie.realpath(e),Ar(r)]);if(!i.isFile()||i.isSymbolicLink()||!Fa(i,t)||!Ba(r[0].realPath,n))throw new Error("Contained atomic write temporary file changed after close");return i}async function xk(e,t){let r=je.resolve(e),i=je.resolve(t);if(!Ba(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await qp(r)],a=je.relative(r,i).split(je.sep).filter(Boolean),o=r;for(let s of a){await Ar(n),o=je.join(o,s);try{await ie.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await qp(o);if(!Ba(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ar(n),n}async function Ck(e){let t;try{t=await ie.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Pk(e,t,r){let i=je.dirname(e),n=await xk(r.containedRoot,i),a=je.join(i,`.${je.basename(e)}.${Nk()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await ie.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([ie.lstat(a),ie.realpath(a)]);if(await Ar(n),!l.isFile()||l.isSymbolicLink()||!Fa(s,l)||!Ba(n[0].realPath,u))throw new Error("Contained 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(),c=await o.stat(),!Fa(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await Ek(a,c,n),await r.beforeCommit?.(),await Ar(n);let d=await ie.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!Sk(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await tl(a,e),await ie.unlink(a)):await Da(a,e),await Ck(i)}catch(l){await o?.close();try{await Ar(n),await ie.rm(a,{force:!0})}catch{}throw l}}async function rr(e,t,r){await Pk(e,t,r)}var Ir=S(()=>{"use strict";el();Fi()});var $I,rl=S(()=>{"use strict";Ir();tr();st();$I=16*1024});async function il(e,t){if(!t)return;let r=await Ha(e);if(!Uc(r,t))throw new Error("Project config changed before commit; rerun the operation")}var nl=S(()=>{"use strict";Ir();Tt();tr();st();rl()});var Ge=S(()=>{"use strict";Fi()});var Gp={};bg(Gp,{atomicWriteBytes:()=>Kp,atomicWriteJson:()=>ae,atomicWriteText:()=>Y});import{randomUUID as Ak}from"crypto";import{promises as ne}from"fs";import $e from"path";function Va(e,t){let r=$e.relative(e,t);return r===""||!$e.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${$e.sep}`)}function Ik(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qa(e,t){return $({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Tk(e,t){return qa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wp(e){let t=await ne.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 ne.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Tr(e){for(let t of e){let r=await ne.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Ik(t,r)||await ne.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function jk(e,t,r){let[i,n]=await Promise.all([ne.lstat(e),ne.realpath(e),r?Tr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!qa(i,t)||r&&!Va(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function $k(e,t){let r=$e.resolve(e),i=$e.resolve(t);if(!Va(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Wp(r)],a=$e.relative(r,i).split($e.sep).filter(Boolean),o=r;for(let s of a){await Tr(n),o=$e.join(o,s);try{await ne.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wp(o);if(!Va(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Tr(n),n}async function Ok(e){let t;try{t=await ne.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function zp(e,t,r={}){let i=$e.dirname(e),n=r.containedRoot?await $k(r.containedRoot,i):null;n||await ne.mkdir(i,{recursive:!0});let a=$e.join(i,`.${$e.basename(e)}.${Ak()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await ne.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([ne.lstat(a),ne.realpath(a)]);if(await Tr(n),!l.isFile()||l.isSymbolicLink()||!qa(s,l)||!Va(n[0].realPath,u))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(),c=await o.stat(),!qa(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await jk(a,c,n),await r.beforeCommit?.(),n){await Tr(n);let l=await ne.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Tk(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await La(a,e),await Zc(a)):await Da(a,e),await Ok(i)}catch(l){if(await o?.close(),!n)await ne.rm(a,{force:!0});else try{await Tr(n),await ne.rm(a,{force:!0})}catch{}throw l}}async function Y(e,t,r={}){await zp(e,t,r)}async function Kp(e,t,r={}){await zp(e,t,r)}async function ae(e,t,r={}){await Y(e,JSON.stringify(t,null,2)+`
|
|
174
|
-
`,r)}var
|
|
173
|
+
# 可选值:neutral | strict`}}});function qt(e){return e!==0&&e!==0n&&e!=="0"}function et(e,t){return qt(e.dev)&&qt(t.dev)&&qt(e.ino)&&qt(t.ino)}function H(e,t){let r=qt(e.dev)&&qt(t.dev);if(r&&e.dev!==t.dev)return!1;let n=qt(e.ino)&&qt(t.ino);return n&&e.ino!==t.ino?!1:r&&n?!0:e.birthtime===t.birthtime}var li=S(()=>{"use strict"});import{constants as uo,promises as dr}from"fs";function Tl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Bh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ui(e){return{dev:e.dev,ino:e.ino,birthtime:Tl(e)}}function fo(e,t){let r=ui(e),n=ui(t);return et(r,n)?H(r,n):H(r,n)&&Tl(e)===Tl(t)&&Bh(e)===Bh(t)&&e.size===t.size}async function Gr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=r.label??"file",i=r.bigint===!0,a=await dr.lstat(e,{bigint:i});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Be("too-large",`${n} exceeds ${t} bytes`);let o=await dr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ui(a)});let s=process.platform==="win32"?uo.O_RDONLY:uo.O_RDONLY|uo.O_NOFOLLOW|uo.O_NONBLOCK,c;try{c=await dr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:i}),dr.lstat(e,{bigint:i}),dr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!fo(a,l)||!fo(a,u))throw new Be("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ui(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:k}=await c.read(m,0,Math.min(m.length,y),null);if(k===0)break;if(p+=k,p>t)throw new Be("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:i}),dr.lstat(e,{bigint:i}),dr.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!fo(a,h)||!fo(a,v))throw new Be("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ui(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:w}}finally{await c.close()}}var Be,di=S(()=>{"use strict";li();Be=class extends Error{reason;constructor(t,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=t}}});import{promises as po}from"fs";import Wt from"path";function VS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function jl(e,t){let r=Wt.relative(e,t);return r===""||!Wt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Wt.sep}`)}async function Mh(e,t){let r=Wt.resolve(e),n=await po.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return po.realpath(r)}async function Fh(e,t,r,n){let i=e;for(let a=0;a<r.length;a++){i=Wt.join(i,r[a]);let o;try{o=await po.lstat(i)}catch(u){if(VS(u))return{exists:!1,kind:"missing"};throw u}let s=Wt.relative(e,i).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===r.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 po.realpath(i);if(!jl(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 gt(e,t,r){let n=so(t,r.label),i=Wt.resolve(e),a=await Mh(i,r.label),o=n.split("/"),s=Wt.resolve(i,...o);if(!jl(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Fh(i,a,o,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Z(e,t,r,n){let i=await gt(e,t,{label:n.label,expected:"file"});if(!i.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await Mh(i.projectRoot,n.label);return Gr(i.target,r,{...n,verify:async(o,s)=>{if(!jl(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Fh(i.projectRoot,a,i.relative.split("/"),{label:n.label,expected:"file"})}})}var tt=S(()=>{"use strict";di();Vt()});import{createHash as qS}from"crypto";function $l(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function WS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ho(e,t={}){return(await pi(e,t)).document}async function Vh(e){try{return(await Z(e,fi,oi,{label:fi})).bytes}catch(t){if(WS(t))return null;throw t}}function qh(e){return e?{exists:!0,sha256:qS("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function mo(e){return qh(await Vh(e))}async function pi(e,t={}){let r=await Vh(e);return{document:r?zr(r.toString("utf8"),t):null,identity:qh(r)}}async function fr(e){return(await ho(e))?.config??null}var fi,pr=S(()=>{"use strict";Vt();tt();fi=".comet/config.yaml"});import{promises as Hl}from"node:fs";async function Dl(e,t){let r;for(let n=0;n<=Ol.length;n+=1)try{return await e()}catch(i){r=i;let a=i.code;if(n===Ol.length||!zS.has(a??""))throw i;await new Promise(o=>setTimeout(o,Ol[n]))}throw r}async function vo(e,t){await Dl(()=>Hl.rename(e,t),`rename ${t}`)}async function Ll(e){await Dl(()=>Hl.unlink(e),`unlink ${e}`)}async function go(e,t){await Dl(()=>Hl.link(e,t),`link ${t}`)}var zS,Ol,Bl=S(()=>{"use strict";zS=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Ol=[50,100,200]});import{randomUUID as GS}from"crypto";import{constants as KS,promises as ce}from"fs";import Me from"path";async function Ml(e,t){try{return await go(e,t),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await ce.copyFile(e,t,KS.COPYFILE_EXCL),{linked:!1}}function wo(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function yo(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function JS(e,t){return H(e,yo(t))}function bo(e,t){return H(yo(e),yo(t))}function US(e,t){return bo(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wh(e){let t=await ce.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ce.realpath(e),...yo(t)}}async function Kr(e){for(let t of e){let r=await ce.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!JS(t,r)||await ce.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function YS(e,t,r){let[n,i]=await Promise.all([ce.lstat(e),ce.realpath(e),Kr(r)]);if(!n.isFile()||n.isSymbolicLink()||!bo(n,t)||!wo(r[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return n}async function XS(e,t){let r=Me.resolve(e),n=Me.resolve(t);if(!wo(r,n))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let i=[await Wh(r)],a=Me.relative(r,n).split(Me.sep).filter(Boolean),o=r;for(let s of a){await Kr(i),o=Me.join(o,s);try{await ce.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wh(o);if(!wo(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await Kr(i),i}async function QS(e){let t;try{t=await ce.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function ZS(e,t,r){let n=Me.dirname(e),i=await XS(r.containedRoot,n),a=Me.join(n,`.${Me.basename(e)}.${GS()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await ce.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([ce.lstat(a),ce.realpath(a)]);if(await Kr(i),!l.isFile()||l.isSymbolicLink()||!bo(s,l)||!wo(i[0].realPath,u))throw new Error("Contained 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(),c=await o.stat(),!bo(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await YS(a,c,i),await r.beforeCommit?.(),await Kr(i);let d=await ce.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!US(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await Ml(a,e),await ce.unlink(a)):await vo(a,e),await QS(n)}catch(l){await o?.close();try{await Kr(i),await ce.rm(a,{force:!0})}catch{}throw l}}async function hr(e,t,r){await ZS(e,t,r)}var Jr=S(()=>{"use strict";Bl();li()});var v$,Fl=S(()=>{"use strict";Jr();pr();tt();v$=16*1024});async function Vl(e,t){if(!t)return;let r=await mo(e);if(!$l(r,t))throw new Error("Project config changed before commit; rerun the operation")}var ql=S(()=>{"use strict";Jr();Vt();pr();tt();Fl()});var rt=S(()=>{"use strict";li()});var Jh={};Kw(Jh,{atomicWriteBytes:()=>Kh,atomicWriteJson:()=>ae,atomicWriteText:()=>ee});import{randomUUID as rE}from"crypto";import{promises as le}from"fs";import Fe from"path";function No(e,t){let r=Fe.relative(e,t);return r===""||!Fe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Fe.sep}`)}function nE(e,t){return H({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ko(e,t){return H({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function iE(e,t){return ko(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function zh(e){let t=await le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ur(e){for(let t of e){let r=await le.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!nE(t,r)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function aE(e,t,r){let[n,i]=await Promise.all([le.lstat(e),le.realpath(e),r?Ur(r):Promise.resolve()]);if(!n.isFile()||n.isSymbolicLink()||!ko(n,t)||r&&!No(r[0].realPath,i))throw new Error("Native atomic write temporary file changed after close");return n}async function oE(e,t){let r=Fe.resolve(e),n=Fe.resolve(t);if(!No(r,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let i=[await zh(r)],a=Fe.relative(r,n).split(Fe.sep).filter(Boolean),o=r;for(let s of a){await Ur(i),o=Fe.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await zh(o);if(!No(i[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await Ur(i),i}async function sE(e){let t;try{t=await le.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function Gh(e,t,r={}){let n=Fe.dirname(e),i=r.containedRoot?await oE(r.containedRoot,n):null;i||await le.mkdir(n,{recursive:!0});let a=Fe.join(n,`.${Fe.basename(e)}.${rE()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),i){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Ur(i),!l.isFile()||l.isSymbolicLink()||!ko(s,l)||!No(i[0].realPath,u))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(),c=await o.stat(),!ko(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await aE(a,c,i),await r.beforeCommit?.(),i){await Ur(i);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!iE(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await go(a,e),await Ll(a)):await vo(a,e),await sE(n)}catch(l){if(await o?.close(),!i)await le.rm(a,{force:!0});else try{await Ur(i),await le.rm(a,{force:!0})}catch{}throw l}}async function ee(e,t,r={}){await Gh(e,t,r)}async function Kh(e,t,r={}){await Gh(e,t,r)}async function ae(e,t,r={}){await ee(e,JSON.stringify(t,null,2)+`
|
|
174
|
+
`,r)}var B=S(()=>{"use strict";Bl();rt()});import{existsSync as Uh,promises as wt}from"fs";import P from"path";import cE from"os";async function Wl(e){try{return await wt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uE(e){try{let t=await wt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xr(e,t){let r=P.relative(e,t);return r===""||!P.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${P.sep}`)}async function Yr(e){let t=[],r=e;for(;!await Wl(r);){let i=P.dirname(r);if(i===r)break;t.push(P.basename(r)),r=i}let n=await wt.realpath(r);return P.resolve(n,...t.reverse())}async function zl(e){try{return(await wt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gl(e){let t=P.resolve(e);try{(await wt.stat(t)).isDirectory()||(t=P.dirname(t))}catch(i){if(i.code!=="ENOENT")throw i}let r=t,n=P.resolve(cE.homedir());for(;;){if(!(t===n&&r!==n)){let o=P.join(t,...So.split("/")),s=t===r||await uE(o);if(await Wl(o)&&s)return t}if(await Wl(P.join(t,".git")))return t;let a=P.dirname(t);if(a===t)return r;t=a}}function Kl(e){return ur(e)}async function dE(e,t){let r=Kl(t),n=P.resolve(e,...r.split("/")),i=await wt.realpath(e),a=await Yr(n);if(!Xr(i,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function yt(e,t){let r=Kl(t),n=await dE(e,r),i=P.join(n,"comet");if(await zl(i))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Yr(n),Yr(i)]);if(!Xr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=P.resolve(e),c=P.join(s,".comet","runtime","native");if(await zl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([wt.realpath(s),Yr(c)]);if(!Xr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:P.join(e,...So.split("/")),artifactRoot:n,artifactRootRef:r,nativeRoot:i,specsDir:P.join(i,"specs"),changesDir:P.join(i,"changes"),archiveDir:P.join(i,"archive"),runtimeDir:c,changesRuntimeDir:P.join(c,"changes"),locksDir:P.join(c,"locks"),transactionsDir:P.join(c,"transactions")}}async function Yh(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await j(e.nativeRoot,t),await wt.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await j(e.projectRoot,t),await wt.mkdir(t,{recursive:!0})}))}function Jl(e){if(!lE.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){Jl(t);let r=P.join(e.changesRuntimeDir,t);if(!te(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function fE(e,t){Jl(t);let r=P.join(e.changesDir,t,"runtime");if(!te(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ne(e,t){let r=Ve(e,t);if(Uh(r))return r;let n=fE(e,t);return Uh(n)?n:r}function Xh(e,t){Jl(t);let r=P.join(e.changesDir,t),n=Ne(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:P.join(r,"brief.md"),childrenPath:P.join(r,"children.yaml"),specsDir:P.join(r,"specs"),verificationPath:P.join(r,"verification.md"),statePath:P.join(r,"comet-state.yaml"),runtimeDir:n,runtimeStatePath:P.join(n,"state.json")}}function qe(e,t){let r=P.resolve(t);if(te(e.runtimeDir,r))return e.runtimeDir;if(te(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function te(e,t){return Xr(P.resolve(e),P.resolve(t))}async function j(e,t){let r=P.resolve(e),n=P.resolve(t);if(!Xr(r,n))throw new Error(`Path is outside the Native root: ${t}`);if(await zl(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[i,a]=await Promise.all([Yr(r),Yr(n)]);if(!Xr(i,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var So,lE,L=S(()=>{"use strict";Vt();So=".comet/config.yaml",lE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import pE from"path";function Qh(e="docs",t="en"){return lo(e,t)}async function oe(e){let t=(await ho(e))?.config??null;return t?.native?t:null}async function xo(e){let t=await oe(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 hi(e,t,r={}){let n=await pi(e,{allowPartialProject:!0}),i=ci(n.document?.value??{},t),a=pE.join(e,...So.split("/"));await ee(a,si(i,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Vl(e,n.identity)}})}var Eo,ke=S(()=>{"use strict";Vt();pr();ql();B();L();Eo=co});function OE(e){return e.toLowerCase().startsWith(".env")}function mi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return r.some(n=>OE(n))?"environment-file":r.some(n=>$E.has(n))?"credential-config":r.includes(".git")?"git-metadata":r.some(n=>jE.has(n))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var jE,$E,vi=S(()=>{"use strict";jE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),$E=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as HE}from"node:crypto";import{promises as We}from"node:fs";import _e from"node:path";import{TextDecoder as DE}from"node:util";function Zl(e,t){let r=_e.relative(e,t);return r===""||!_e.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_e.sep}`)}function LE(e){let t=_e.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let a=i.codePointAt(0)??0;return a<=31||a===127})||_e.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 r=e.toLowerCase(),n=mi(e);if(n||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function BE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ME(e,t){return H({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function To(e,t){let r={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return et(r,n)?H(r,n):H(r,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cm(e){let t=await We.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact 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 FE(e,t){let r=_e.resolve(e),n=_e.resolve(t);if(!Zl(r,n))throw new Error("Native artifact path is outside its root");let i=[await cm(r)],a=r;for(let o of _e.relative(r,n).split(_e.sep).filter(Boolean)){a=_e.join(a,o);let s=await cm(a);if(!Zl(i[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);i.push(s)}return i}async function lm(e){for(let t of e){let r=await We.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ME(t,r)||await We.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ue(e){let t=LE(e.ref),r=e.maxBytes===null?null:BE(e.maxBytes??um),n=_e.resolve(e.root,...t.split("/")),i=await FE(e.root,_e.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await We.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await We.realpath(n);if(!Zl(i[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await We.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),We.lstat(n),We.realpath(n)]);if(await lm(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!To(a,c)||!To(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?p.length:r+1-f,E=await s.read(p,0,Math.min(p.length,k),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),We.lstat(n),We.realpath(n)]);if(await lm(i),!h.isFile()||h.isSymbolicLink()||v!==o||!To(c,m)||!To(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(d,f),y;try{y=new DE("utf-8",{fatal:!0}).decode(w)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:e.includeHash===!1?null:HE("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var um,Ae=S(()=>{"use strict";vi();rt();um=1024*1024});import{createHash as VE}from"node:crypto";function ru(e){return e.replaceAll(`\r
|
|
175
175
|
`,`
|
|
176
176
|
`).replaceAll("\r",`
|
|
177
|
-
`)}function
|
|
178
|
-
`),
|
|
177
|
+
`)}function mm(e){return VE("sha256").update(ru(e)).digest("hex")}function nu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new D(`${t} must be an object`);return e}function vm(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new D(`${r} has unknown field(s): ${n.join(", ")}`)}function iu(e,t){if(typeof e!="string"||e.trim().length===0)throw new D(`${t} must be a non-empty string`);return e.trim()}function fm(e,t){if(e!==void 0){if(typeof e!="string")throw new D(`${t} must be text`);return ru(e).replace(/^\n+|\n+$/gu,"")}}function jo(e,t){let r=iu(e,t).toLowerCase();if(!WE.test(r))throw new D(`${t} must be a SHA-256 hash`);return r}function pm(e,t,r){let n=nu(e,t),i=Object.entries(n);if(i.length>dm)throw new D(`${t} must contain at most ${dm} entries`);let a={};for(let[o,s]of i){if(tu(o,`${t} ID`)!==o)throw new D(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=jo(s,`${t}.${o}`)}return a}function tu(e,t){let r=iu(e,t);if(!hm.test(r))throw new D(`${t} is not a valid stable requirement ID`);return r}function zE(e,t){let r=iu(e,t);if(!qE.test(r))throw new D(`${t} is not a valid capability ID`);return r}function GE(e,t){let r=`Native delta operations[${t}]`,n=nu(e,r);vm(n,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let i=tu(n.id,`${r}.id`),a=n.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new D(`${r}.operation is invalid`);let o=a,s=n.to_id===void 0?void 0:tu(n.to_id,`${r}.to_id`),c=fm(n.title,`${r}.title`),l=fm(n.body,`${r}.body`),u=n.expected_hash===void 0?void 0:jo(n.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new D(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new D(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new D(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===i||!u||l==="")throw new D(`${r} rename requires a different to_id and expected_hash`);return{id:i,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function KE(e){let t=nu(e,"Native delta");if(vm(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==eu)throw new D(`Native delta schema must be ${eu}`);let r=zE(t.capability,"Native delta capability"),n=jo(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new D("Native delta base_version must be a positive integer");let i=t.legacy_hash===void 0?void 0:jo(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=pm(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:pm(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new D("Native delta operations must be an array");let s=t.operations.map(GE),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let f of d){if(c.has(f))throw new D(`Native delta operations contain duplicate or overlapping requirement ID ${f} at ${l}`);c.add(f)}}if(o!==void 0){if(a===void 0)throw new D("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new D(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new D(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:eu,capability:r,base_hash:n,base_version:Number(t.base_version),...i===void 0?{}:{legacy_hash:i},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function JE(e){let t=(0,$o.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new D(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Oo(e){return KE(typeof e=="string"?JE(e):e)}function au(e){let t=Oo(e);return(0,$o.stringify)({schema:t.schema,capability:t.capability,base_hash:t.base_hash,base_version:t.base_version,...t.legacy_hash===void 0?{}:{legacy_hash:t.legacy_hash},...t.base_requirements===void 0?{}:{base_requirements:Object.fromEntries(Object.entries(t.base_requirements).sort(([r],[n])=>r.localeCompare(n,"en")))},...t.independent_requirements===void 0?{}:{independent_requirements:Object.fromEntries(Object.entries(t.independent_requirements).sort(([r],[n])=>r.localeCompare(n,"en")))},operations:t.operations.map(r=>({id:r.id,operation:r.operation,...r.to_id===void 0?{}:{to_id:r.to_id},...r.title===void 0?{}:{title:r.title},...r.body===void 0?{}:{body:r.body},...r.expected_hash===void 0?{}:{expected_hash:r.expected_hash}}))})}function UE(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function YE(e){let t=[],r=null;for(let[n,i]of e.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(i.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(i);if(!o)continue;let s=o[3];if(!hm.test(s))throw new D(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:n,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function gm(e){let t=ru(e),r=t.split(`
|
|
178
|
+
`),n=YE(r),i=[],a=new Set;for(let l of n){if(a.has(l.id))throw new D(`Native total Spec contains duplicate requirement ID ${l.id}`);a.add(l.id);let u=r.length;for(let d=l.line+1;d<r.length;d+=1){if(n.some(p=>p.line===d)){u=d;break}let f=UE(r[d]);if(f!==null&&f<=l.level){u=d;break}}i.push({start:l.line,end:u,marker:l})}let o=new Map;for(let l of i){let u=`${r.slice(l.start,l.end).join(`
|
|
179
179
|
`)}${l.end<r.length?`
|
|
180
180
|
`:""}`,d=r.slice(l.start+1,l.end).join(`
|
|
181
|
-
`).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:d,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of
|
|
181
|
+
`).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:d,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of i)s.push(r.slice(c,l.start).join(`
|
|
182
182
|
`)),c=l.end;return s.push(r.slice(c).join(`
|
|
183
183
|
`)),{text:t,lines:r,requirements:o,legacyText:s.join(`
|
|
184
|
-
`)}}function
|
|
184
|
+
`)}}function zt(e){return mm(e)}function Ho(e){let t=gm(e).legacyText;return mm(t.split(`
|
|
185
185
|
`).filter(r=>r.trim().length>0).join(`
|
|
186
|
-
`).trim())}function
|
|
187
|
-
${Hl(t)}`).digest("hex")}var K=S(()=>{"use strict"});var co,Dl=S(()=>{"use strict";co=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});var tn=S(()=>{"use strict"});var lo=S(()=>{"use strict";Dl();tn()});var uo,ir=S(()=>{"use strict";K();lo();uo=3});import{promises as WE}from"node:fs";function le(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ue(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function G(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Ml(e,t){return e===null?null:G(e,t)}function Fl(e,t){let r=G(e,t);if(!JE.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function qr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function B(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function YE(e,t){return e===null?null:B(e,t,Number.MIN_SAFE_INTEGER)}function F(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ue(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function go(e,t){return Ue(e,t,(r,i)=>G(r,`${t}[${i}]`))}function lr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Wr(e,t){let r=G(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function mo(e,t,r=!1){let i=G(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Ce(e,t){let r=le(e,t);return ue(r,new Set(["text","truncated"]),t),{text:G(r.text,`${t}.text`,{empty:!0}),truncated:qr(r.truncated,`${t}.truncated`)}}function XE(e,t){let r=`Native spec_changes[${t}]`,i=le(e,r);ue(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=G(i.capability,`${r}.capability`);if(!KE.test(n))throw new Error(`${r}.capability is invalid`);let a=F(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:mo(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:mo(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:Fl(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function QE(e){let t="Native workspace",r=le(e,t);ue(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=F(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ml(r.change_branch,`${t}.change_branch`),a=Ml(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:F(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function ZE(e){let t="Native loop",r=le(e,t);ue(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=go(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);lr(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:F(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:F(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:B(r.goal_cycle,`${t}.goal_cycle`,1),iteration:B(r.iteration,`${t}.iteration`),attempt:B(r.attempt,`${t}.attempt`),retry_epoch:B(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:B(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:B(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:B(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Ml(r.next_action,`${t}.next_action`)}}function ex(e,t){let r=`Native acceptance[${t}]`,i=le(e,r);ue(i,new Set(["id","source","text","result","reason"]),r);let n=G(i.id,`${r}.id`);if(!GE.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:mo(i.source,`${r}.source`),text:G(i.text,`${r}.text`),result:F(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ce(i.reason,`${r}.reason`)}}function tx(e,t){let r=`Native builder_handoff.checks[${t}]`,i=le(e,r);return ue(i,new Set(["name","result","note"]),r),{name:Ce(i.name,`${r}.name`),result:F(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ce(i.note,`${r}.note`)}}function rx(e){let t="Native builder_handoff",r=le(e,t);ue(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=go(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);lr(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:le(r.review,`${t}.review`);return n&&ue(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:G(r.candidate_id,`${t}.candidate_id`),identity_provider:G(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:G(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:B(r.iteration,`${t}.iteration`,1),summary:Ce(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ue(r.checks,`${t}.checks`,tx),checks_truncated:qr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ue(r.known_limits,`${t}.known_limits`,(a,o)=>Ce(a,`${t}.known_limits[${o}]`)),known_limits_truncated:qr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:F(n.status,["passed"],`${t}.review.status`),summary:Ce(n.summary,`${t}.review.summary`),reviewer_execution_ref:G(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Wr(r.submitted_at,`${t}.submitted_at`)}}function ix(e,t){let r=`Native blockers[${t}]`,i=le(e,r);ue(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=go(i.acceptance_ids,`${r}.acceptance_ids`);return lr(n,`${r}.acceptance_ids`),{owner:F(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ce(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:F(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function nx(e,t){let r=`Native verification.checks[${t}]`,i=le(e,r);return ue(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:G(i.id,`${r}.id`),name:Ce(i.name,`${r}.name`),argv_display:Ue(i.argv_display,`${r}.argv_display`,(n,a)=>Ce(n,`${r}.argv_display[${a}]`)),argv_truncated:qr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:mo(i.cwd_ref,`${r}.cwd_ref`,!0),status:F(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:YE(i.exit_code,`${r}.exit_code`),duration_ms:B(i.duration_ms,`${r}.duration_ms`)}}function ax(e){let t="Native verification",r=le(e,t);ue(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ue(r.checks,`${t}.checks`,nx);lr(i.map(a=>a.id),`${t}.checks IDs`);let n=G(r.identity_provider,`${t}.identity_provider`);return{candidate_id:G(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:G(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:B(r.iteration,`${t}.iteration`,1),attempt:B(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":F(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:F(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ce(r.summary,`${t}.summary`),risks:Ue(r.risks,`${t}.risks`,(a,o)=>Ce(a,`${t}.risks[${o}]`)),risks_truncated:qr(r.risks_truncated,`${t}.risks_truncated`),completed_at:Wr(r.completed_at,`${t}.completed_at`)}}function ox(e,t){let r=`Native history[${t}]`,i=le(e,r);ue(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=go(i.unresolved_ids,`${r}.unresolved_ids`);return lr(n,`${r}.unresolved_ids`),{goal_cycle:B(i.goal_cycle,`${r}.goal_cycle`,1),iteration:B(i.iteration,`${r}.iteration`),attempt:B(i.attempt,`${r}.attempt`),outcome:F(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ce(i.summary,`${r}.summary`),completed_at:Wr(i.completed_at,`${r}.completed_at`)}}function sx(e){let t="Native history_overflow.outcome_counts",r=le(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ue(r,new Set(i),t),{pass:B(r.pass,`${t}.pass`),fail:B(r.fail,`${t}.fail`),blocked:B(r.blocked,`${t}.blocked`),"execution-error":B(r["execution-error"],`${t}.execution-error`),recovery:B(r.recovery,`${t}.recovery`)}}function cx(e){let t="Native history_overflow",r=le(e,t);ue(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=B(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Wr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Wr(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=sx(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function lx(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(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.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}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 i=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(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function ux(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 r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);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(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.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 zr(e){let t=le(e,"Native portable state");if(ue(t,UE,"Native portable state"),t.schema!==Lr)throw new Error(`Native portable state schema must be ${Lr}`);let r=G(t.name,"Native state name");if(!zE.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ue(t.spec_changes,"Native spec_changes",XE);lr(i.map(s=>s.capability),"Native spec change capabilities");let n=Ue(t.acceptance,"Native acceptance",ex);lr(n.map(s=>s.id),"Native acceptance IDs");let a=Ue(t.history,"Native history",ox);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Lr,name:r,language:F(t.language,["en","zh-CN"],"Native state language"),phase:F(t.phase,["shape","build","verify","archive"],"Native state phase"),status:F(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:B(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1?{document_constraints_version:1}:(()=>{throw new Error("Native document_constraints_version must be 1")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Fl(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Fl(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:F(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:QE(t.workspace),loop:ZE(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:rx(t.builder_handoff),blockers:Ue(t.blockers,"Native blockers",ix),verification:t.verification===null?null:ax(t.verification),history:a,history_overflow:cx(t.history_overflow),verification_result:F(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:F(t.verification_report,["verification.md"],"Native verification_report"),archived:qr(t.archived,"Native archived"),created_at:Wr(t.created_at,"Native created_at")};return lx(o),ux(o),o}function im(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return zr({schema:Lr,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:$l(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function dx(e,t){let r=(0,vo.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Vl(e){let t=await WE.readFile(e,"utf8");return zr(dx(t,"Native portable state"))}async function nm(e,t,r={}){let i=zr(t);await Y(e,(0,vo.stringify)(i),r)}var vo,zE,KE,GE,JE,UE,Bt=S(()=>{"use strict";vo=Nt(nt(),1);D();en();zE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,KE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GE=/^A[1-9][0-9]*$/u,JE=/^[a-f0-9]{64}$/u,UE=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"])});function vx(e,t){return Kl[e][t]}function sn(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${vx(e,r)}
|
|
188
|
-
|
|
189
|
-
`
|
|
190
|
-
`,"utf8"),await r.sync(),i=bm(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Be(e);if(!i||!n||n.owner.id!==t.id||!So(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function Bx(e,t){let r=await T(e.runtimeDir,e.locksDir);await Pe.mkdir(r,{recursive:!0});let i=await T(e.runtimeDir,L.join(r,Zl));await Pe.mkdir(i,{recursive:!0});let n=await km(t),a=L.join(i,`.${n.id}.tmp`),o=L.join(i,`${n.id}.claim`);try{let s=await Sm(a,n);await Pe.rename(a,o);let c=await Be(o);if(!c||!So(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Pe.rm(a,{force:!0})}}async function Mx(e){let t=L.dirname(e.file),r=!1,i=L.basename(e.file);for(let n of await Pe.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=L.join(t,n.name);if(L.resolve(a)!==L.resolve(e.file))try{let o=await Be(a),s=await eu(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await xo(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Em(e){let t=await Be(e.file);if(t){if(t.owner.id!==e.owner.id||!Eo(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await xo(t,L.dirname(e.file))}}async function Fx(e,t){let r=Date.now()+Tx;for(;;){let i=await Bx(e,t);if(!await Mx(i))return i;if(await Em(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Vx(e){let t=ko.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return ko.set(e,n),await t,()=>{r(),ko.get(e)===n&&ko.delete(e)}}async function Co(e,t,r){let i=L.resolve(e.locksDir),n=wm.getStore();if(n?.has(i))return r();let a=await Vx(i);try{let o=await Fx(e,t),s=new Map(n??[]);return s.set(i,o),await wm.run(s,async()=>{try{return await r()}finally{await Em(o)}})}finally{a()}}async function xm(e,t,r){let i=[...new Map(e.map(a=>[L.resolve(a.locksDir),a])).values()].sort((a,o)=>L.resolve(a.locksDir).localeCompare(L.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Co(o,t,()=>n(a+1)):r()};return n(0)}async function Po(e,t,r){return Co(e,`acquire ${t}`,async()=>{let i=await T(e.runtimeDir,e.locksDir);await Pe.mkdir(i,{recursive:!0});let n=await T(e.runtimeDir,L.join(i,$x(t))),a=await km(r),o=await Sm(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Ro(e){await Be(e.file)&&await Co({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${L.basename(e.file)}`,async()=>{let t=await Be(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Eo(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=L.join(e.locksDir,Zl);await xo(t,r)})}function qx(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function Cm(e){return eu(await Be(e))}async function Pm(e,t,r,i={}){return Co(e,`take over ${L.basename(t)}`,async()=>{let n=await T(e.runtimeDir,e.locksDir),a=await T(e.runtimeDir,t);if(L.resolve(L.dirname(a))!==L.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await Be(a),s=await eu(o);if(s.status==="missing")return{status:"missing"};if(r&&!Hx(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&qx(o?.owner??null)>=jx;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=L.join(n,Zl);return await xo(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var gm,Zl,Tx,jx,wm,ko,un=S(()=>{"use strict";qi();bo();H();Ge();gm=16*1024,Zl=".coordinator",Tx=5e3,jx=900*1e3,wm=new Ix,ko=new Map});var Xe,pt,ht,dn=S(()=>{"use strict";Xe="comet.native.v3",pt="comet.native.v2",ht="comet.native.v1"});import Wx from"node:path";function pn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Im(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Gr(e){if(!Am.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Tm(e){if(!Am.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function jm(e,t){if(e.length===0||Wx.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Qx(e,t){let r=pn(e,`spec_changes[${t}]`);if(Im(r,Gx,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Tm(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&jm(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!ru.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!ru.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function Zx(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 iu(e,t){if(Im(e,t,Me),typeof e.name!="string")throw new Error("Native change name is required");if(Gr(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"||!Jx.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&&!Ux.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 r=e.spec_changes.map(Qx),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!Yx.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"&&jm(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Zx(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:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function hn(e){let t=pn(e,Me);if(t.schema!==ht)throw new Error(`Expected ${ht}`);return{schema:ht,...iu(t,zx)}}function fn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function tu(e,t,r){if(e===null)return null;let i=typeof e=="string"?Xx.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function eC(e){if(e==null)return null;if(typeof e!="string"||!ru.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function tC(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 mn(e){let t=pn(e,Me);if(t.schema!==pt)throw new Error(`Expected ${pt}`);if(fn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${pt} minimum_runtime_version must be 2`);return{schema:pt,minimum_runtime_version:2,revision:fn(t.revision,"Native v2 revision"),...iu(t,_m)}}function Jr(e){let t=pn(e,Me);if(t.schema!==Xe){if(t.schema===ht||t.schema===pt){let o=t.schema===ht?hn(t):mn(t);throw new Kr(o.name,o.schema)}throw new vt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=fn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new vt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=fn(t.revision,"Native revision"),n=iu(t,Kx),a=eC(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Xe,minimum_runtime_version:3,revision:i,verification_protocol:tC(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:tu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:tu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:tu(t.partial_allowance,"Native partial_allowance","allowances")}}function _o(e){let t=pn(e,Me);if(t.schema===ht){let n=hn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Xe}`}}if(t.schema===pt){let n=mn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Xe}`}}if(t.schema!==Xe){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 vt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=fn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new vt(t.schema,r).message};let i=Jr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Rm,zx,_m,Kx,Gx,Jx,Ux,Yx,Me,ru,Am,Xx,Kr,vt,Ao=S(()=>{"use strict";dn();Rm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],zx=new Set(Rm),_m=new Set([...Rm,"minimum_runtime_version","revision"]),Kx=new Set([..._m,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Gx=new Set(["capability","operation","source","base_hash"]),Jx=new Set(["shape","build","verify","archive"]),Ux=new Set(["implicit","confirmed"]),Yx=new Set(["pending","pass","fail"]),Me="comet-state.yaml",ru=/^[a-f0-9]{64}$/u,Am=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xx=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Kr=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},vt=class extends Error{constructor(r,i){super(r!==Xe||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});var u$,$m,Io=S(()=>{"use strict";dr();K();u$=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),$m=Object.freeze({maxCriteria:1024})});var nu=S(()=>{"use strict";Io()});var fr=S(()=>{"use strict"});function uC(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function dC(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Hm(e){let t=uC(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!aC.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Om)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!sC.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!oC.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!lC.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!cC.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Om,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:dC(t.createdAt,"Native portable migration transaction createdAt")}}var Om,aC,oC,sC,cC,lC,Dm=S(()=>{"use strict";Ao();nu();Bt();fr();en();dn();Om="comet.native.portable-migration.v1",aC=new Set(["schema","id","change","fromSchema","status","createdAt"]),oC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sC=/^[a-z0-9][a-z0-9-]{7,127}$/u,cC=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),lC=new Set([ht,pt,Xe])});import fC from"node:path";function Vm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qm(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function au(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function Bm(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function NC(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Vm(e,r);if(qm(i,yC,r),typeof i.capability!="string"||!Fm.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(f=>f==="."||f==="..")))throw new Error(`${r}.delta_source is invalid`);let o=au(i.base_hash,`${r}.base_hash`),s=Bm(i.delta_content,`${r}.delta_content`),c=Bm(i.source_content,`${r}.source_content`),l=au(i.expected_target_hash,`${r}.expected_target_hash`),u=au(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=ro(s);if(f.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(f.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(Ot(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Ot(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(f=>f==="."||f===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||Ot(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function bC(e){let t=Vm(e,"Native portable Archive transaction");if(qm(t,wC,"Native portable Archive transaction"),t.schema!==Lm)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!mC.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Fm.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"||!vC.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"||!gC.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 r=t.spec_changes.map(NC);if(new Set(r.map(({capability:n})=>n)).size!==r.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)>r.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 i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Lm,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:r,created_at:t.created_at}}function ou(e){let t=pC.exec(e);if(t)return{kind:"archive",change:t[1]};let r=hC.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Wm(e,t){let r=ou(t);if(!r)return null;let i=await oe({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=fC.join(e.transactionsDir,t);if(r.kind==="archive"){let s=bC(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Hm(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function zm(e){return e.kind==="archive"||e.journal.status!=="committed"}var Lm,Mm,pC,hC,mC,vC,gC,wC,yC,Fm,su=S(()=>{"use strict";xe();no();Dm();Lm="comet.native.archive-transaction.v4",Mm="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",pC=new RegExp(`^portable-archive-(${Mm})\\.json$`,"u"),hC=new RegExp(`^portable-migration-(${Mm})\\.json$`,"u"),mC=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vC=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gC=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),wC=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),yC=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Fm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as kC}from"node:crypto";import{constants as To,promises as be}from"node:fs";import Fe from"node:path";import{TextDecoder as SC}from"node:util";function $o(e,t){let r=Fe.relative(e,t);return r===""||!Fe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Fe.sep}`)}function Km(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function EC(e,t){return $({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xC(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function jo(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 cu(e,t){let r=await be.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await be.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Gm(e,t,r){let i=Fe.resolve(e),n=Fe.resolve(t);if(!$o(i,n))throw new Error(`${r} is outside its managed root`);let a=[await cu(i,r)],o=i;for(let s of Fe.relative(i,n).split(Fe.sep).filter(Boolean)){await gt(a,r),o=Fe.join(o,s);let c=await cu(o,r);if(!$o(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await gt(a,r),a}async function gt(e,t){for(let r of e){let i=await be.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!EC(r,i)||await be.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function CC(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Ur(e){let t=e.maxBytes===null?null:Km(e.maxBytes),r=Fe.resolve(e.file),i=await Gm(e.root,Fe.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>cu(Fe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await gt(i,e.label);let a=await be.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=xC(a),s=await be.realpath(r);if(!$o(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>$o(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?To.O_RDONLY:To.O_RDONLY|To.O_NOFOLLOW|To.O_NONBLOCK,l=await be.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([be.lstat(r),be.realpath(r)]);if(await gt(i,e.label),await gt(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!jo(o,u)||!jo(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await CC(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),be.lstat(r),be.realpath(r)]);if(await gt(i,e.label),await gt(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!jo(o,m)||!jo(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:kC("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Jm(e){let t=await Ur(e),r;try{r=new SC("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function gn(e){let t=await Gm(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await be.readdir(e.directory,{withFileTypes:!0});else{let i=Km(e.maxEntries);r=[];let n=await be.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await gt(t,e.label),{entries:r,verify:()=>gt(t,e.label)}}var Qe=S(()=>{"use strict";D();Ge()});import wt from"path";import{TextDecoder as RC}from"util";function Ho(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Do(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Qm(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function lu(e,t){if(typeof e!="string"||e.length===0||wt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Oo(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Um(e,t){if(lu(e,t),e.includes("\\")||e!==wt.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 $C(e,t){let r=Ho(e,`transaction operations[${t}]`);if(Do(r,AC,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);lu(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&lu(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Zm(e){let t=Ho(e,"Native Archive transaction journal");if(Do(t,IC,"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"||!Xm.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(!Qm(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Oo(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 r=t.operations.map((s,c)=>{let l=Ho(s,`Archive transaction operations[${c}]`);if(Do(l,TC,`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`);Um(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Um(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Oo(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(Oo(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`);Oo(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.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)||r.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 r.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:r}}function OC(e){let t=Ho(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Zm(t);if(Do(t,_C,"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"||!Xm.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!wt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!wt.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(!Qm(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 r=t.operations.map($C),i=r.map(n=>n.id);if(new Set(i).size!==i.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:r}}function HC(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return wt.join(e.transactionsDir,t)}function ev(e,t){let r=HC(e,t);return{directory:r,journal:wt.join(r,"transaction.json"),events:wt.join(r,"events.jsonl"),staged:wt.join(r,"staged"),backups:wt.join(r,"backups")}}async function uu(e,t){let r=ev(e,t);return await Promise.all(Object.values(r).map(i=>T(e.runtimeDir,i))),r}async function du(e,t,r={}){let i=await uu(e,t),n=await Ur({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(jC.decode(n.bytes)),o=OC(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var _C,AC,IC,TC,Xm,jC,Lo=S(()=>{"use strict";D();H();Qe();_C=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),AC=new Set(["id","type","source","target","staged","backup"]),IC=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),TC=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Xm=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),jC=new RC("utf-8",{fatal:!0})});import{promises as DC}from"fs";import LC from"path";async function BC(e,t,r){let i;try{i=await DC.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 a=await du(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(ou(n.name))try{let a=await Wm(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(zm(a))return!0}catch{return!0}return!1}async function MC(e,t){let r=Date.now()+5e3,i=LC.join(e.locksDir,"root-move.lock");for(;;)try{return await Po(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Cm(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Pm(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function J(e,t,r,i){let n=await MC(e,t);try{if(await Ka(e.projectRoot),await BC(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Ro(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
|
|
191
|
-
`)
|
|
192
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function fu(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function lP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function tv(e){let t=za(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?lP(n):void 0;if(a&&!a())return!1;let o=fu(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[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=fu(r,c,a),o===null||o.size===0)return!1}return fu(r,o,a)?.has(r.length)??!1}}function uP(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>za(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>za(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=cP(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(tv),excludeMatchers:r.map(tv),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Re(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _e(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Xr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function et(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function nv(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 r=pu.posix.normalize(e);if(r!==e||pu.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function dP(e,t){let r=Re(e,`Native snapshot entry ${t}`);_e(r,eP,`Native snapshot entry ${t}`);let i=nv(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Mo.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:et(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!oP.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function fP(e,t){let r=Re(e,`Native snapshot omission ${t}`);if(_e(r,tP,`Native snapshot omission ${t}`),!nP.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!aP.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:nv(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:et(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function pP(e){let t=Re(e,"Native snapshot omission overflow");if(_e(t,rP,"Native snapshot omission overflow"),typeof t.hash!="string"||!Mo.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Xr(t.count,"Native snapshot omission overflow count")}}function Yr(e,t){let r=Re(e,t);if(_e(r,XC,t),typeof r.hash!="string"||!Mo.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=et(r.recordCount,`${t} recordCount`),n=et(r.storedRecordCount,`${t} storedRecordCount`),a=et(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function rv(e){let t=Re(e,"Native Git selection evidence");if(_e(t,YC,"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 r=Yr(t.stageBefore,"Native Git selection stageBefore"),i=Yr(t.combined,"Native Git selection combined"),n=Yr(t.stageAfter,"Native Git selection stageAfter"),a=Yr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Yr(t.finalCombined,"Native Git selection finalCombined"),s=Yr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Bo(r,n)||!Bo(n,a)||!Bo(i,o)||!Bo(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:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function iv(e,t){let r=Re(e,t);if(_e(r,ZC,t),typeof r.hash!="string"||!Mo.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=et(r.visitedNodeCount,`${t} visitedNodeCount`),n=et(r.recordCount,`${t} recordCount`),a=et(r.storedRecordCount,`${t} storedRecordCount`),o=et(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function hP(e){let t=Re(e,"Native physical selection evidence");if(_e(t,QC,"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 r=iv(t.before,"Native physical selection before"),i=iv(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!sP(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function av(e){let t=Re(e,"Native content snapshot manifest");if(_e(t,zC,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!iP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let g=Re(t.capture,"Native content snapshot capture");if(_e(g,JC,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=g.gitSelection===void 0?void 0:rv(g.gitSelection),N=g.physicalSelection===void 0?void 0:hP(g.physicalSelection),I=null;if(g.projection!==void 0){let Z=Re(g.projection,"Native content snapshot projection");if(_e(Z,UC,"Native content snapshot projection"),Z.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");I={provider:"git",...Z.selection===void 0?{}:{selection:rv(Z.selection)}}}if(g.provider==="git"){if(N||I)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&I)throw new Error("Native physical-tree capture cannot combine selection and projection");r=I?{provider:"physical-tree",projection:I}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}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 i=Re(t.limits,"Native content snapshot limits");_e(i,KC,"Native content snapshot limits");let n={maxFiles:Xr(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Xr(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Xr(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Xr(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Xr(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let g=Re(t.policy,"Native snapshot policy");if(_e(g,GC,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=uP({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(dP),s=t.omitted.map(fP),c=et(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:pP(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>n.maxFileBytes)||o.reduce((g,R)=>g+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>qC||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(g=>g.reason==="git-enumeration-limit"),f=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...f])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(g=>g.reason==="physical-enumeration-limit"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=r?.physicalSelection,k=y?.status==="overflow"||y?.status==="overflow-and-changed",E=y?.status==="changed"||y?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}function mP(e,t){if(!WC.test(t))throw new Error(`Invalid Native change name: ${t}`);return pu.join(ge(e,t),"baseline-manifest.json")}async function ov(e,t){let r=mP(e,t),i=He(e,r);await T(i,r);try{let n=await Jm({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return av(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var cO,qC,WC,zC,KC,GC,JC,UC,YC,XC,QC,ZC,eP,tP,rP,iP,nP,aP,Mo,oP,lO,uO,dO,fO,pO,wn=S(()=>{"use strict";D();we();Ze();Ge();H();Qe();Ji();cO={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},qC=1e3,WC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),KC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),GC=new Set(["schema","include","exclude","hash"]),JC=new Set(["provider","gitSelection","physicalSelection","projection"]),UC=new Set(["provider","selection"]),YC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),XC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),QC=new Set(["schema","status","before","after"]),ZC=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),eP=new Set(["path","hash","size","type","gitObjectId"]),tP=new Set(["path","size","type","reason"]),rP=new Set(["ref","hash","count"]),iP=new Set(["change-created","legacy-migration","explicit"]),nP=new Set(["file","directory","other"]),aP=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"]),Mo=/^[a-f0-9]{64}$/u,oP=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,lO=64*1024,uO=64*1024,dO={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},fO={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};pO=(1n<<256n)-1n});var ZP,Yo=S(()=>{"use strict";ZP=Nt(nt(),1);xe()});var Wt=S(()=>{"use strict";D();K();Yo();H();ir()});var xu=S(()=>{"use strict"});var pr=S(()=>{"use strict"});var Xo=S(()=>{"use strict";wo();xu();pr()});var xv=S(()=>{"use strict";Je();Xo();K()});import{createHash as oR}from"node:crypto";import{lstatSync as pD,readFileSync as hD,promises as Cv}from"node:fs";import Cu from"node:path";async function Qo(e){let t=Cu.join(e,sR),r;try{r=await Cv.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=cR(e);await Cv.mkdir(Cu.dirname(i),{recursive:!0}),await ae(i,{hash:lR(r)},{containedRoot:e})}var sR,cR,lR,Zo=S(()=>{"use strict";Je();D();sR=".comet/config.yaml",cR=e=>Cu.join(e,".comet","runtime","native","workspace-config.json"),lR=e=>oR("sha256").update(e).digest("hex")});var $v,ii=S(()=>{"use strict";K();wn();$v=1024*1024});var ts=S(()=>{"use strict";K();pr();Ji();ii()});var Hv,IR,TR,jR,hB,$R,mB,_u=S(()=>{"use strict";K();Hv="scoped-text-safety",IR=1,TR=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),jR="comet.native.checker-policy.v1",hB=z(jR,{policy:Hv,version:IR,limits:TR,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),$R=["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"],mB=new Set($R)});var rs=S(()=>{"use strict";K();_u();pr()});var DR,TB,ni=S(()=>{"use strict";D();H();Ge();ii();ts();rs();DR=$v,TB=3*DR});we();D();import{promises as B_}from"node:fs";import cs from"node:path";var pl=Nt(nt(),1);st();import{createHash as zk}from"node:crypto";import Kk from"node:path";var ul={strong:8,phrase:8,weak:12},Qp=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" ")),Ua=new Set(["请","帮我","一下","这个","进行","实现","需要","如何"]);function Ya(e,t=2e3){return[...e].map(r=>{let i=r.codePointAt(0)??0;return i<32||i===127?" ":r}).join("").replace(/\s+/gu," ").trim().slice(0,t)}function Vk(e){if(!e)return;let t=Ya(e,512).replaceAll("\\","/");if(!(!t||t.startsWith("/")||/^[A-Za-z]:\//u.test(t)||t.split("/").includes("..")))return t}function dl(e){return e.replace(/(^|[\s([{"'])(?:[A-Za-z]:[\\/]|\\\\)[^\s)\]}>,;"']+/gu,"$1").replace(/(^|[\s([{"',;:])\/(?!\/)[^\s)\]}>,;"']+/gu,"$1").replace(/\s+/gu," ").trim()}function ye(e,t){let r=t.trim();r.length<2||e.includes(r)||e.push(r)}function Ga(e,t,r){let i=[],n=[],a=new Intl.Segmenter("zh",{granularity:"word"});for(let o of r.matchAll(/[\u3400-\u9fff]{2,}/gu)){let s=o[0];if(Ua.has(s))continue;ye(e,s);let c="";for(let{segment:l,isWordLike:u}of a.segment(s))u&&!Ua.has(l)&&ye(t,l),u&&l.length===1&&!"的和与给为在对及".includes(l)?(c&&ye(n,c+l),c=l):c="";for(let l=Math.min(4,s.length);l>=2;l-=1)for(let u=0;u+l<=s.length;u+=l){let d=s.slice(u,u+l);!Ua.has(d)&&d!==s&&ye(i,d)}}for(let o of n)ye(t,o);for(let o of i)ye(t,o)}function Ja(e,t,r){for(let i of r.matchAll(/[A-Za-z][A-Za-z0-9_./:-]*/gu)){let n=i[0].replace(/^[./:]+|[./:]+$/gu,"");if(!n)continue;let a=n.toLowerCase();if(!Qp.has(a)&&(ye(qk(n)?e:t,n),n.includes("/")))for(let o of n.split(/[/:.]/u))ye(t,o)}for(let i of r.matchAll(/\b\d+(?:\.\d+)?\b/gu))ye(e,i[0])}function qk(e){return e.includes("/")||e.includes("\\")||e.includes("_")||/[a-z][A-Z]/u.test(e)||/[A-Z]{2,}/u.test(e)||/[A-Za-z][A-Za-z0-9]*\d[A-Za-z0-9]*/u.test(e)||/\d{2,}/u.test(e)||/(?:^|[^A-Za-z0-9])[A-Za-z0-9]+\.[A-Za-z0-9]+(?:$|[^A-Za-z0-9])/u.test(e)}function Wk(e){return e.length>256||!/\s/u.test(e)?void 0:e.split(/\s+/u).filter(r=>{let i=r.toLowerCase();return r.length>=2&&!Qp.has(i)&&!Ua.has(r)}).length>=2?e:void 0}function Zp(e){let t=Ya(e.task);if(!t)throw new Error("Project knowledge task must not be empty");let r=Vk(e.path),i=e.phase?Ya(e.phase,128):void 0,n=e.operation?Ya(e.operation,128):void 0,a=[],o=[],s=[],c=[],l=[];Ja(a,c,t),Ga(o,l,t);for(let v=0;v<Math.max(c.length,l.length);v++)c[v]&&ye(s,c[v]),l[v]&&ye(s,l[v]);r&&(ye(a,r),Ja(a,s,r),Ga(o,s,r)),i&&(Ja(a,s,i),Ga(o,s,i)),n&&(Ja(a,s,n),Ga(o,s,n));let u=Wk(t);u&&ye(o,u);let d=a.slice(0,ul.strong),f=o.slice(0,ul.phrase),p=s.filter(v=>!d.includes(v)&&!f.includes(v)).slice(0,ul.weak),m=[...d,...f,...p],h=[dl(t),...r?[`Target path: ${r}`]:[],...i?[`Phase: ${dl(i)}`]:[],...n?[`Operation: ${dl(n)}`]:[]].join(`
|
|
193
|
-
`)
|
|
186
|
+
`).trim())}function ou(e){let t=gm(e);return{legacy_hash:Ho(e),requirements:[...t.requirements.values()].map(r=>({...r}))}}var $o,eu,qE,hm,WE,dm,D,Do=S(()=>{"use strict";$o=At(mt(),1),eu="comet.native.delta.v1",qE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hm=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,WE=/^[a-f0-9]{64}$/iu,dm=512,D=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}}});import{AsyncLocalStorage as XE}from"node:async_hooks";import{performance as Lo}from"node:perf_hooks";function su(e=0){QE+=1,ZE+=e;let t=ex.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function gi(e){let t=Lo.now();try{return e()}finally{su(Lo.now()-t)}}async function cu(e){let t=Lo.now();try{return await e()}finally{su(Lo.now()-t)}}var QE,ZE,ex,Qr=S(()=>{"use strict";QE=0,ZE=0,ex=new XE});import{execFileSync as tx}from"node:child_process";function ix(e,t){try{return gi(()=>tx("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:rx,maxBuffer:nx,windowsHide:!0}))}catch(r){let n=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new lu(e,t,n)}}function re(e,t){return ix(e,t).trim()}function uu(e){return re(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function du(e,t){re(e,["check-ref-format","--branch",t])}var rx,nx,lu,ze=S(()=>{"use strict";Qr();rx=3e4,nx=8*1024*1024,lu=class extends Error{constructor(r,n,i){super(`git ${n.join(" ")} failed${i?`: ${i}`:""}`);this.cwd=r;this.args=n;this.stderr=i;this.name="GitCommandError"}cwd;args;stderr}});function Nu(){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 rn,ki,Gm,Si=S(()=>{"use strict";rn="comet.native.v4",ki="comet.native.local-execution.v4",Gm=["multi-session","single-session"]});import{createHash as Zx}from"crypto";function Ge(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function eC(e,t){t.has(e)&&Ge("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||Ge("sparse arrays are not supported");return(r.length!==e.length||r.some((n,i)=>n!==String(i)))&&Ge("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ge("symbol properties are not supported"),`[${e.map(n=>ku(n,t)).join(",")}]`}finally{t.delete(e)}}function tC(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Ge("only plain objects are supported"),t.has(e)&&Ge("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ge("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))&&Ge("accessor properties are not supported"),`${JSON.stringify(o)}:${ku(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ku(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)||Ge("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?eC(e,t):tC(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ge(`${typeof e} values are not supported`)}return Ge("unsupported value type")}function Su(e){return ku(e,new Set)}function K(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 Zx("sha256").update(`${e}
|
|
187
|
+
${Su(t)}`).digest("hex")}var J=S(()=>{"use strict"});function Eu(e,t,r,n=""){let i=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=i.filter(s=>!t.includes(s));if(a.length||o.length)throw new Ei({code:"invalid-fields",path:n,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var Ei,Vo=S(()=>{"use strict";Ei=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});var xi=S(()=>{"use strict"});var qo=S(()=>{"use strict";Vo();xi()});var Wo,mr=S(()=>{"use strict";J();qo();Wo=3});import{existsSync as dC}from"node:fs";import Ci from"node:path";function Qm(e,t){let r=t.toLowerCase();return Object.entries(e).find(([n,i])=>n.toLowerCase()===r&&i!==void 0)?.[1]}function pC(e){let t=(Qm(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function hC(e,t,r){let i=Ci.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Qm(t,"PATH")??"").split(Ci.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ci.win32.extname(e)?[e]:pC(t).map(s=>`${e}${s}`);return i.flatMap(s=>o.map(c=>s?Ci.join(s,c):Ci.resolve(r,c)))}function Go(e,t,r){return hC(e,t,r).find(n=>dC(n))??e}function xu(e){if(e.some(t=>fC.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var fC,X0,Pi=S(()=>{"use strict";fC=/[&|<>()^%"!\r\n]/u,X0=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFile as mC,execFileSync as eO}from"node:child_process";import Zm from"node:path";async function Kt(e,t,r={}){let n=r.timeoutMs??vC,i=r.maxBufferBytes??gC;if(!Number.isSafeInteger(n)||n<1||!Number.isSafeInteger(i)||i<1)throw new Error("External command limits must be positive integers");let a=Zm.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Go(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&xu(t);let l=()=>new Promise((u,d)=>{let f=!1,p=mC(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:i,windowsHide:!0,shell:c},(w,y,k)=>{f||(f=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),w?d(new Ri(e,t,k.trim(),{cause:w,timedOut:wC(w)})):u(y))}),m=w=>{f||(f=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),p.kill("SIGKILL"),p.stdin?.destroy(),p.stdout?.destroy(),p.stderr?.destroy(),p.unref(),d(new Ri(e,t,"",{timedOut:w})))},h=()=>m(!1),v=setTimeout(()=>m(!0),n);r.signal?.addEventListener("abort",h,{once:!0}),r.signal?.aborted&&h(),p.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Zm.win32.basename(e))?cu(l):l()}function wC(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var vC,gC,Ri,Ko=S(()=>{"use strict";Qr();Pi();vC=6e4,gC=8*1024*1024;Ri=class extends Error{constructor(r,n,i,a){super(`${r} ${n.join(" ")} failed${i?`: ${i}`:""}`,a);this.command=r;this.args=n;this.stderr=i;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});function Ru(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function _u(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let n=t,i=`Native Builder acceptance_review[${r}]`;Eu(n,["id","status","evidence","note"],i,`/acceptance_review/${r}`);let a=n.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${i}.status is invalid`);if(!Array.isArray(n.evidence))throw new Error(`${i}.evidence must be an array`);return{id:Ru(n.id,`${i}.id`),status:a,evidence:n.evidence.map(o=>Ru(o,`${i}.evidence`)),note:Ru(n.note,`${i}.note`)}})}function Au(e,t){if(!t)throw new cn(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),n=t.map(({id:c})=>c),i=new Set(n);if(i.size!==n.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=n.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!i.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new cn(o,s)}var cn,Uo=S(()=>{"use strict";Vo();cn=class extends Error{constructor(r,n){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${n.length?`; not ready: ${n.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=n}missingIds;incompleteIds}});import{promises as _C}from"node:fs";function fe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pe(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function Y(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Iu(e,t){return e===null?null:Y(e,t)}function Tu(e,t){let r=Y(e,t);if(!jC.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ln(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function F(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function OC(e,t){return e===null?null:F(e,t,Number.MIN_SAFE_INTEGER)}function q(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function at(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((n,i)=>r(n,i))}function Qo(e,t){return at(e,t,(r,n)=>Y(r,`${t}[${n}]`))}function Sr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function un(e,t){let r=Y(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Yo(e,t,r=!1){let n=Y(e,t);if(n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/u.test(n)||n.split("/").includes("..")||!r&&(n==="."||n.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return n}function Ie(e,t){let r=fe(e,t);return pe(r,new Set(["text","truncated"]),t),{text:Y(r.text,`${t}.text`,{empty:!0}),truncated:ln(r.truncated,`${t}.truncated`)}}function HC(e,t){let r=`Native spec_changes[${t}]`,n=fe(e,r);pe(n,new Set(["capability","operation","source","delta_source","base_hash"]),r);let i=Y(n.capability,`${r}.capability`);if(!IC.test(i))throw new Error(`${r}.capability is invalid`);let a=q(n.operation,["create","modify","remove"],`${r}.operation`),o=n.source===null?null:Yo(n.source,`${r}.source`),s=n.delta_source===void 0?void 0:Yo(n.delta_source,`${r}.delta_source`),c=n.base_hash===void 0?void 0:n.base_hash===null?null:Tu(n.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:i,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function DC(e){let t="Native workspace",r=fe(e,t);pe(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let n=q(r.isolation,["current","branch","worktree"],`${t}.isolation`),i=Iu(r.change_branch,`${t}.change_branch`),a=Iu(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:q(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(n==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(n==="current"&&i===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(n!=="current"&&(i===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:n,change_branch:i,target_branch:a,finish:o}}function LC(e){let t="Native loop",r=fe(e,t);pe(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let n=Qo(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Sr(n,`${t}.previous_unresolved_ids`);let i=r.stop_reason===void 0?void 0:q(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:q(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:F(r.goal_cycle,`${t}.goal_cycle`,1),iteration:F(r.iteration,`${t}.iteration`),attempt:F(r.attempt,`${t}.attempt`),retry_epoch:F(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:F(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:F(r.no_progress_count,`${t}.no_progress_count`),...i===void 0?{}:{stop_reason:i},execution_failure_count:F(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:n,next_action:Iu(r.next_action,`${t}.next_action`)}}function BC(e,t){let r=`Native acceptance[${t}]`,n=fe(e,r);pe(n,new Set(["id","source","text","result","reason"]),r);let i=Y(n.id,`${r}.id`);if(!TC.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:Yo(n.source,`${r}.source`),text:Y(n.text,`${r}.text`),result:q(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:Ie(n.reason,`${r}.reason`)}}function MC(e,t){let r=`Native builder_handoff.checks[${t}]`,n=fe(e,r);return pe(n,new Set(["name","result","note"]),r),{name:Ie(n.name,`${r}.name`),result:q(n.result,["passed","failed","not-run"],`${r}.result`),note:n.note===null?null:Ie(n.note,`${r}.note`)}}function FC(e){let t="Native builder_handoff",r=fe(e,t);pe(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let n=Qo(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Sr(n,`${t}.addressed_acceptance_ids`);let i=r.review===null||r.review===void 0?null:fe(r.review,`${t}.review`);return i&&pe(i,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:Y(r.candidate_id,`${t}.candidate_id`),identity_provider:Y(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:Y(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:F(r.iteration,`${t}.iteration`,1),summary:Ie(r.summary,`${t}.summary`),addressed_acceptance_ids:n,...r.acceptance_review===void 0?{}:{acceptance_review:_u(r.acceptance_review)},checks:at(r.checks,`${t}.checks`,MC),checks_truncated:ln(r.checks_truncated,`${t}.checks_truncated`),known_limits:at(r.known_limits,`${t}.known_limits`,(a,o)=>Ie(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ln(r.known_limits_truncated,`${t}.known_limits_truncated`),review:i?{status:q(i.status,["passed"],`${t}.review.status`),summary:Ie(i.summary,`${t}.review.summary`),reviewer_execution_ref:Y(i.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:un(r.submitted_at,`${t}.submitted_at`)}}function VC(e,t){let r=`Native blockers[${t}]`,n=fe(e,r);pe(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=Qo(n.acceptance_ids,`${r}.acceptance_ids`);return Sr(i,`${r}.acceptance_ids`),{owner:q(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ie(n.reason,`${r}.reason`),acceptance_ids:i,resolution_action:q(n.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function qC(e,t){let r=`Native verification.checks[${t}]`,n=fe(e,r);return pe(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:Y(n.id,`${r}.id`),name:Ie(n.name,`${r}.name`),argv_display:at(n.argv_display,`${r}.argv_display`,(i,a)=>Ie(i,`${r}.argv_display[${a}]`)),argv_truncated:ln(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:Yo(n.cwd_ref,`${r}.cwd_ref`,!0),status:q(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:OC(n.exit_code,`${r}.exit_code`),duration_ms:F(n.duration_ms,`${r}.duration_ms`)}}function WC(e){let t="Native verification",r=fe(e,t);pe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let n=at(r.checks,`${t}.checks`,qC);Sr(n.map(a=>a.id),`${t}.checks IDs`);let i=Y(r.identity_provider,`${t}.identity_provider`);return{candidate_id:Y(r.candidate_id,`${t}.candidate_id`),identity_provider:i,verifier_execution_ref:Y(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:F(r.iteration,`${t}.iteration`,1),attempt:F(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?i==="skill-coordinated"?"skill-coordinated":"host-attested":q(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:q(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:n,summary:Ie(r.summary,`${t}.summary`),risks:at(r.risks,`${t}.risks`,(a,o)=>Ie(a,`${t}.risks[${o}]`)),risks_truncated:ln(r.risks_truncated,`${t}.risks_truncated`),completed_at:un(r.completed_at,`${t}.completed_at`)}}function zC(e,t){let r=`Native history[${t}]`,n=fe(e,r);pe(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=Qo(n.unresolved_ids,`${r}.unresolved_ids`);return Sr(i,`${r}.unresolved_ids`),{goal_cycle:F(n.goal_cycle,`${r}.goal_cycle`,1),iteration:F(n.iteration,`${r}.iteration`),attempt:F(n.attempt,`${r}.attempt`),outcome:q(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:Ie(n.summary,`${r}.summary`),completed_at:un(n.completed_at,`${r}.completed_at`)}}function GC(e){let t="Native history_overflow.outcome_counts",r=fe(e,t),n=["pass","fail","blocked","execution-error","recovery"];return pe(r,new Set(n),t),{pass:F(r.pass,`${t}.pass`),fail:F(r.fail,`${t}.fail`),blocked:F(r.blocked,`${t}.blocked`),"execution-error":F(r["execution-error"],`${t}.execution-error`),recovery:F(r.recovery,`${t}.recovery`)}}function KC(e){let t="Native history_overflow",r=fe(e,t);pe(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let n=F(r.dropped_entries,`${t}.dropped_entries`),i=r.first_dropped_at===null?null:un(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:un(r.last_dropped_at,`${t}.last_dropped_at`);if(n===0&&(i!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(n>0&&(i===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=GC(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==n)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:n,first_dropped_at:i,last_dropped_at:a,outcome_counts:o}}function JC(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&Au(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let n of r.acceptance_ids)if(!t.has(n))throw new Error(`Native blocker references unknown ID ${n}`);if(e.builder_handoff){if(!(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.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}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 n=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,i=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!n&&!i)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function UC(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 r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);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(n=>n.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(n=>n.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 dn(e){let t=fe(e,"Native portable state");if(pe(t,$C,"Native portable state"),t.schema!==rn)throw new Error(`Native portable state schema must be ${rn}`);let r=Y(t.name,"Native state name");if(!AC.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let n=at(t.spec_changes,"Native spec_changes",HC);Sr(n.map(s=>s.capability),"Native spec change capabilities");let i=at(t.acceptance,"Native acceptance",BC);Sr(i.map(s=>s.id),"Native acceptance IDs");let a=at(t.history,"Native history",zC);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:rn,name:r,language:q(t.language,["en","zh-CN"],"Native state language"),phase:q(t.phase,["shape","build","verify","archive"],"Native state phase"),status:q(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:F(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Tu(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Tu(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:q(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:n,workspace:DC(t.workspace),loop:LC(t.loop),acceptance:i,builder_handoff:t.builder_handoff===null?null:FC(t.builder_handoff),blockers:at(t.blockers,"Native blockers",VC),verification:t.verification===null?null:WC(t.verification),history:a,history_overflow:KC(t.history_overflow),verification_result:q(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:q(t.verification_report,["verification.md"],"Native verification_report"),archived:ln(t.archived,"Native archived"),created_at:un(t.created_at,"Native created_at")};return JC(o),UC(o),o}function cv(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return dn({schema:rn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:Nu(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function YC(e,t){let r=(0,Xo.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function ju(e){let t=await _C.readFile(e,"utf8");return dn(YC(t,"Native portable state"))}async function lv(e,t,r={}){let n=dn(t);await ee(e,(0,Xo.stringify)(n),r)}var Xo,AC,IC,TC,jC,$C,Yt=S(()=>{"use strict";Uo();Xo=At(mt(),1);B();Si();AC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TC=/^A[1-9][0-9]*$/u,jC=/^[a-f0-9]{64}$/u,$C=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"])});function jv(e,t){return Ju[e][t]}function eR(e){return Di[e].section}function tR(e,t){return Di[e].subsections[t]}function Li(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(n=>{if(n!=="scope")return`# ${jv(e,n)}
|
|
188
|
+
`;let i=[`# ${jv(e,n)}
|
|
189
|
+
`];i.push(`## ${eR(e)}
|
|
190
|
+
`);for(let a of $v)i.push(`### ${tR(e,a)}
|
|
191
|
+
`);return i.join(`
|
|
192
|
+
`)}).join(`
|
|
193
|
+
`)}var $v,Ju,UP,YP,XP,Tv,QP,ZP,Di,Rr=S(()=>{"use strict";$v=["created","modified","deleted","notCreated"],Ju={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},UP={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},YP={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},XP=new Map,Tv=new Map,QP=new Set,ZP=new Map,Di={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys(Ju)){for(let[t,r]of Object.entries(Ju[e]))XP.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(UP[e]))Tv.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(YP[e]))Tv.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(Di)){QP.add(Di[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(Di[e].subsections))ZP.set(r.toLocaleLowerCase("en-US"),t)}});import{createHash as Yu,randomUUID as rR}from"node:crypto";import{promises as xe}from"node:fs";import nR from"node:os";import we from"node:path";async function Uu(e,t){let r=await xe.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let n=await xe.readFile(e),i=await xe.lstat(e,{bigint:!0});if(r.ino!==i.ino||r.ctimeNs!==i.ctimeNs||r.size!==i.size)throw new Error("Process probe cache changed");return n}async function Dv(e){try{let t=JSON.parse((await Uu(we.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=we.join(e,t.file),n=await Uu(r,65536);return Yu("sha256").update(n).digest("hex")===t.hash?r:null}catch{return null}}async function oR(e,t){let r,n=rR(),i=we.join(e,`probe-${n}.cs`),a=we.join(e,`probe-${n}.exe`),o=we.join(e,`probe-${n}.json`);try{if(await xe.mkdir(e,{recursive:!0,mode:448}),(await xe.lstat(e)).isSymbolicLink())return null;r=await xe.open(we.join(e,"prepare.lock"),"wx",384);let s=await Dv(e);if(s)return s;await xe.writeFile(i,Hv,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=we.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await xe.access(d),c=d;break}catch{}}if(!c)return null;await Kt(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,i],{timeoutMs:1500,maxBufferBytes:4096});let l=Yu("sha256").update(await Uu(a,65536)).digest("hex");return await xe.writeFile(o,JSON.stringify({file:we.basename(a),hash:l}),{flag:"wx",mode:384}),await xe.rename(o,we.join(e,"probe.json")),a}catch{return null}finally{await xe.unlink(i).catch(()=>{}),await xe.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await xe.unlink(we.join(e,"prepare.lock")).catch(()=>{}))}}async function Ov(e,t,r){try{let n=await Kt(we.join(t,"System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),i=/^CreationDate=(\S+)/mu.exec(n);if(i)return`win32-wmic:${i[1]}`}catch{}if(r.aborted)return null;try{let i=(await Kt(we.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(i)?`win32-ps:${i}`:null}catch{return null}}function sR(e,t){let r=is.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let n={promise:oR(e,t),retryAfter:1/0};return is.set(e,n),n.promise.then(i=>{is.get(e)===n&&(i?is.delete(e):n.retryAfter=performance.now()+aR)}),n.promise}async function Lv(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",n=we.join(t.cacheRoot??we.join(nR.tmpdir(),"comet-process-identity"),iR),i=async l=>{if(!l)return null;try{let d=(await Kt(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await Dv(n);if(a){let l=await i(a);return l||Ov(e,r,new AbortController().signal)}let o=sR(n,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(i).then(c),Ov(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Hv,iR,aR,is,Bv=S(()=>{"use strict";Ko();Hv=`using System;
|
|
194
|
+
using System.Runtime.InteropServices;
|
|
195
|
+
class CometProcessIdentity {
|
|
196
|
+
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
|
197
|
+
[DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
|
|
198
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
|
199
|
+
static int Main(string[] args) {
|
|
200
|
+
int pid; if(args.Length != 1 || !int.TryParse(args[0], out pid) || pid <= 0) return 1;
|
|
201
|
+
IntPtr handle=OpenProcess(0x1000, false, pid); if(handle == IntPtr.Zero) return 1;
|
|
202
|
+
try { long creation, exit, kernel, user; if(!GetProcessTimes(handle,out creation,out exit,out kernel,out user)) return 1;
|
|
203
|
+
Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
|
|
204
|
+
} finally { CloseHandle(handle); }
|
|
205
|
+
}
|
|
206
|
+
}`,iR=Yu("sha256").update(Hv).digest("hex"),aR=1e4,is=new Map});import{promises as Mv}from"node:fs";function lR(e){let t=Qu.get(e);if(t){if(Date.now()-t.at>cR){Qu.delete(e);return}return t.value}}async function Bi(e){if(e===process.pid&&Xu!==null)return Xu;let t=lR(e);if(t!==void 0)return t;let r=as.get(e);r||(r=uR(e),as.set(e,r));let n=await r;return as.get(e)===r&&as.delete(e),e===process.pid&&n!==null&&(Xu=n),n===null&&Qu.set(e,{value:null,at:Date.now()}),n}async function uR(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Mv.readFile(`/proc/${e}/stat`,"utf8"),Mv.readFile("/proc/sys/kernel/random/boot_id","utf8")]),n=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(n??"")?`linux:${r.trim()}:${n}`:null}if(process.platform==="win32")return await Lv(e);if(process.platform==="darwin"){let t=(await Kt("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return t?`darwin:${t}`:null}}catch{}return null}function os(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function Zu(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(n){if(n.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Bi(e);return r===t?"alive":r===null||os(r)!==os(t)&&Fv.has(os(r))&&Fv.has(os(t))?"unknown":"dead"}var Xu,cR,Qu,as,Fv,ss=S(()=>{"use strict";Ko();Bv();Xu=null,cR=1e4,Qu=new Map,as=new Map;Fv=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as dR}from"async_hooks";import{randomUUID as Wv}from"crypto";import{promises as je}from"fs";import zv from"os";import M from"path";function hR(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function mR(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Gv(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 ls(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return et(r,n)?H(r,n):H(r,n)&&e.size===t.size}function Mi(e,t){return ls(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function vR(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Mi(e.identity,t.identity)}async function $e(e){let t,r;try{let n=await Gr(e,Vv,{bigint:!0,label:"Native lock"});t=n.bytes,r=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Be?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Vv} 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:mR(JSON.parse(t.toString("utf8")),e),identity:Gv(r)}}async function gR(e){return(await $e(e))?.owner??null}async function td(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==zv.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await Zu(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function wR(e,t){try{await je.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await je.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function us(e,t){let r=await $e(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Mi(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await je.mkdir(t,{recursive:!0});let n=M.join(t,`${M.basename(e.file)}.${e.owner.id}.${Wv()}.removed`);try{await je.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let i=await $e(n);if(!i||i.owner.id!==e.owner.id||!ls(i.identity,e.identity))throw await wR(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await je.rm(n,{force:!0}),"removed"}async function Kv(e){let t=await Bi(process.pid);return{id:Wv(),pid:process.pid,hostname:zv.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Jv(e,t){let r;try{r=await je.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await gR(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let n;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
207
|
+
`,"utf8"),await r.sync(),n=Gv(await r.stat({bigint:!0}))}finally{await r.close()}let i=await $e(e);if(!n||!i||i.owner.id!==t.id||!ls(i.identity,n))throw new Error(`Native lock changed after write: ${e}`);return i.identity}async function yR(e,t){let r=await j(e.runtimeDir,e.locksDir);await je.mkdir(r,{recursive:!0});let n=await j(e.runtimeDir,M.join(r,ed));await je.mkdir(n,{recursive:!0});let i=await Kv(t),a=M.join(n,`.${i.id}.tmp`),o=M.join(n,`${i.id}.claim`);try{let s=await Jv(a,i);await je.rename(a,o);let c=await $e(o);if(!c||!ls(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:i,identity:c.identity}}finally{await je.rm(a,{force:!0})}}async function bR(e){let t=M.dirname(e.file),r=!1,n=M.basename(e.file);for(let i of await je.readdir(t,{withFileTypes:!0})){if(!i.isFile()||i.isSymbolicLink()||!i.name.endsWith(".claim"))continue;let a=M.join(t,i.name);if(M.resolve(a)!==M.resolve(e.file))try{let o=await $e(a),s=await td(o);if(s.status==="missing")continue;let c=await $e(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Mi(c.identity,o.identity)){i.name<n&&(r=!0);continue}if(s.status==="stale"&&o){await us(o,t);continue}i.name<n&&(r=!0)}catch{i.name<n&&(r=!0)}}return r}async function Uv(e){let t=await $e(e.file);if(t){if(t.owner.id!==e.owner.id||!Mi(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await us(t,M.dirname(e.file))}}async function NR(e,t){let r=Date.now()+fR;for(;;){let n=await yR(e,t);if(!await bR(n))return n;if(await Uv(n),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(i=>setTimeout(i,2+Math.floor(Math.random()*7)))}}async function kR(e){let t=cs.get(e)??Promise.resolve(),r,n=new Promise(a=>{r=a}),i=t.then(()=>n);return cs.set(e,i),await t,()=>{r(),cs.get(e)===i&&cs.delete(e)}}async function ds(e,t,r){let n=M.resolve(e.locksDir),i=qv.getStore();if(i?.has(n))return r();let a=await kR(n);try{let o=await NR(e,t),s=new Map(i??[]);return s.set(n,o),await qv.run(s,async()=>{try{return await r()}finally{await Uv(o)}})}finally{a()}}async function Yv(e,t,r){let n=[...new Map(e.map(a=>[M.resolve(a.locksDir),a])).values()].sort((a,o)=>M.resolve(a.locksDir).localeCompare(M.resolve(o.locksDir))),i=async a=>{let o=n[a];return o?ds(o,t,()=>i(a+1)):r()};return i(0)}async function fs(e,t,r){return ds(e,`acquire ${t}`,async()=>{let n=await j(e.runtimeDir,e.locksDir);await je.mkdir(n,{recursive:!0});let i=await j(e.runtimeDir,M.join(n,hR(t))),a=await Kv(r),o=await Jv(i,a);return{file:i,nativeRoot:e.runtimeDir,locksDir:n,owner:a,identity:o}})}async function ps(e){await $e(e.file)&&await ds({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${M.basename(e.file)}`,async()=>{let t=await $e(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Mi(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=M.join(e.locksDir,ed);await us(t,r)})}function SR(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function Xv(e){return td(await $e(e))}async function Qv(e,t,r,n={}){return ds(e,`take over ${M.basename(t)}`,async()=>{let i=await j(e.runtimeDir,e.locksDir),a=await j(e.runtimeDir,t);if(M.resolve(M.dirname(a))!==M.resolve(i))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await $e(a),s=await td(o);if(s.status==="missing")return{status:"missing"};if(r&&!vR(r,s))return{status:"changed",diagnosis:s};let c=n.allowAgedUnknown===!0&&s.status==="unknown"&&SR(o?.owner??null)>=pR;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=M.join(i,ed);return await us(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Vv,ed,fR,pR,qv,cs,Fi=S(()=>{"use strict";di();ss();L();rt();Vv=16*1024,ed=".coordinator",fR=5e3,pR=900*1e3,qv=new dR,cs=new Map});var ct,St,Et,Vi=S(()=>{"use strict";ct="comet.native.v3",St="comet.native.v2",Et="comet.native.v1"});import ER from"node:path";function Wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function rg(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function mn(e){if(!tg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ng(e){if(!tg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function ig(e,t){if(e.length===0||ER.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function TR(e,t){let r=Wi(e,`spec_changes[${t}]`);if(rg(r,PR,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(ng(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let n=r.source,i=r.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof n=="string"&&ig(n,`Spec source for ${r.capability}`),r.operation==="create"){if(!n)throw new Error(`Create spec ${r.capability} requires source`);if(i!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!n)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof i!="string"||!nd.test(i))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof i!="string"||!nd.test(i))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof n=="string"?{source:n}:{},base_hash:i}}function jR(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 id(e,t){if(rg(e,t,Je),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"||!RR.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&&!_R.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 r=e.spec_changes.map(TR),n=r.map(i=>i.capability).filter((i,a,o)=>o.indexOf(i)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof e.verification_result!="string"||!AR.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"&&ig(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!jR(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:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function zi(e){let t=Wi(e,Je);if(t.schema!==Et)throw new Error(`Expected ${Et}`);return{schema:Et,...id(t,xR)}}function qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rd(e,t,r){if(e===null)return null;let n=typeof e=="string"?IR.exec(e):null;if(!n||n[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function $R(e){if(e==null)return null;if(typeof e!="string"||!nd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function OR(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 Gi(e){let t=Wi(e,Je);if(t.schema!==St)throw new Error(`Expected ${St}`);if(qi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${St} minimum_runtime_version must be 2`);return{schema:St,minimum_runtime_version:2,revision:qi(t.revision,"Native v2 revision"),...id(t,eg)}}function vn(e){let t=Wi(e,Je);if(t.schema!==ct){if(t.schema===Et||t.schema===St){let o=t.schema===Et?zi(t):Gi(t);throw new hn(o.name,o.schema)}throw new Ct(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Ct(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=qi(t.revision,"Native revision"),i=id(t,CR),a=$R(t.approved_contract_hash);if(i.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ct,minimum_runtime_version:3,revision:n,verification_protocol:OR(t.verification_protocol),...i,approved_contract_hash:a,implementation_scope:rd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:rd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:rd(t.partial_allowance,"Native partial_allowance","allowances")}}function hs(e){let t=Wi(e,Je);if(t.schema===Et){let i=zi(t);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:1,state:i,message:`Native change ${i.name} requires migration to ${ct}`}}if(t.schema===St){let i=Gi(t);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i,message:`Native change ${i.name} requires migration to ${ct}`}}if(t.schema!==ct){let i=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:i,state:null,message:new Ct(typeof t.schema=="string"?t.schema:"(missing)",i).message}}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Ct(t.schema,r).message};let n=vn(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}var Zv,xR,eg,CR,PR,RR,_R,AR,Je,nd,tg,IR,hn,Ct,ms=S(()=>{"use strict";Vi();Zv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],xR=new Set(Zv),eg=new Set([...Zv,"minimum_runtime_version","revision"]),CR=new Set([...eg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),PR=new Set(["capability","operation","source","base_hash"]),RR=new Set(["shape","build","verify","archive"]),_R=new Set(["implicit","confirmed"]),AR=new Set(["pending","pass","fail"]),Je="comet-state.yaml",nd=/^[a-f0-9]{64}$/u,tg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,hn=class extends Error{constructor(r,n){super(`Native change ${r} uses ${n}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ct=class extends Error{constructor(r,n){super(r!==ct||n===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});var SH,ag,vs=S(()=>{"use strict";Rr();J();SH=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ag=Object.freeze({maxCriteria:1024})});var ad=S(()=>{"use strict";vs()});var _r=S(()=>{"use strict"});function WR(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zR(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function sg(e){let t=WR(e,"Native portable migration transaction"),r=Object.keys(t).filter(n=>!BR.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==og)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!FR.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!MR.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!qR.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!VR.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:og,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:zR(t.createdAt,"Native portable migration transaction createdAt")}}var og,BR,MR,FR,VR,qR,cg=S(()=>{"use strict";ms();ad();Yt();_r();Si();Vi();og="comet.native.portable-migration.v1",BR=new Set(["schema","id","change","fromSchema","status","createdAt"]),MR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FR=/^[a-z0-9][a-z0-9-]{7,127}$/u,VR=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),qR=new Set([Et,St,ct])});import GR from"node:path";function pg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hg(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function od(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function ug(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function e_(e,t){let r=`Native portable Archive spec_changes[${t}]`,n=pg(e,r);if(hg(n,ZR,r),typeof n.capability!="string"||!fg.test(n.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(n.operation)))throw new Error(`${r}.operation is invalid`);let i=n.operation,a=n.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(f=>f==="."||f==="..")))throw new Error(`${r}.delta_source is invalid`);let o=od(n.base_hash,`${r}.base_hash`),s=ug(n.delta_content,`${r}.delta_content`),c=ug(n.source_content,`${r}.source_content`),l=od(n.expected_target_hash,`${r}.expected_target_hash`),u=od(n.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=Oo(s);if(f.capability!==n.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(f.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(zt(n.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(zt(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(i==="remove"){if(n.source!==null||n.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:n.capability,operation:i,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof n.source!="string"||n.source.length===0||n.source.includes("\\")||n.source.startsWith("/")||/^[A-Za-z]:/u.test(n.source)||n.source.split("/").some(f=>f==="."||f===".."))throw new Error(`${r}.${i} source is invalid`);if(typeof n.content!="string")throw new Error(`${r}.${i} content is invalid`);if(u!==void 0&&(u===null||zt(n.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:n.capability,operation:i,source:n.source,content:n.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function t_(e){let t=pg(e,"Native portable Archive transaction");if(hg(t,QR,"Native portable Archive transaction"),t.schema!==lg)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!UR.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!fg.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"||!YR.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"||!XR.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 r=t.spec_changes.map(e_);if(new Set(r.map(({capability:i})=>i)).size!==r.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)>r.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 n=new Date(t.created_at);if(Number.isNaN(n.valueOf())||n.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:lg,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:r,created_at:t.created_at}}function sd(e){let t=KR.exec(e);if(t)return{kind:"archive",change:t[1]};let r=JR.exec(e);return r?{kind:"migration",change:r[1]}:null}async function mg(e,t){let r=sd(t);if(!r)return null;let n=await ue({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),a=GR.join(e.transactionsDir,t);if(r.kind==="archive"){let s=t_(i);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=sg(i);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function vg(e){return e.kind==="archive"||e.journal.status!=="committed"}var lg,dg,KR,JR,UR,YR,XR,QR,ZR,fg,cd=S(()=>{"use strict";Ae();Do();cg();lg="comet.native.archive-transaction.v4",dg="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",KR=new RegExp(`^portable-archive-(${dg})\\.json$`,"u"),JR=new RegExp(`^portable-migration-(${dg})\\.json$`,"u"),UR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YR=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XR=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),QR=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ZR=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),fg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as r_}from"node:crypto";import{constants as gs,promises as Ce}from"node:fs";import Ue from"node:path";import{TextDecoder as n_}from"node:util";function ys(e,t){let r=Ue.relative(e,t);return r===""||!Ue.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ue.sep}`)}function gg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function i_(e,t){return H({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function a_(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ws(e,t){return H({...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 ld(e,t){let r=await Ce.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ce.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function wg(e,t,r){let n=Ue.resolve(e),i=Ue.resolve(t);if(!ys(n,i))throw new Error(`${r} is outside its managed root`);let a=[await ld(n,r)],o=n;for(let s of Ue.relative(n,i).split(Ue.sep).filter(Boolean)){await Pt(a,r),o=Ue.join(o,s);let c=await ld(o,r);if(!ys(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Pt(a,r),a}async function Pt(e,t){for(let r of e){let n=await Ce.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!i_(r,n)||await Ce.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function o_(e,t,r){let n=[],i=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-i,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(i+=s,t!==null&&i>t)throw new Error(`${r} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,i)}async function gn(e){let t=e.maxBytes===null?null:gg(e.maxBytes),r=Ue.resolve(e.file),n=await wg(e.root,Ue.dirname(r),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(u=>ld(Ue.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Pt(n,e.label);let a=await Ce.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=a_(a),s=await Ce.realpath(r);if(!ys(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(u=>ys(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?gs.O_RDONLY:gs.O_RDONLY|gs.O_NOFOLLOW|gs.O_NONBLOCK,l=await Ce.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ce.lstat(r),Ce.realpath(r)]);if(await Pt(n,e.label),await Pt(i,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ws(o,u)||!ws(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await o_(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),Ce.lstat(r),Ce.realpath(r)]);if(await Pt(n,e.label),await Pt(i,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ws(o,m)||!ws(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:r_("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function yg(e){let t=await gn(e),r;try{r=new n_("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e.label} is not valid UTF-8`,{cause:n})}return{...t,text:r}}async function Ji(e){let t=await wg(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await Ce.readdir(e.directory,{withFileTypes:!0});else{let n=gg(e.maxEntries);r=[];let i=await Ce.opendir(e.directory);try{for await(let a of i)if(r.push(a),r.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await i.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Pt(t,e.label),{entries:r,verify:()=>Pt(t,e.label)}}var lt=S(()=>{"use strict";B();rt()});import Rt from"path";import{TextDecoder as c_}from"util";function Ns(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ks(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function Sg(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ud(e,t){if(typeof e!="string"||e.length===0||Rt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function bs(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function bg(e,t){if(ud(e,t),e.includes("\\")||e!==Rt.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 h_(e,t){let r=Ns(e,`transaction operations[${t}]`);if(ks(r,u_,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);ud(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&ud(r[n],`transaction operation ${r.id} ${n}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Eg(e){let t=Ns(e,"Native Archive transaction journal");if(ks(t,d_,"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"||!kg.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(!Sg(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(bs(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 r=t.operations.map((s,c)=>{let l=Ns(s,`Archive transaction operations[${c}]`);if(ks(l,f_,`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`);bg(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&bg(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&bs(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(bs(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`);bs(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=r.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let i=`runtime/transactions/${t.id}`,a=r.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)||r.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 r.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(`${i}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${i}/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:r}}function m_(e){let t=Ns(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Eg(t);if(ks(t,l_,"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"||!kg.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Rt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Rt.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(!Sg(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 r=t.operations.map(h_),n=r.map(i=>i.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:r}}function v_(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Rt.join(e.transactionsDir,t)}function xg(e,t){let r=v_(e,t);return{directory:r,journal:Rt.join(r,"transaction.json"),events:Rt.join(r,"events.jsonl"),staged:Rt.join(r,"staged"),backups:Rt.join(r,"backups")}}async function dd(e,t){let r=xg(e,t);return await Promise.all(Object.values(r).map(n=>j(e.runtimeDir,n))),r}async function fd(e,t,r={}){let n=await dd(e,t),i=await gn({root:e.runtimeDir,file:n.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(p_.decode(i.bytes)),o=m_(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var l_,u_,d_,f_,kg,p_,Ss=S(()=>{"use strict";B();L();lt();l_=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),u_=new Set(["id","type","source","target","staged","backup"]),d_=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),f_=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),kg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),p_=new c_("utf-8",{fatal:!0})});import{promises as g_}from"fs";import w_ from"path";async function y_(e,t,r){let n;try{n=await g_.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of n)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let a=await fd(e,i.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let i of n)if(sd(i.name))try{let a=await mg(e,i.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(vg(a))return!0}catch{return!0}return!1}async function b_(e,t){let r=Date.now()+5e3,n=w_.join(e.locksDir,"root-move.lock");for(;;)try{return await fs(e,"root-move",t)}catch(i){if(i.cause?.code!=="EEXIST")throw i;let o=await Xv(n);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Qv(e,n,o);if(s.status==="removed"||s.status==="missing")continue;throw i}if(o.status!=="active"||Date.now()>=r)throw i;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function X(e,t,r,n){let i=await b_(e,t);try{if(await xo(e.projectRoot),await y_(e,n?.allowedTransactionId,n?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await ps(i)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${i.file} (${a.message}); run comet native doctor --repair if commands start failing
|
|
208
|
+
`)}}}var ne=S(()=>{"use strict";ke();Fi();cd();Ss()});import{createHash as N_}from"crypto";function Pe(e){return N_("sha256").update(e).digest("hex")}var ut=S(()=>{"use strict"});import hd from"path";function Es(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function F_(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 V_(e,t){return Pe(`comet.native.snapshot-policy.v1
|
|
209
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function pd(e,t,r){let n=new Set(t),i=[...t];for(;i.length>0;){if(r&&!r())return null;let a=i.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),i.push(a+1))}return n}function q_(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Cg(e){let t=Eo(e,"Native snapshot pattern"),r=[];for(let n=0;n<t.length;n+=1){let i=t[n];i==="*"&&t[n+1]==="*"?(n+=1,t[n+1]==="/"?(n+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):i==="*"?r.push({kind:"star"}):i==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:i})}return(n,i)=>{let a=i?q_(i):void 0;if(a&&!a())return!1;let o=pd(r,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=r[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=pd(r,c,a),o===null||o.size===0)return!1}return pd(r,o,a)?.has(r.length)??!1}}function W_(e){if(e===void 0)return;let t=[...new Set(e.include.map(i=>Eo(i,"include")))].sort((i,a)=>i.localeCompare(a,"en")),r=[...new Set(e.exclude.map(i=>Eo(i,"exclude")))].sort((i,a)=>i.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=V_(t,r);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:r,hash:n},includeMatchers:t.map(Cg),excludeMatchers:r.map(Cg),excludedDirectoryPrefixes:r.flatMap(i=>{if(!i.endsWith("/**"))return[];let a=i.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((i,a)=>i.localeCompare(a,"en"))}}function Oe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function He(e,t,r){let n=Object.keys(e).find(i=>!t.has(i));if(n)throw new Error(`${r} contains unknown field: ${n}`)}function yn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function dt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function _g(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 r=hd.posix.normalize(e);if(r!==e||hd.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function z_(e,t){let r=Oe(e,`Native snapshot entry ${t}`);He(r,$_,`Native snapshot entry ${t}`);let n=_g(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!xs.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let i={path:n,hash:r.hash,size:dt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!M_.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);i.gitObjectId=r.gitObjectId}return i}function G_(e,t){let r=Oe(e,`Native snapshot omission ${t}`);if(He(r,O_,`Native snapshot omission ${t}`),!L_.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!B_.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:_g(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:dt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function K_(e){let t=Oe(e,"Native snapshot omission overflow");if(He(t,H_,"Native snapshot omission overflow"),typeof t.hash!="string"||!xs.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:yn(t.count,"Native snapshot omission overflow count")}}function wn(e,t){let r=Oe(e,t);if(He(r,I_,t),typeof r.hash!="string"||!xs.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let n=dt(r.recordCount,`${t} recordCount`),i=dt(r.storedRecordCount,`${t} storedRecordCount`),a=dt(r.stdoutBytes,`${t} stdoutBytes`);if(i>n||!r.overflow&&i!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:n,storedRecordCount:i,stdoutBytes:a,overflow:r.overflow}}function Pg(e){let t=Oe(e,"Native Git selection evidence");if(He(t,A_,"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 r=wn(t.stageBefore,"Native Git selection stageBefore"),n=wn(t.combined,"Native Git selection combined"),i=wn(t.stageAfter,"Native Git selection stageAfter"),a=wn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=wn(t.finalCombined,"Native Git selection finalCombined"),s=wn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,n,i,a,o,s].some(d=>d.overflow),l=!Es(r,i)||!Es(i,a)||!Es(n,o)||!Es(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:r,combined:n,stageAfter:i,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Rg(e,t){let r=Oe(e,t);if(He(r,j_,t),typeof r.hash!="string"||!xs.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let n=dt(r.visitedNodeCount,`${t} visitedNodeCount`),i=dt(r.recordCount,`${t} recordCount`),a=dt(r.storedRecordCount,`${t} storedRecordCount`),o=dt(r.encodedBytes,`${t} encodedBytes`);if(a>i||!r.overflow&&a!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:n,recordCount:i,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function J_(e){let t=Oe(e,"Native physical selection evidence");if(He(t,T_,"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 r=Rg(t.before,"Native physical selection before"),n=Rg(t.after,"Native physical selection after"),i=r.overflow||n.overflow,a=r.unstable||n.unstable||!F_(r,n);if(!i&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=i&&a?"overflow-and-changed":i?"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:r,after:n}}function Ag(e){let t=Oe(e,"Native content snapshot manifest");if(He(t,x_,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!D_.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let g=Oe(t.capture,"Native content snapshot capture");if(He(g,R_,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let _=g.gitSelection===void 0?void 0:Pg(g.gitSelection),b=g.physicalSelection===void 0?void 0:J_(g.physicalSelection),T=null;if(g.projection!==void 0){let ie=Oe(g.projection,"Native content snapshot projection");if(He(ie,__,"Native content snapshot projection"),ie.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");T={provider:"git",...ie.selection===void 0?{}:{selection:Pg(ie.selection)}}}if(g.provider==="git"){if(b||T)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",..._?{gitSelection:_}:{}}}else{if(_)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&T)throw new Error("Native physical-tree capture cannot combine selection and projection");r=T?{provider:"physical-tree",projection:T}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Oe(t.limits,"Native content snapshot limits");He(n,C_,"Native content snapshot limits");let i={maxFiles:yn(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:yn(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:yn(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:yn(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:yn(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let g=Oe(t.policy,"Native snapshot policy");if(He(g,P_,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=W_({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(z_),s=t.omitted.map(G_),c=dt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:K_(t.omissionOverflow);if(o.length>i.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>i.maxFileBytes)||o.reduce((g,_)=>g+_.size,0)>i.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>S_||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(g=>g.reason==="git-enumeration-limit"),f=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...f])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(g=>g.reason==="physical-enumeration-limit"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=r?.physicalSelection,k=y?.status==="overflow"||y?.status==="overflow-and-changed",E=y?.status==="changed"||y?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:i,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}function U_(e,t){if(!E_.test(t))throw new Error(`Invalid Native change name: ${t}`);return hd.join(Ne(e,t),"baseline-manifest.json")}async function Ig(e,t){let r=U_(e,t),n=qe(e,r);await j(n,r);try{let i=await yg({root:n,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return Ag(JSON.parse(i.text))}catch(i){if(i.code==="ENOENT")return null;throw i}}var kD,S_,E_,x_,C_,P_,R_,__,A_,I_,T_,j_,$_,O_,H_,D_,L_,B_,xs,M_,SD,ED,xD,CD,PD,Ui=S(()=>{"use strict";Qr();B();ke();ut();rt();L();lt();vi();kD={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},S_=1e3,E_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,x_=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),C_=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),P_=new Set(["schema","include","exclude","hash"]),R_=new Set(["provider","gitSelection","physicalSelection","projection"]),__=new Set(["provider","selection"]),A_=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),I_=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),T_=new Set(["schema","status","before","after"]),j_=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),$_=new Set(["path","hash","size","type","gitObjectId"]),O_=new Set(["path","size","type","reason"]),H_=new Set(["ref","hash","count"]),D_=new Set(["change-created","legacy-migration","explicit"]),L_=new Set(["file","directory","other"]),B_=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"]),xs=/^[a-f0-9]{64}$/u,M_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,SD=64*1024,ED=64*1024,xD={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},CD={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};PD=(1n<<256n)-1n});var OA,Os=S(()=>{"use strict";OA=At(mt(),1);Ae()});var rr=S(()=>{"use strict";B();J();Os();L();mr()});var Cd=S(()=>{"use strict"});var Ar=S(()=>{"use strict"});var Hs=S(()=>{"use strict";Pi();Cd();Ar()});var Yg=S(()=>{"use strict";ze();Hs();J()});import{createHash as VA}from"node:crypto";import{lstatSync as IB,readFileSync as TB,promises as Xg}from"node:fs";import Pd from"node:path";async function Ds(e){let t=Pd.join(e,qA),r;try{r=await Xg.readFile(t)}catch(i){if(i.code==="ENOENT")return;throw i}let n=WA(e);await Xg.mkdir(Pd.dirname(n),{recursive:!0}),await ae(n,{hash:zA(r)},{containedRoot:e})}var qA,WA,zA,Ls=S(()=>{"use strict";ze();B();qA=".comet/config.yaml",WA=e=>Pd.join(e,".comet","runtime","native","workspace-config.json"),zA=e=>VA("sha256").update(e).digest("hex")});var aw,xn=S(()=>{"use strict";J();Ui();aw=1024*1024});var Ms=S(()=>{"use strict";J();Ar();vi();xn()});var sw,pI,hI,mI,jF,vI,$F,Ad=S(()=>{"use strict";J();sw="scoped-text-safety",pI=1,hI=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),mI="comet.native.checker-policy.v1",jF=K(mI,{policy:sw,version:pI,limits:hI,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),vI=["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"],$F=new Set(vI)});var Fs=S(()=>{"use strict";J();Ad();Ar()});var yI,XF,Cn=S(()=>{"use strict";B();L();rt();xn();Ms();Fs();yI=aw,XF=3*yI});ke();B();import{promises as NT}from"node:fs";import Ks from"node:path";var Ql=At(mt(),1);tt();import{createHash as gE}from"node:crypto";import wE from"node:path";var Ul={strong:8,phrase:8,weak:12},Zh=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" ")),Ro=new Set(["请","帮我","一下","这个","进行","实现","需要","如何"]);function _o(e,t=2e3){return[...e].map(r=>{let n=r.codePointAt(0)??0;return n<32||n===127?" ":r}).join("").replace(/\s+/gu," ").trim().slice(0,t)}function hE(e){if(!e)return;let t=_o(e,512).replaceAll("\\","/");if(!(!t||t.startsWith("/")||/^[A-Za-z]:\//u.test(t)||t.split("/").includes("..")))return t}function Yl(e){return e.replace(/(^|[\s([{"'])(?:[A-Za-z]:[\\/]|\\\\)[^\s)\]}>,;"']+/gu,"$1").replace(/(^|[\s([{"',;:])\/(?!\/)[^\s)\]}>,;"']+/gu,"$1").replace(/\s+/gu," ").trim()}function Se(e,t){let r=t.trim();r.length<2||e.includes(r)||e.push(r)}function Co(e,t,r){let n=[],i=[],a=new Intl.Segmenter("zh",{granularity:"word"});for(let o of r.matchAll(/[\u3400-\u9fff]{2,}/gu)){let s=o[0];if(Ro.has(s))continue;Se(e,s);let c="";for(let{segment:l,isWordLike:u}of a.segment(s))u&&!Ro.has(l)&&Se(t,l),u&&l.length===1&&!"的和与给为在对及".includes(l)?(c&&Se(i,c+l),c=l):c="";for(let l=Math.min(4,s.length);l>=2;l-=1)for(let u=0;u+l<=s.length;u+=l){let d=s.slice(u,u+l);!Ro.has(d)&&d!==s&&Se(n,d)}}for(let o of i)Se(t,o);for(let o of n)Se(t,o)}function Po(e,t,r){for(let n of r.matchAll(/[A-Za-z][A-Za-z0-9_./:-]*/gu)){let i=n[0].replace(/^[./:]+|[./:]+$/gu,"");if(!i)continue;let a=i.toLowerCase();if(!Zh.has(a)&&(Se(mE(i)?e:t,i),i.includes("/")))for(let o of i.split(/[/:.]/u))Se(t,o)}for(let n of r.matchAll(/\b\d+(?:\.\d+)?\b/gu))Se(e,n[0])}function mE(e){return e.includes("/")||e.includes("\\")||e.includes("_")||/[a-z][A-Z]/u.test(e)||/[A-Z]{2,}/u.test(e)||/[A-Za-z][A-Za-z0-9]*\d[A-Za-z0-9]*/u.test(e)||/\d{2,}/u.test(e)||/(?:^|[^A-Za-z0-9])[A-Za-z0-9]+\.[A-Za-z0-9]+(?:$|[^A-Za-z0-9])/u.test(e)}function vE(e){return e.length>256||!/\s/u.test(e)?void 0:e.split(/\s+/u).filter(r=>{let n=r.toLowerCase();return r.length>=2&&!Zh.has(n)&&!Ro.has(r)}).length>=2?e:void 0}function em(e){let t=_o(e.task);if(!t)throw new Error("Project knowledge task must not be empty");let r=hE(e.path),n=e.phase?_o(e.phase,128):void 0,i=e.operation?_o(e.operation,128):void 0,a=[],o=[],s=[],c=[],l=[];Po(a,c,t),Co(o,l,t);for(let v=0;v<Math.max(c.length,l.length);v++)c[v]&&Se(s,c[v]),l[v]&&Se(s,l[v]);r&&(Se(a,r),Po(a,s,r),Co(o,s,r)),n&&(Po(a,s,n),Co(o,s,n)),i&&(Po(a,s,i),Co(o,s,i));let u=vE(t);u&&Se(o,u);let d=a.slice(0,Ul.strong),f=o.slice(0,Ul.phrase),p=s.filter(v=>!d.includes(v)&&!f.includes(v)).slice(0,Ul.weak),m=[...d,...f,...p],h=[Yl(t),...r?[`Target path: ${r}`]:[],...n?[`Phase: ${Yl(n)}`]:[],...i?[`Operation: ${Yl(i)}`]:[]].join(`
|
|
210
|
+
`);return{task:t,...r?{path:r}:{},...n?{phase:n}:{},...i?{operation:i}:{},terms:m,strongTerms:d,phraseTerms:f,weakTerms:p,remoteQuery:h}}function tm(e,t){return e.toLocaleLowerCase().includes(t.toLocaleLowerCase())}var rm=5,Ao=40,yE=5,bE=600,NE=256*1024,kE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;function Xl(e,t){let r=e.replaceAll("\\","/").replace(/^\.\//u,"").replace(/\/+$/u,"");if(!r||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a project-relative path`);return r}function Io(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),n=r.split("/"),i=t==="native"?kE:SE;if(!r||n.some(a=>!i.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return n.join("/")}function EE(e,t){let r=t.replaceAll("\\","/").replace(/^\.\//u,""),n=`${Xl(e.currentSpecRoot,"current Spec root")}/`;if(r.startsWith(n)&&r.endsWith("/spec.md")){let s=r.slice(n.length,-8);try{return{kind:"current",capability:Io(s,e.workflow),source:r}}catch{return null}}let i=`${Xl(e.archiveRoot,"archive root")}/`;if(!r.startsWith(i))return null;let a=r.slice(i.length).split("/");if(a.length<4||a[1]!=="specs"||a.at(-1)!=="spec.md")return null;let o=a.slice(2,-1).join("/");try{return{kind:"archive",capability:Io(o,e.workflow),source:r}}catch{return null}}function xE(e,t){return`${Xl(e.currentSpecRoot,"current Spec root")}/${Io(t,e.workflow)}/spec.md`}function CE(e){return gE("sha256").update(e.toString("utf8").replaceAll(`\r
|
|
194
211
|
`,`
|
|
195
212
|
`).replaceAll("\r",`
|
|
196
|
-
`)).digest("hex")}function
|
|
197
|
-
`),resultScore:t,resultRank:0},
|
|
198
|
-
`),resultScore:t,resultRank:a+1}))]}function rS(e,t,r){let i=`${t.workflow}\0${r}`,n=e.get(i);if(n)return n;let a={workflow:t.workflow,capability:r,historicalSources:new Set,matchedTerms:new Set,evidence:new Map,currentHits:0,historicalHits:0,bestScore:0,bestRank:Number.MAX_SAFE_INTEGER};return e.set(i,a),a}function iS(e,t){let r=t.terms.some(i=>i.toLocaleLowerCase()===e.capability.toLocaleLowerCase());return e.currentHits>0&&(e.matchedTerms.size>=2||r)?"high":e.currentHits>0?"medium":"low"}function nS(e,t){let r=e.currentHits>0?"当前总 Spec 已命中":"检索命中历史 change",i=e.historicalSources.size?`,并找到 ${e.historicalSources.size} 个历史来源`:"";return`${r}${i};已核对当前能力文件,匹配 ${e.matchedTerms.size} 个查询词(${t})`}function aS(e,t){let r=e.matchedTerms.size/Math.max(1,t.terms.length);return Math.min(1,(e.currentHits>0?.5:.15)+Math.min(.3,r*.3)+Math.min(.15,Math.max(0,e.bestScore)*.15)+Math.min(.05,e.historicalSources.size*.02))}function oS(e){return[...e.values()].sort((t,r)=>{let i=t.kind.endsWith("-spec")?0:1,n=r.kind.endsWith("-spec")?0:1;return i-n||t.source.localeCompare(r.source)}).slice(0,Gk)}function rh(e,t,r){return{schema:"comet.capability-association.v1",status:r,workflow:e.workflow,capability:e.capability,current_spec:e.currentSpec.source,current_hash:e.currentSpec.hash,confidence:e.confidence,...t?{query:t.task}:{},reason:e.reason,historical_sources:[...e.historicalSources],evidence:e.evidence}}async function ih(e,t,r){let i=Zk(t,r),n=await ee(e,i,Uk,{label:`${t.workflow} current capability Spec`});return{source:i,hash:eS(n.bytes)}}function nh(e,t,r,i){return{workflow:e.workflow,query:t,candidates:[],associationDraft:null,diagnostics:r,searched:i,providerLimit:Xa}}async function ah(e){let t=Kk.resolve(e.projectRoot),r=[],i=e.capability?.trim();if(!i&&!e.task?.trim())throw new Error("Capability discovery requires task or capability");let n=e.task?.trim()?Zp({task:e.task.trim(),operation:"associate capability"}):null;if(i){let d=Qa(i,e.scope.workflow),f=await ih(t,e.scope,d),p={workflow:e.scope.workflow,capability:d,currentSpec:f,historicalSources:[],matchedTerms:[d],confidence:"high",score:1,reason:"用户显式指定能力,已直接核对当前总 Spec 路径。",evidence:[{source:f.source,kind:`${e.scope.workflow}-spec`}]};return{workflow:e.scope.workflow,query:n,candidates:[p],associationDraft:rh(p,n,"explicit"),diagnostics:r,searched:!1,providerLimit:Xa}}if(!e.provider)throw new Error("Capability discovery requires a Project Knowledge provider for task search");let a;try{a=await e.provider.query({kind:"search",query:n,limit:Xa})}catch(d){return r.push({code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${d instanceof Error?d.message:String(d)}`}),nh(e.scope,n,r,!0)}if(a.kind!=="search")return nh(e.scope,n,a.diagnostics,!0);r.push(...a.diagnostics);let o=new Map;for(let[d,f]of a.results.entries())for(let p of tS(f)){let m=Qk(e.scope,p.source);if(!m)continue;let h=rS(o,e.scope,m.capability),v=n.terms.filter(w=>eh(p.searchableText,w));for(let w of v)h.matchedTerms.add(w);h.bestScore=Math.max(h.bestScore,p.resultScore),h.bestRank=Math.min(h.bestRank,d),m.kind==="current"?h.currentHits+=1:(h.historicalHits+=1,h.historicalSources.add(m.source)),h.evidence.has(m.source)||h.evidence.set(m.source,{source:m.source,kind:m.kind==="current"?`${e.scope.workflow}-spec`:`${e.scope.workflow}-archive`,...p.title?{title:p.title}:{},...p.snippet?{snippet:p.snippet}:{}})}let s=Math.max(1,Math.min(th,e.limit??th)),c=[],l=[...o.values()].sort((d,f)=>f.currentHits-d.currentHits||f.matchedTerms.size-d.matchedTerms.size||f.bestScore-d.bestScore||d.bestRank-f.bestRank||d.capability.localeCompare(f.capability));for(let d of l.slice(0,s)){let f;try{f=await ih(t,e.scope,d.capability)}catch(h){r.push({code:"capability-stale",message:`候选 ${d.capability} 没有可核对的当前总 Spec,已排除:${h instanceof Error?h.message:String(h)}`});continue}let p=iS(d,n),m={workflow:e.scope.workflow,capability:d.capability,currentSpec:f,historicalSources:[...d.historicalSources].sort(),matchedTerms:[...d.matchedTerms],confidence:p,score:aS(d,n),reason:nS(d,p),evidence:oS(d.evidence)};c.push(m)}c.sort((d,f)=>f.score-d.score||d.capability.localeCompare(f.capability));let u=c.length===1&&c[0].confidence==="high"?rh(c[0],n,"suggested"):null;return{workflow:e.scope.workflow,query:n,candidates:c,associationDraft:u,diagnostics:r,searched:!0,providerLimit:Xa}}function oh(e){return(0,pl.stringify)({schema:e.schema,status:e.status,workflow:e.workflow,capability:e.capability,current_spec:e.current_spec,current_hash:e.current_hash,confidence:e.confidence,...e.query===void 0?{}:{query:e.query},reason:e.reason,historical_sources:[...e.historical_sources],evidence:e.evidence.map(t=>({source:t.source,kind:t.kind,...t.title===void 0?{}:{title:t.title},...t.snippet===void 0?{}:{snippet:t.snippet}}))})}xe();no();st();tr();import{createHash as Oh}from"node:crypto";import{promises as Dr}from"node:fs";import W from"node:path";Je();import{createHash as AS}from"node:crypto";import{AsyncLocalStorage as IS}from"node:async_hooks";import ao from"node:path";function oo(...e){if(e.length===0)return ao.resolve();if(ao.win32.isAbsolute(e[0])){let t=ao.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return ao.resolve(...e)}var TS=new IS;function jS(e,t){let r=oo(e),i=t.runGit??re,n=TS.getStore(),a=n?.active?n.observations:void 0,o=a?.get(r)?.get(i);if(o)return o;let s=r;try{let l=i(r,["remote","get-url","origin"]).trim();if(l)s=l;else throw new Error("No origin")}catch{try{let l=i(r,["rev-parse","--git-common-dir"]).trim();l&&(s=oo(r,l))}catch{}}let c={identity:Nh(s),name:HS(s)};if(a){let l=a.get(r)??new Map;l.set(i,c),a.set(r,l)}return c}function $S(e,t={}){return jS(e,t).identity}function OS(e){let t=Nh(e),i=(t.split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project",n=AS("sha256").update(t,"utf8").digest("hex").slice(0,8);return`${i.slice(0,40)}-${n}`}function yh(e,t={}){return OS($S(e,t))}function HS(e){return(e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-zA-Z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project"}function Nh(e){let t=e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").toLocaleLowerCase();return t||"project"}var ut=class extends Error{code;constructor(t,r,i){super(r,i),this.name="BoundedHttpRequestError",this.code=t}};async function DS(e,t){if(!e.body){let s=new Uint8Array(await e.arrayBuffer());if(s.byteLength>t)throw new ut("response-too-large","HTTP response exceeds byte limit");return s}let r=e.body.getReader(),i=[],n=0;try{for(;;){let s=await r.read();if(s.done)break;if(n+=s.value.byteLength,n>t)throw await r.cancel(),new ut("response-too-large","HTTP response exceeds byte limit");i.push(s.value)}}finally{r.releaseLock()}let a=new Uint8Array(n),o=0;for(let s of i)a.set(s,o),o+=s.byteLength;return a}async function bh(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e.timeoutMs);try{let i=await(e.fetch??globalThis.fetch)(e.url,{...e.init,signal:t.signal}),n=i.ok?await DS(i,e.maxResponseBytes):new Uint8Array;return{response:i,bytes:n}}catch(i){throw i instanceof ut?i:t.signal.aborted?new ut("timeout","HTTP request timed out",{cause:i}):new ut("request-failed","HTTP request failed",{cause:i})}finally{clearTimeout(r)}}import kh from"node:path";var LS=/^[a-z0-9][a-z0-9._-]{1,127}$/u,Ch=2e3,BS=1024,MS=32,FS=32,VS=32,qS=16,WS=16,Ph=32,zS=128,KS=32,GS=new Set(["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"]),JS=new Set(["trial","proven","enforced","superseded"]),US=new Set(["automatic","user","repository"]),YS=new Set(["contains","depends-on","consumes","registers","propagates-to","generated-by","validated-by","supersedes"]);function Hr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ne(e,t,r=Ch){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e.trim()}function xl(e,t){let r=Ne(e,t,128);if(!LS.test(r))throw new Error(`${t} must use a stable record id`);return r}function Or(e,t,r,i){if(e===void 0)return[];if(!Array.isArray(e)||e.length>r)throw new Error(`${t} must be a bounded list`);return e.map((n,a)=>i(n,a))}function Rh(e,t,r,i){if(!Array.isArray(e)||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty bounded list`);return e.map((n,a)=>i(n,a))}function Pl(e,t){let r=Ne(e,t,BS).replaceAll("\\","/");if(kh.posix.isAbsolute(r)||kh.win32.isAbsolute(r)||r.includes("\0")||r.split("/").some(i=>i===".."))throw new Error(`${t} must be a project-relative path`);return r}function XS(e,t,r=MS){return Or(e,t,r,(i,n)=>Pl(i,`${t}[${n}]`))}function Sh(e,t,r=FS){return Or(e,t,r,(i,n)=>Ne(i,`${t}[${n}]`,512))}function Cl(e,t,r=Ch){if(e!==void 0)return Ne(e,t,r)}function Eh(e,t){if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error(`${t} must be a positive integer`);return Number(e)}function Ui(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw new Error(`${t} must be a non-negative integer`);return Number(e)}function _h(e,t){let r=Hr(e,t),i=r.lineStart,n=r.lineEnd,a=i===void 0?void 0:Eh(i,`${t}.lineStart`),o=n===void 0?void 0:Eh(n,`${t}.lineEnd`);if(a!==void 0&&o!==void 0&&o<a)throw new Error(`${t}.lineEnd must be greater than or equal to lineStart`);let s=Cl(r.anchor,`${t}.anchor`,256),c=Cl(r.evidence,`${t}.evidence`,1024);return{source:Pl(r.source,`${t}.source`),...s===void 0?{}:{anchor:s},...a===void 0?{}:{lineStart:a},...o===void 0?{}:{lineEnd:o},...c===void 0?{}:{evidence:c}}}function QS(e,t){let r=Hr(e,`conclusions[${t}]`);return{text:Ne(r.text,`conclusions[${t}].text`),sources:Rh(r.sources,`conclusions[${t}].sources`,Ph,(i,n)=>_h(i,`conclusions[${t}].sources[${n}]`))}}function ZS(e,t){let r=Hr(e,`relations[${t}]`),i=Ne(r.type,`relations[${t}].type`,64);if(!YS.has(i))throw new Error(`relations[${t}].type is unsupported`);return{type:i,targetId:xl(r.targetId,`relations[${t}].targetId`),sources:Rh(r.sources,`relations[${t}].sources`,Ph,(n,a)=>_h(n,`relations[${t}].sources[${a}]`))}}function eE(e,t){let r=Hr(e,`verification[${t}]`),i=Cl(r.expected,`verification[${t}].expected`);return{command:Ne(r.command,`verification[${t}].command`),...i===void 0?{}:{expected:i}}}function tE(e,t){let r=Hr(e,`sourceVersions[${t}]`),i=r.digest;if(i!==void 0&&(typeof i!="string"||!/^[a-f0-9]{64}$/u.test(i)))throw new Error(`sourceVersions[${t}].digest must be a SHA-256 hash`);return{source:Pl(r.source,`sourceVersions[${t}].source`),size:Ui(r.size,`sourceVersions[${t}].size`),modifiedAt:Ui(r.modifiedAt,`sourceVersions[${t}].modifiedAt`),...i===void 0?{}:{digest:i}}}function rE(e,t){return e.reduce((r,i)=>r+i.sources.length,0)+t.reduce((r,i)=>r+i.sources.length,0)}function xh(e){let t=Ne(e,"updatedAt",64);if(Number.isNaN(Date.parse(t)))throw new Error("updatedAt must be an ISO-8601 timestamp");return t}function iE(e){let t=Hr(e,"record"),r=Ne(t.type,"type",64);if(!GS.has(r))throw new Error("type is unsupported");let i=Ne(t.state,"state",32);if(!JS.has(i))throw new Error("state is unsupported");let n=Ne(t.authority,"authority",32);if(!US.has(n))throw new Error("authority is unsupported");let a=Or(t.conclusions,"conclusions",VS,QS),o=Or(t.relations,"relations",qS,ZS);if(rE(a,o)>zS)throw new Error("conclusions/relations sources exceed the bounded total reference count");let s=Or(t.sourceVersions,"sourceVersions",KS,tE);if(new Set(s.map(c=>c.source)).size!==s.length)throw new Error("sourceVersions must not contain duplicate sources");return{id:xl(t.id,"id"),projectId:xl(t.projectId,"projectId"),type:r,state:i,authority:n,title:Ne(t.title,"title"),summary:Ne(t.summary,"summary"),applicablePaths:XS(t.applicablePaths,"applicablePaths"),operations:Sh(t.operations,"operations"),phases:Sh(t.phases,"phases"),conclusions:a,relations:o,verification:Or(t.verification,"verification",WS,eE),sourceVersions:s,applicationCount:Ui(t.applicationCount,"applicationCount"),successCount:Ui(t.successCount,"successCount"),failureCount:Ui(t.failureCount,"failureCount"),...t.lastAppliedAt===void 0?{}:{lastAppliedAt:xh(t.lastAppliedAt)},updatedAt:xh(t.updatedAt)}}function Ht(e){return iE(e)}var nE=1024*1024,aE=512,jh=200,$h=1600,oE=5e3,sE=8,cE=512*1024,lE=32;function A(e,t,r=!1){if(typeof e!="string")return null;let i=[...e].map(n=>{let a=n.codePointAt(0)??0;return a<32||a===127?" ":n}).join("").trim().slice(0,t);return r&&!i?null:i}function _l(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))return null;let r=A(t.code,64,!0),i=A(t.message,240,!0);return r&&i?{code:r,message:i}:null}).filter(t=>t!==null).slice(0,sE):[]}function Yi(){return[]}function Ah(e){let t={...e};return delete t.evidence,t}function Ih(e){return{...e,conclusions:e.conclusions.map(t=>({...t,sources:t.sources.map(Ah)})),relations:e.relations.map(t=>({...t,sources:t.sources.map(Ah)}))}}function uE(e){if(e.kind==="upsert")return{kind:"upsert",record:Ih(e.record)};if(e.kind!=="experience-delta")return e;let t=e.delta,r=t.payload;r?.kind==="record"?r={kind:"record",record:Ih(Ht(r.record))}:r?.kind==="verify"?r={kind:"verify",projectId:A(r.projectId,128)??"",commands:Xi(r.commands,16,2e3),...typeof r.updatedAt=="string"?{updatedAt:r.updatedAt.slice(0,64)}:{}}:r!==void 0&&(r=void 0);let{payload:i,...n}=t,a={...n,statement:A(t.statement,4e3)??"",...t.title===void 0?{}:{title:A(t.title,512)??""},applicability:{...t.applicability.projectId===void 0?{}:{projectId:A(t.applicability.projectId,128)??""},...t.applicability.paths===void 0?{}:{paths:Xi(t.applicability.paths,32,512)},...t.applicability.operations===void 0?{}:{operations:Xi(t.applicability.operations,16,128)},...t.applicability.phases===void 0?{}:{phases:Xi(t.applicability.phases,16,128)},...t.applicability.tasks===void 0?{}:{tasks:Xi(t.applicability.tasks,16,512)}},evidence:t.evidence.slice(0,lE).map(o=>({...o,summary:A(o.summary,1e3)??"",...o.source===void 0?{}:{source:A(o.source,512)??""},...o.anchor===void 0?{}:{anchor:A(o.anchor,256)??""},...o.command===void 0?{}:{command:A(o.command,2e3)??""}})),...r===void 0?{}:{payload:r}};return{...e,idempotencyKey:A(e.idempotencyKey,256,!0)??"invalid",delta:a}}function Xi(e,t,r){return Array.isArray(e)?e.map(i=>A(i,r)).filter(i=>!!i).slice(0,t):[]}function dE(e){if(e.kind==="search"){let t=e.query;return{kind:"search",task:A(t.task,2e3)??"",...t.path?{path:A(t.path,512)}:{},...t.phase?{phase:A(t.phase,128)}:{},...t.operation?{operation:A(t.operation,128)}:{},terms:t.terms.slice(0,28).map(r=>A(r,128)).filter(Boolean),limit:Math.max(1,Math.min(8,e.limit??8))}}return e.kind==="list"?{kind:"list",...e.projectId?{projectId:A(e.projectId,128)}:{},...e.type?{type:e.type}:{},...e.state?{state:e.state}:{},...e.authority?{authority:e.authority}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="manifest"?{kind:"manifest",...e.projectId?{projectId:A(e.projectId,128)}:{},...e.state?{state:e.state}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="expand"?{kind:"expand",id:A(e.id,128)??"",...e.projectId?{projectId:A(e.projectId,128)}:{}}:{kind:"get",id:A(e.id,128)??"",...e.projectId?{projectId:A(e.projectId,128)}:{}}}function Rl(e,t,r){if(!Array.isArray(e))return[];let i=[];for(let n of e.slice(0,500))try{let a=Ht(n);if(a.projectId!==r)throw new Error("Project mismatch");i.push(a)}catch{t()}return i}function fE(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return t(),null;let i=A(e.content,$h,!0),n=A(e.source,aE,!0);if(!i||!n)return t(),null;let a=e.title,o=a===void 0?void 0:A(a,jh);if(a!==void 0&&o===null)return t(),null;let s=e.score;if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)))return t(),null;let c,l=e.record;if(l!==void 0)try{if(c=Ht(l),c.projectId!==r)throw new Error("Project mismatch")}catch{return t(),null}return{content:i,source:n,...o?{title:o}:{},...s===void 0?{}:{score:s},...c?{record:c}:{}}}function pE(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)&&"status"in e?e.status:e;if(!r||typeof r!="object"||Array.isArray(r))return t(),null;let i=r.provider,n=r.healthy,a=r.writable;if(i!=="remote"||typeof n!="boolean"||typeof a!="boolean")return t(),null;let o=r.recordCount,s=r.updatedAt;return{provider:"remote",healthy:n,writable:a,...Number.isSafeInteger(o)&&Number(o)>=0?{recordCount:Number(o)}:{},...typeof s=="string"?{updatedAt:s.slice(0,64)}:{},diagnostics:_l(r.diagnostics)}}function hE(e,t,r,i){let n=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.kind??t.kind,o=_l(n.diagnostics);if(a==="list")return{kind:"list",records:Rl(n.records,r,i),truncated:n.truncated===!0,diagnostics:o};if(a==="get"){let f=n.record,p=null;if(f!=null)try{if(p=Ht(f),p.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"get",record:p,diagnostics:o}}if(a==="expand"){let f=n.record,p=null;if(f!=null)try{if(p=Ht(f),p.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"expand",record:p,diagnostics:o}}if(a==="manifest")return{kind:"manifest",items:Array.isArray(n.items)?n.items.slice(0,500).flatMap(p=>{if(!p||typeof p!="object"||Array.isArray(p))return r(),[];let m=p,h=A(m.id,128,!0),v=A(m.title,jh,!0),w=A(m.summary,$h,!0),y=m.type,k=m.memoryType,E=m.state,x=m.authority;if(!h||!v||!w||!["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"].includes(String(y))||k!=="project-model"&&k!=="project-policy"||!["trial","proven","enforced","superseded"].includes(String(E))||!["automatic","user","repository"].includes(String(x)))return r(),[];let g=N=>Array.isArray(N)?N.map(I=>A(I,1024)).filter(I=>I!==null):[],R=Array.isArray(m.verification)?m.verification.slice(0,16).flatMap(N=>{if(!N||typeof N!="object"||Array.isArray(N))return r(),[];let I=A(N.command,4e3,!0),Z=A(N.expected,2e3);return I?[{command:I,...Z===null?{}:{expected:Z}}]:[]}):[];return[{id:h,memoryType:k,type:y,state:E,authority:x,title:v,summary:w,applicablePaths:g(m.applicablePaths),operations:g(m.operations),phases:g(m.phases),sourceTypes:g(m.sourceTypes),verification:R}]}):[],truncated:n.truncated===!0,diagnostics:o};let s=[],c=0,l=new Set;for(let f of Array.isArray(n.results)?(n.results??[]).slice(0,16):[]){let p=fE(f,r,i);if(!(!p||l.has(`${p.source}\0${p.title??""}`))){if(c+p.content.length>oE)break;l.add(`${p.source}\0${p.title??""}`),c+=p.content.length,s.push(p)}}let u=Rl(n.records,r,i);return{kind:"search",hits:Array.isArray(n.hits)?(n.hits??[]).slice(0,40).flatMap(f=>{if(!f||typeof f!="object"||Array.isArray(f))return r(),[];try{let p=Ht(f.record);if(p.projectId!==i)throw new Error("Project mismatch");let m=f.score;return m!==void 0&&(typeof m!="number"||!Number.isFinite(m))?(r(),[]):[{record:p,...m===void 0?{}:{score:m}}]}catch{return r(),[]}}):u.map(f=>({record:f})),results:s,records:u,truncated:n.truncated===!0,diagnostics:o}}function mE(e,t,r,i){let n=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.record,o;if(a===null)o=null;else if(a!==void 0)try{if(o=Ht(a),o.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:t.kind,changed:n.changed===!0,...o===void 0?{}:{record:o},...Array.isArray(n.records)?{records:Rl(n.records,r,i)}:{},diagnostics:_l(n.diagnostics)}}var so=class{options;projectId;constructor(t){this.options=t,this.projectId=t.projectId??(t.projectRoot?yh(t.projectRoot):"project")}async status(){let t=this.options.config.token_env;if(t&&!this.token()){let a={code:"remote-token",message:`Remote Project Knowledge 未配置环境变量 ${t}。`};return this.report(a.code,a.message),{provider:"remote",healthy:!1,writable:!1,diagnostics:[a]}}let r=await this.request("status",{});if(r===null)return{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let i={value:!1},n=pE(r,()=>{i.value=!0});return!n||i.value?(this.report("remote-schema","Remote Project Knowledge status 响应格式无效。"),{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge status 响应格式无效。"}]}):n}async query(t){let r=t.kind==="search"?this.projectId:t.projectId??this.projectId,i=await this.request("query",dE(t),t.kind==="search"?void 0:t.projectId);if(i===null)return Th(t);let n={value:!1},a=hE(i,t,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge query 响应包含无效数据。"),Th(t)):a}async apply(t){let r=(t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId)??this.projectId,i=await this.request("apply",uE(t),t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId);if(i===null)return{kind:t.kind,changed:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let n={value:!1},a=mE(i,t,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge apply 响应格式无效。"),{kind:t.kind,changed:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge apply 响应格式无效。"}]}):a}async request(t,r,i=this.projectId){let n=this.options.config.token_env,a=this.token();if(n&&!a)return this.report("remote-token",`Remote Project Knowledge 未配置环境变量 ${n}。`),null;let o={schema:"comet.project-knowledge.provider.v1",operation:t,...this.options.config.scope?{scope:this.options.config.scope}:{},projectId:A(i,128,!0)??this.projectId,input:r},s=JSON.stringify(o);if(new TextEncoder().encode(s).byteLength>cE)return this.report("remote-request-size","Remote Project Knowledge 请求超过大小限制。"),null;try{let{response:c,bytes:l}=await bh({url:this.options.config.endpoint,timeoutMs:this.options.config.timeout_ms,maxResponseBytes:nE,fetch:this.options.fetch,init:{method:"POST",redirect:"error",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:s}});if(!c.ok)return this.report("remote-status",`Remote Project Knowledge 返回 HTTP ${c.status}。`),null;try{let u=JSON.parse(new TextDecoder().decode(l));return vE(u,t,o.projectId)?u.result:(this.report("remote-schema","Remote Project Knowledge 响应 envelope 无效。"),null)}catch{return this.report("remote-json","Remote Project Knowledge 返回了无效 JSON。"),null}}catch(c){return this.report("remote-failed",c instanceof ut&&c.code==="timeout"?"Remote Project Knowledge 请求超时。":"Remote Project Knowledge 请求失败。"),null}}report(t,r){this.options.reportDiagnostic?.({code:t,message:r})}token(){let t=this.options.config.token_env;return t?this.options.env?.[t]??process.env[t]:void 0}};function vE(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;let i=e;return i.schema==="comet.project-knowledge.provider.v1"&&i.operation===t&&i.projectId===r&&Object.prototype.hasOwnProperty.call(i,"result")}function Th(e){return e.kind==="list"?{kind:"list",records:[],truncated:!1,diagnostics:Yi()}:e.kind==="get"?{kind:"get",record:null,diagnostics:Yi()}:e.kind==="expand"?{kind:"expand",record:null,diagnostics:Yi()}:e.kind==="manifest"?{kind:"manifest",items:[],truncated:!1,diagnostics:Yi()}:{kind:"search",hits:[],results:[],records:[],truncated:!1,diagnostics:Yi()}}var Hh=512,Al=256*1024,Lh=8*1024*1024,gE=2e3,Bh=W.join(".comet","runtime","native","capability-discovery-cache.json"),Qi="comet.native.capability-cache.v1",Mh=512*1024,Fh=32;function Il(e,t){let r=W.relative(W.resolve(e),W.resolve(t));return r===""||!W.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${W.sep}`)}function wE(e,t){return W.relative(e,t).replaceAll(W.sep,"/")}function yE(e,t,r){e?.({code:t,message:r})}async function NE(e,t){if(!Il(t,e))return!1;try{let r=await Dr.lstat(e);return!r.isDirectory()||r.isSymbolicLink()?!1:Il(await Dr.realpath(t),await Dr.realpath(e))}catch{return!1}}async function jl(e){let t=W.resolve(e.projectRoot),r=Date.now()+gE,i=[],n=!0,a=0,o=async(c,l)=>{if(Date.now()>r){n=!1;return}if(!await NE(c,t))return;let u=async d=>{if(Date.now()>r||i.length>=Hh){n=!1;return}let f;try{f=await Dr.readdir(d,{withFileTypes:!0})}catch{n=!1;return}for(let p of f.sort((m,h)=>m.name.localeCompare(h.name,"en"))){if(Date.now()>r){n=!1;return}if(p.isSymbolicLink())continue;let m=W.join(d,p.name);if(p.isDirectory()){await u(m);continue}if(!p.isFile()||!p.name.toLowerCase().endsWith(".md")||!Il(t,m))continue;let h=await Dr.stat(m);if(h.size>Al)continue;if(a+h.size>Lh){n=!1;return}if(Date.now()>r){n=!1;return}let v=wE(t,m),w;try{w=await ee(t,v,Al,{label:`${l} capability Spec`})}catch{n=!1;continue}if(a+=w.bytes.length,i.push({absolutePath:m,source:v,kind:l,size:h.size,mtimeMs:h.mtimeMs,contentHash:Oh("sha256").update(w.bytes).digest("hex")}),i.length>=Hh){n=!1;return}}};await u(c)};await o(W.resolve(t,...e.scope.currentSpecRoot.split("/")),"native-spec"),await o(W.resolve(t,...e.scope.archiveRoot.split("/")),"native-archive"),i.sort((c,l)=>c.source.localeCompare(l.source,"en"));let s=Oh("sha256").update(JSON.stringify(i.map(({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})=>({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})))).digest("hex");return n||yE(e.reportDiagnostic,"capability-corpus-limit","能力候选语料发现达到时间或文件数量上限,当前结果可能不完整。"),{sources:i,fingerprint:s,complete:n}}function Dh(e){return/^(?:#)\s+(.+)$/mu.exec(e)?.[1]?.trim()}function bE(e,t,r){let i=`${t}
|
|
199
|
-
${e}`.toLocaleLowerCase();return r.reduce((n,a)=>n+(i.includes(a.toLocaleLowerCase())?1:0),0)}var Tl=class{constructor(t,r,i){this.projectRoot=t;this.manifest=r;this.reportDiagnostic=i}projectRoot;manifest;reportDiagnostic;async status(){return{provider:"local",healthy:!0,writable:!1,diagnostics:[]}}async query(t){if(t.kind!=="search")throw new Error("Native capability discovery only supports search queries");let r=[],i=[],n=0;for(let a of this.manifest.sources){if(n+a.size>Lh){r.push({code:"capability-corpus-bytes",message:"能力候选语料达到总字节预算,剩余来源不会参与本次召回。"});break}try{let o=await ee(this.projectRoot,a.source,Al,{label:`${a.kind} capability Spec`});n+=o.bytes.length;let s=o.bytes.toString("utf8"),c=bE(s,a.source,t.query.terms);if(c===0)continue;let l={absolutePath:a.absolutePath,source:a.source,kind:a.kind};i.push({content:s,source:a.source,...Dh(s)?{title:Dh(s)}:{},score:c,document:l})}catch(o){let s={code:"capability-corpus-read",message:`能力候选来源无法读取,已跳过 ${a.source}:${o instanceof Error?o.message:String(o)}`};r.push(s),this.reportDiagnostic?.(s)}}return i.sort((a,o)=>o.score-a.score||a.source.localeCompare(o.source)),{kind:"search",hits:[],results:i,records:[],truncated:!this.manifest.complete,diagnostics:r}}async apply(t){throw new Error("Native capability discovery is read-only")}};async function Vh(e){let r=(await er(e.projectRoot))?.knowledge;if(r?.provider==="remote"){if(!r.remote)throw new Error("Configured remote Project Knowledge provider is missing remote settings");return new so({config:r.remote,projectRoot:e.projectRoot,...e.reportDiagnostic?{reportDiagnostic:e.reportDiagnostic}:{}})}let i=await jl(e);return new Tl(W.resolve(e.projectRoot),i,e.reportDiagnostic)}function qh(e){return JSON.stringify({workflow:e.scope.workflow,currentSpecRoot:e.scope.currentSpecRoot,archiveRoot:e.scope.archiveRoot,task:e.task.trim()})}function kE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.workflow==="native"&&(t.query===null||typeof t.query=="object"&&t.query!==null)&&Array.isArray(t.candidates)&&t.candidates.length<=5&&(t.associationDraft===null||typeof t.associationDraft=="object"&&t.associationDraft!==null)&&Array.isArray(t.diagnostics)&&typeof t.searched=="boolean"&&t.providerLimit===40}function SE(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema!==Qi||!Array.isArray(t.entries)||t.entries.length>Fh)return null;let r=[];for(let i of t.entries){if(!i||typeof i!="object"||Array.isArray(i))return null;let n=i;if(typeof n.key!="string"||typeof n.fingerprint!="string"||!kE(n.result))return null;r.push({key:n.key,fingerprint:n.fingerprint,result:n.result})}return{schema:Qi,entries:r}}async function Wh(e){try{let t=await Dr.readFile(W.join(e,Bh),"utf8");return Buffer.byteLength(t,"utf8")>Mh?null:SE(JSON.parse(t))}catch{return null}}async function zh(e){let t=W.resolve(e.projectRoot);if((await er(t))?.knowledge?.provider==="remote")return null;let i=await jl({projectRoot:t,scope:e.scope});return i.complete?(await Wh(t))?.entries.find(o=>o.key===qh(e)&&o.fingerprint===i.fingerprint)?.result??null:null}async function Kh(e){let t=W.resolve(e.projectRoot);if((await er(t))?.knowledge?.provider==="remote")return;let i=await jl({projectRoot:t,scope:e.scope});if(!i.complete)return;let n=await Wh(t)??{schema:Qi,entries:[]},a=qh(e),o=[{key:a,fingerprint:i.fingerprint,result:e.result},...n.entries.filter(l=>!(l.key===a&&l.fingerprint===i.fingerprint))].slice(0,Fh),s=JSON.stringify({schema:Qi,entries:o});if(Buffer.byteLength(s,"utf8")>Mh)return;let{atomicWriteJson:c}=await Promise.resolve().then(()=>(D(),Gp));await c(W.join(t,Bh),{schema:Qi,entries:o},{containedRoot:W.join(t,".comet","runtime","native")})}H();en();ir();function se(e,t,r){return e.language==="zh-CN"?r:t}function RE(e,t,r){let i=n=>({required:!1,message:null,suggestedReply:null,agentInstruction:n});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:se(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:se(e,"Reply A or B","回复 A 或 B"),agentInstruction:se(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(se(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(se(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:n})=>n==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let a=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",o=a?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=a?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:o,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:se(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:se(e,"Accept the result","接受结果"),agentInstruction:se(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let n=r?.children.some(({status:c})=>c==="blocked")??!1,a=r?.children.some(({status:c})=>c==="needs-reverify")??!1,o=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=uo)??!1;return n&&!a&&!o&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i(se(e,"Implement the confirmed scope and run focused checks. A separate pre-review is optional, not a prerequisite for Builder handoff. If review is useful, retain the same Reviewer for focused repair follow-ups rather than starting repeated full reviews. Submit the stable candidate for one complete independent verification; release completed helper tasks.","实现已确认范围并运行相关检查。额外预审是可选项,不是 Builder 交接的前置条件。确有必要审查时,保留同一个 Reviewer 复核修复及受影响范围,避免反复启动完整审查。候选稳定后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i(se(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function _E(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function AE(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:se(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:se(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Xh(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function nr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Jh(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function IE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Uh(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function TE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function jE(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Dt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Xh({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[nr("summary","--summary"),IE(e.name,e.flag)]}}function Yh(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:se(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function $E(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function fo(e){return[Dt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Dt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function OE(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function Qh(e,t,r={}){let i=TE(t)&&e.coordination_mode===void 0,n=RE(e,i,t),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[nr("summary","--summary")],commandAlternatives:[Dt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[nr("summary","--summary")],commandAlternatives:[Dt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...fo({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[nr("summary","--summary")],commandAlternatives:[Dt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Dt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[nr("summary","--summary")],commandAlternatives:[Dt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...fo({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[nr("summary","--summary")],commandAlternatives:fo({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:fo({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Xh({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:jE({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Uh("coordination-mode","--coordination-mode",Gh)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,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:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"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}],verification_checks:[Jh()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=uo)??null,f=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:se(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&f===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:f!==null?[f]:[nr("summary","--summary")],runnerAction:o("none")}}return{...a,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}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=Jh();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${se(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:OE([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Yh(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>$E(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:Yh(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Uh("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...AE(e)],userCommunication:_E(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Dt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{promises as fx}from"node:fs";import ql from"node:path";import{execFileSync as HE}from"child_process";import DE from"fs";import po from"path";function dt(e,t){return HE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Lt(e,t){return Zh(e)===Zh(t)}function Zh(e){let t=po.resolve(e);try{let r=DE.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function he(e){try{let t=po.resolve(dt(e,["rev-parse","--show-toplevel"])),i=dt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?po.resolve(i.slice(9)):t,a=null;try{a=dt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Lt(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ho(e){try{dt(e,["rev-parse","--is-inside-work-tree"]);let t=dt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:po.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function ar(e){return ho(e).map(t=>t.root)}function em(e){try{return dt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function Br(e,t){try{return dt(e,["check-ref-format","--branch",t]),dt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function or(e,t){try{let r=dt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}Je();D();en();import{promises as LE}from"node:fs";import BE from"node:os";import an from"node:path";function rn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function nn(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ce(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Mr(e,t){return e===null?null:ce(e,t)}function Fr(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function ME(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 FE(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Vr(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ll(e,t){if(e===null)return null;let r=ce(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function VE(e,t){let r=ce(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Bl(e,t){let r=ce(e,t);if(!an.isAbsolute(r))throw new Error(`${t} must be absolute`);return an.resolve(r)}function qE(e,t){let r=`Native local checks[${t}]`,i=rn(e,r);if(nn(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>ce(u,`${r}.argv[${d}]`,!0)),a=Vr(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Ll(i.startedAt,`${r}.startedAt`),s=Ll(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Fr(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=rn(i.activeProcess,`${r}.activeProcess`),d=Vr(u.status,["starting","running"],`${r}.activeProcess.status`);if(nn(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:Fr(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:ce(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:ce(i.id,`${r}.id`),name:ce(i.name,`${r}.name`),operationId:ce(i.operationId,`${r}.operationId`),status:a,repeatable:FE(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Fr(i.executionCount,`${r}.executionCount`),argv:n,cwd:Bl(i.cwd,`${r}.cwd`),exitCode:ME(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:ce(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:Vr(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:ce(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function tm(e){let t="Native local execution state",r=rn(e,t);if(nn(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Zi)throw new Error(`Native local execution schema must be ${Zi}`);let i=rn(r.workspace,"Native local workspace");nn(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=rn(r.execution,"Native local execution");nn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Ll(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:ce(o.operationId,"Native local execution.operationId"),stage:Vr(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Vr(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Mr(o.executionId,"Native local execution.executionId"),status:Vr(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Fr(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:VE(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Fr(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:ce(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(qE);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:Zi,change:ce(r.change,"Native local change"),basedOnStateVersion:Fr(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Mr(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Mr(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Mr(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Mr(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Bl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Bl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Mr(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:ce(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function sr(e){return tm({schema:Zi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:an.resolve(e.projectRoot),worktreeRoot:an.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:BE.hostname()},execution:null,checks:[]})}async function cr(e,t,r={}){let i=tm(t);await LE.mkdir(an.dirname(e),{recursive:!0}),await ae(e,i,r)}Bt();H();var Wl=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,om="comet-state.yaml",sm="state.json";function Ye(e,t){if(!Wl.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ql.join(e.changesDir,t);if(!X(e.changesDir,r))throw new Error("Native change path escaped");return r}function on(e,t){return ql.join(Ye(e,t),om)}function Mt(e,t){return ql.join(Oe(e,t),sm)}async function zl(e,t){try{let r=await fx.readFile(on(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function cm(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function ur(e){return em(e)}function lm(e,t){if(!t)return;let r=he(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function ft(e,t){return Vl(on(e,t))}D();import{promises as hr}from"node:fs";import Dv from"node:path";dr();var Su=Nt(nt(),1);import{promises as Go}from"fs";import Ve from"path";xe();D();dr();we();Q();H();Qe();wn();Q();H();Ir();Tt();var bP=Nt(nt(),1);Ir();Tt();st();st();tr();nl();Ir();st();import{promises as kP}from"node:fs";import SP from"node:path";var Qr=".gitignore",hu=4*1024*1024,vu="# >>> Comet managed project state >>>",cv="# <<< Comet managed project state <<<";function EP(e){return e.includes(`\r
|
|
213
|
+
`)).digest("hex")}function PE(e){let t=typeof e.score=="number"&&Number.isFinite(e.score)?e.score:0,r={source:e.source,kind:e.document?.kind??"project-knowledge",...e.title?{title:e.title}:{},snippet:e.content.slice(0,bE),searchableText:[e.source,e.title??"",e.content,e.record?.summary??""].join(`
|
|
214
|
+
`),resultScore:t,resultRank:0},n=e.record?[...e.record.conclusions,...e.record.relations].flatMap(i=>i.sources):[];return[r,...n.map((i,a)=>({source:i.source,kind:"record-reference",searchableText:[i.source,e.title??"",e.content,e.record?.summary??""].join(`
|
|
215
|
+
`),resultScore:t,resultRank:a+1}))]}function RE(e,t,r){let n=`${t.workflow}\0${r}`,i=e.get(n);if(i)return i;let a={workflow:t.workflow,capability:r,historicalSources:new Set,matchedTerms:new Set,evidence:new Map,currentHits:0,historicalHits:0,bestScore:0,bestRank:Number.MAX_SAFE_INTEGER};return e.set(n,a),a}function _E(e,t){let r=t.terms.some(n=>n.toLocaleLowerCase()===e.capability.toLocaleLowerCase());return e.currentHits>0&&(e.matchedTerms.size>=2||r)?"high":e.currentHits>0?"medium":"low"}function AE(e,t){let r=e.currentHits>0?"当前总 Spec 已命中":"检索命中历史 change",n=e.historicalSources.size?`,并找到 ${e.historicalSources.size} 个历史来源`:"";return`${r}${n};已核对当前能力文件,匹配 ${e.matchedTerms.size} 个查询词(${t})`}function IE(e,t){let r=e.matchedTerms.size/Math.max(1,t.terms.length);return Math.min(1,(e.currentHits>0?.5:.15)+Math.min(.3,r*.3)+Math.min(.15,Math.max(0,e.bestScore)*.15)+Math.min(.05,e.historicalSources.size*.02))}function TE(e){return[...e.values()].sort((t,r)=>{let n=t.kind.endsWith("-spec")?0:1,i=r.kind.endsWith("-spec")?0:1;return n-i||t.source.localeCompare(r.source)}).slice(0,yE)}function nm(e,t,r){return{schema:"comet.capability-association.v1",status:r,workflow:e.workflow,capability:e.capability,current_spec:e.currentSpec.source,current_hash:e.currentSpec.hash,confidence:e.confidence,...t?{query:t.task}:{},reason:e.reason,historical_sources:[...e.historicalSources],evidence:e.evidence}}async function im(e,t,r){let n=xE(t,r),i=await Z(e,n,NE,{label:`${t.workflow} current capability Spec`});return{source:n,hash:CE(i.bytes)}}function am(e,t,r,n){return{workflow:e.workflow,query:t,candidates:[],associationDraft:null,diagnostics:r,searched:n,providerLimit:Ao}}async function om(e){let t=wE.resolve(e.projectRoot),r=[],n=e.capability?.trim();if(!n&&!e.task?.trim())throw new Error("Capability discovery requires task or capability");let i=e.task?.trim()?em({task:e.task.trim(),operation:"associate capability"}):null;if(n){let d=Io(n,e.scope.workflow),f=await im(t,e.scope,d),p={workflow:e.scope.workflow,capability:d,currentSpec:f,historicalSources:[],matchedTerms:[d],confidence:"high",score:1,reason:"用户显式指定能力,已直接核对当前总 Spec 路径。",evidence:[{source:f.source,kind:`${e.scope.workflow}-spec`}]};return{workflow:e.scope.workflow,query:i,candidates:[p],associationDraft:nm(p,i,"explicit"),diagnostics:r,searched:!1,providerLimit:Ao}}if(!e.provider)throw new Error("Capability discovery requires a Project Knowledge provider for task search");let a;try{a=await e.provider.query({kind:"search",query:i,limit:Ao})}catch(d){return r.push({code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${d instanceof Error?d.message:String(d)}`}),am(e.scope,i,r,!0)}if(a.kind!=="search")return am(e.scope,i,a.diagnostics,!0);r.push(...a.diagnostics);let o=new Map;for(let[d,f]of a.results.entries())for(let p of PE(f)){let m=EE(e.scope,p.source);if(!m)continue;let h=RE(o,e.scope,m.capability),v=i.terms.filter(w=>tm(p.searchableText,w));for(let w of v)h.matchedTerms.add(w);h.bestScore=Math.max(h.bestScore,p.resultScore),h.bestRank=Math.min(h.bestRank,d),m.kind==="current"?h.currentHits+=1:(h.historicalHits+=1,h.historicalSources.add(m.source)),h.evidence.has(m.source)||h.evidence.set(m.source,{source:m.source,kind:m.kind==="current"?`${e.scope.workflow}-spec`:`${e.scope.workflow}-archive`,...p.title?{title:p.title}:{},...p.snippet?{snippet:p.snippet}:{}})}let s=Math.max(1,Math.min(rm,e.limit??rm)),c=[],l=[...o.values()].sort((d,f)=>f.currentHits-d.currentHits||f.matchedTerms.size-d.matchedTerms.size||f.bestScore-d.bestScore||d.bestRank-f.bestRank||d.capability.localeCompare(f.capability));for(let d of l.slice(0,s)){let f;try{f=await im(t,e.scope,d.capability)}catch(h){r.push({code:"capability-stale",message:`候选 ${d.capability} 没有可核对的当前总 Spec,已排除:${h instanceof Error?h.message:String(h)}`});continue}let p=_E(d,i),m={workflow:e.scope.workflow,capability:d.capability,currentSpec:f,historicalSources:[...d.historicalSources].sort(),matchedTerms:[...d.matchedTerms],confidence:p,score:IE(d,i),reason:AE(d,p),evidence:TE(d.evidence)};c.push(m)}c.sort((d,f)=>f.score-d.score||d.capability.localeCompare(f.capability));let u=c.length===1&&c[0].confidence==="high"?nm(c[0],i,"suggested"):null;return{workflow:e.scope.workflow,query:i,candidates:c,associationDraft:u,diagnostics:r,searched:!0,providerLimit:Ao}}function sm(e){return(0,Ql.stringify)({schema:e.schema,status:e.status,workflow:e.workflow,capability:e.capability,current_spec:e.current_spec,current_hash:e.current_hash,confidence:e.confidence,...e.query===void 0?{}:{query:e.query},reason:e.reason,historical_sources:[...e.historical_sources],evidence:e.evidence.map(t=>({source:t.source,kind:t.kind,...t.title===void 0?{}:{title:t.title},...t.snippet===void 0?{}:{snippet:t.snippet}}))})}Ae();Do();tt();pr();import{createHash as $m}from"node:crypto";import{promises as tn}from"node:fs";import G from"node:path";ze();import{createHash as ax}from"node:crypto";import{AsyncLocalStorage as ox}from"node:async_hooks";import Bo from"node:path";function Mo(...e){if(e.length===0)return Bo.resolve();if(Bo.win32.isAbsolute(e[0])){let t=Bo.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Bo.resolve(...e)}var sx=new ox;function cx(e,t){let r=Mo(e),n=t.runGit??re,i=sx.getStore(),a=i?.active?i.observations:void 0,o=a?.get(r)?.get(n);if(o)return o;let s=r;try{let l=n(r,["remote","get-url","origin"]).trim();if(l)s=l;else throw new Error("No origin")}catch{try{let l=n(r,["rev-parse","--git-common-dir"]).trim();l&&(s=Mo(r,l))}catch{}}let c={identity:ym(s),name:dx(s)};if(a){let l=a.get(r)??new Map;l.set(n,c),a.set(r,l)}return c}function lx(e,t={}){return cx(e,t).identity}function ux(e){let t=ym(e),n=(t.split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project",i=ax("sha256").update(t,"utf8").digest("hex").slice(0,8);return`${n.slice(0,40)}-${i}`}function wm(e,t={}){return ux(lx(e,t))}function dx(e){return(e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-zA-Z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project"}function ym(e){let t=e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").toLocaleLowerCase();return t||"project"}var bt=class extends Error{code;constructor(t,r,n){super(r,n),this.name="BoundedHttpRequestError",this.code=t}};async function fx(e,t){if(!e.body){let s=new Uint8Array(await e.arrayBuffer());if(s.byteLength>t)throw new bt("response-too-large","HTTP response exceeds byte limit");return s}let r=e.body.getReader(),n=[],i=0;try{for(;;){let s=await r.read();if(s.done)break;if(i+=s.value.byteLength,i>t)throw await r.cancel(),new bt("response-too-large","HTTP response exceeds byte limit");n.push(s.value)}}finally{r.releaseLock()}let a=new Uint8Array(i),o=0;for(let s of n)a.set(s,o),o+=s.byteLength;return a}async function bm(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=await(e.fetch??globalThis.fetch)(e.url,{...e.init,signal:t.signal}),i=n.ok?await fx(n,e.maxResponseBytes):new Uint8Array;return{response:n,bytes:i}}catch(n){throw n instanceof bt?n:t.signal.aborted?new bt("timeout","HTTP request timed out",{cause:n}):new bt("request-failed","HTTP request failed",{cause:n})}finally{clearTimeout(r)}}import Nm from"node:path";var px=/^[a-z0-9][a-z0-9._-]{1,127}$/u,xm=2e3,hx=1024,mx=32,vx=32,gx=32,wx=16,yx=16,Cm=32,bx=128,Nx=32,kx=new Set(["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"]),Sx=new Set(["trial","proven","enforced","superseded"]),Ex=new Set(["automatic","user","repository"]),xx=new Set(["contains","depends-on","consumes","registers","propagates-to","generated-by","validated-by","supersedes"]);function en(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ee(e,t,r=xm){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e.trim()}function fu(e,t){let r=Ee(e,t,128);if(!px.test(r))throw new Error(`${t} must use a stable record id`);return r}function Zr(e,t,r,n){if(e===void 0)return[];if(!Array.isArray(e)||e.length>r)throw new Error(`${t} must be a bounded list`);return e.map((i,a)=>n(i,a))}function Pm(e,t,r,n){if(!Array.isArray(e)||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty bounded list`);return e.map((i,a)=>n(i,a))}function hu(e,t){let r=Ee(e,t,hx).replaceAll("\\","/");if(Nm.posix.isAbsolute(r)||Nm.win32.isAbsolute(r)||r.includes("\0")||r.split("/").some(n=>n===".."))throw new Error(`${t} must be a project-relative path`);return r}function Cx(e,t,r=mx){return Zr(e,t,r,(n,i)=>hu(n,`${t}[${i}]`))}function km(e,t,r=vx){return Zr(e,t,r,(n,i)=>Ee(n,`${t}[${i}]`,512))}function pu(e,t,r=xm){if(e!==void 0)return Ee(e,t,r)}function Sm(e,t){if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error(`${t} must be a positive integer`);return Number(e)}function wi(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw new Error(`${t} must be a non-negative integer`);return Number(e)}function Rm(e,t){let r=en(e,t),n=r.lineStart,i=r.lineEnd,a=n===void 0?void 0:Sm(n,`${t}.lineStart`),o=i===void 0?void 0:Sm(i,`${t}.lineEnd`);if(a!==void 0&&o!==void 0&&o<a)throw new Error(`${t}.lineEnd must be greater than or equal to lineStart`);let s=pu(r.anchor,`${t}.anchor`,256),c=pu(r.evidence,`${t}.evidence`,1024);return{source:hu(r.source,`${t}.source`),...s===void 0?{}:{anchor:s},...a===void 0?{}:{lineStart:a},...o===void 0?{}:{lineEnd:o},...c===void 0?{}:{evidence:c}}}function Px(e,t){let r=en(e,`conclusions[${t}]`);return{text:Ee(r.text,`conclusions[${t}].text`),sources:Pm(r.sources,`conclusions[${t}].sources`,Cm,(n,i)=>Rm(n,`conclusions[${t}].sources[${i}]`))}}function Rx(e,t){let r=en(e,`relations[${t}]`),n=Ee(r.type,`relations[${t}].type`,64);if(!xx.has(n))throw new Error(`relations[${t}].type is unsupported`);return{type:n,targetId:fu(r.targetId,`relations[${t}].targetId`),sources:Pm(r.sources,`relations[${t}].sources`,Cm,(i,a)=>Rm(i,`relations[${t}].sources[${a}]`))}}function _x(e,t){let r=en(e,`verification[${t}]`),n=pu(r.expected,`verification[${t}].expected`);return{command:Ee(r.command,`verification[${t}].command`),...n===void 0?{}:{expected:n}}}function Ax(e,t){let r=en(e,`sourceVersions[${t}]`),n=r.digest;if(n!==void 0&&(typeof n!="string"||!/^[a-f0-9]{64}$/u.test(n)))throw new Error(`sourceVersions[${t}].digest must be a SHA-256 hash`);return{source:hu(r.source,`sourceVersions[${t}].source`),size:wi(r.size,`sourceVersions[${t}].size`),modifiedAt:wi(r.modifiedAt,`sourceVersions[${t}].modifiedAt`),...n===void 0?{}:{digest:n}}}function Ix(e,t){return e.reduce((r,n)=>r+n.sources.length,0)+t.reduce((r,n)=>r+n.sources.length,0)}function Em(e){let t=Ee(e,"updatedAt",64);if(Number.isNaN(Date.parse(t)))throw new Error("updatedAt must be an ISO-8601 timestamp");return t}function Tx(e){let t=en(e,"record"),r=Ee(t.type,"type",64);if(!kx.has(r))throw new Error("type is unsupported");let n=Ee(t.state,"state",32);if(!Sx.has(n))throw new Error("state is unsupported");let i=Ee(t.authority,"authority",32);if(!Ex.has(i))throw new Error("authority is unsupported");let a=Zr(t.conclusions,"conclusions",gx,Px),o=Zr(t.relations,"relations",wx,Rx);if(Ix(a,o)>bx)throw new Error("conclusions/relations sources exceed the bounded total reference count");let s=Zr(t.sourceVersions,"sourceVersions",Nx,Ax);if(new Set(s.map(c=>c.source)).size!==s.length)throw new Error("sourceVersions must not contain duplicate sources");return{id:fu(t.id,"id"),projectId:fu(t.projectId,"projectId"),type:r,state:n,authority:i,title:Ee(t.title,"title"),summary:Ee(t.summary,"summary"),applicablePaths:Cx(t.applicablePaths,"applicablePaths"),operations:km(t.operations,"operations"),phases:km(t.phases,"phases"),conclusions:a,relations:o,verification:Zr(t.verification,"verification",yx,_x),sourceVersions:s,applicationCount:wi(t.applicationCount,"applicationCount"),successCount:wi(t.successCount,"successCount"),failureCount:wi(t.failureCount,"failureCount"),...t.lastAppliedAt===void 0?{}:{lastAppliedAt:Em(t.lastAppliedAt)},updatedAt:Em(t.updatedAt)}}function Gt(e){return Tx(e)}var jx=1024*1024,$x=512,Tm=200,jm=1600,Ox=5e3,Hx=8,Dx=512*1024,Lx=32;function I(e,t,r=!1){if(typeof e!="string")return null;let n=[...e].map(i=>{let a=i.codePointAt(0)??0;return a<32||a===127?" ":i}).join("").trim().slice(0,t);return r&&!n?null:n}function vu(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))return null;let r=I(t.code,64,!0),n=I(t.message,240,!0);return r&&n?{code:r,message:n}:null}).filter(t=>t!==null).slice(0,Hx):[]}function yi(){return[]}function _m(e){let t={...e};return delete t.evidence,t}function Am(e){return{...e,conclusions:e.conclusions.map(t=>({...t,sources:t.sources.map(_m)})),relations:e.relations.map(t=>({...t,sources:t.sources.map(_m)}))}}function Bx(e){if(e.kind==="upsert")return{kind:"upsert",record:Am(e.record)};if(e.kind!=="experience-delta")return e;let t=e.delta,r=t.payload;r?.kind==="record"?r={kind:"record",record:Am(Gt(r.record))}:r?.kind==="verify"?r={kind:"verify",projectId:I(r.projectId,128)??"",commands:bi(r.commands,16,2e3),...typeof r.updatedAt=="string"?{updatedAt:r.updatedAt.slice(0,64)}:{}}:r!==void 0&&(r=void 0);let{payload:n,...i}=t,a={...i,statement:I(t.statement,4e3)??"",...t.title===void 0?{}:{title:I(t.title,512)??""},applicability:{...t.applicability.projectId===void 0?{}:{projectId:I(t.applicability.projectId,128)??""},...t.applicability.paths===void 0?{}:{paths:bi(t.applicability.paths,32,512)},...t.applicability.operations===void 0?{}:{operations:bi(t.applicability.operations,16,128)},...t.applicability.phases===void 0?{}:{phases:bi(t.applicability.phases,16,128)},...t.applicability.tasks===void 0?{}:{tasks:bi(t.applicability.tasks,16,512)}},evidence:t.evidence.slice(0,Lx).map(o=>({...o,summary:I(o.summary,1e3)??"",...o.source===void 0?{}:{source:I(o.source,512)??""},...o.anchor===void 0?{}:{anchor:I(o.anchor,256)??""},...o.command===void 0?{}:{command:I(o.command,2e3)??""}})),...r===void 0?{}:{payload:r}};return{...e,idempotencyKey:I(e.idempotencyKey,256,!0)??"invalid",delta:a}}function bi(e,t,r){return Array.isArray(e)?e.map(n=>I(n,r)).filter(n=>!!n).slice(0,t):[]}function Mx(e){if(e.kind==="search"){let t=e.query;return{kind:"search",task:I(t.task,2e3)??"",...t.path?{path:I(t.path,512)}:{},...t.phase?{phase:I(t.phase,128)}:{},...t.operation?{operation:I(t.operation,128)}:{},terms:t.terms.slice(0,28).map(r=>I(r,128)).filter(Boolean),limit:Math.max(1,Math.min(8,e.limit??8))}}return e.kind==="list"?{kind:"list",...e.projectId?{projectId:I(e.projectId,128)}:{},...e.type?{type:e.type}:{},...e.state?{state:e.state}:{},...e.authority?{authority:e.authority}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="manifest"?{kind:"manifest",...e.projectId?{projectId:I(e.projectId,128)}:{},...e.state?{state:e.state}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="expand"?{kind:"expand",id:I(e.id,128)??"",...e.projectId?{projectId:I(e.projectId,128)}:{}}:{kind:"get",id:I(e.id,128)??"",...e.projectId?{projectId:I(e.projectId,128)}:{}}}function mu(e,t,r){if(!Array.isArray(e))return[];let n=[];for(let i of e.slice(0,500))try{let a=Gt(i);if(a.projectId!==r)throw new Error("Project mismatch");n.push(a)}catch{t()}return n}function Fx(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return t(),null;let n=I(e.content,jm,!0),i=I(e.source,$x,!0);if(!n||!i)return t(),null;let a=e.title,o=a===void 0?void 0:I(a,Tm);if(a!==void 0&&o===null)return t(),null;let s=e.score;if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)))return t(),null;let c,l=e.record;if(l!==void 0)try{if(c=Gt(l),c.projectId!==r)throw new Error("Project mismatch")}catch{return t(),null}return{content:n,source:i,...o?{title:o}:{},...s===void 0?{}:{score:s},...c?{record:c}:{}}}function Vx(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)&&"status"in e?e.status:e;if(!r||typeof r!="object"||Array.isArray(r))return t(),null;let n=r.provider,i=r.healthy,a=r.writable;if(n!=="remote"||typeof i!="boolean"||typeof a!="boolean")return t(),null;let o=r.recordCount,s=r.updatedAt;return{provider:"remote",healthy:i,writable:a,...Number.isSafeInteger(o)&&Number(o)>=0?{recordCount:Number(o)}:{},...typeof s=="string"?{updatedAt:s.slice(0,64)}:{},diagnostics:vu(r.diagnostics)}}function qx(e,t,r,n){let i=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!i||typeof i!="object"||Array.isArray(i))return r(),null;let a=i.kind??t.kind,o=vu(i.diagnostics);if(a==="list")return{kind:"list",records:mu(i.records,r,n),truncated:i.truncated===!0,diagnostics:o};if(a==="get"){let f=i.record,p=null;if(f!=null)try{if(p=Gt(f),p.projectId!==n)throw new Error("Project mismatch")}catch{r()}return{kind:"get",record:p,diagnostics:o}}if(a==="expand"){let f=i.record,p=null;if(f!=null)try{if(p=Gt(f),p.projectId!==n)throw new Error("Project mismatch")}catch{r()}return{kind:"expand",record:p,diagnostics:o}}if(a==="manifest")return{kind:"manifest",items:Array.isArray(i.items)?i.items.slice(0,500).flatMap(p=>{if(!p||typeof p!="object"||Array.isArray(p))return r(),[];let m=p,h=I(m.id,128,!0),v=I(m.title,Tm,!0),w=I(m.summary,jm,!0),y=m.type,k=m.memoryType,E=m.state,x=m.authority;if(!h||!v||!w||!["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"].includes(String(y))||k!=="project-model"&&k!=="project-policy"||!["trial","proven","enforced","superseded"].includes(String(E))||!["automatic","user","repository"].includes(String(x)))return r(),[];let g=b=>Array.isArray(b)?b.map(T=>I(T,1024)).filter(T=>T!==null):[],_=Array.isArray(m.verification)?m.verification.slice(0,16).flatMap(b=>{if(!b||typeof b!="object"||Array.isArray(b))return r(),[];let T=I(b.command,4e3,!0),ie=I(b.expected,2e3);return T?[{command:T,...ie===null?{}:{expected:ie}}]:[]}):[];return[{id:h,memoryType:k,type:y,state:E,authority:x,title:v,summary:w,applicablePaths:g(m.applicablePaths),operations:g(m.operations),phases:g(m.phases),sourceTypes:g(m.sourceTypes),verification:_}]}):[],truncated:i.truncated===!0,diagnostics:o};let s=[],c=0,l=new Set;for(let f of Array.isArray(i.results)?(i.results??[]).slice(0,16):[]){let p=Fx(f,r,n);if(!(!p||l.has(`${p.source}\0${p.title??""}`))){if(c+p.content.length>Ox)break;l.add(`${p.source}\0${p.title??""}`),c+=p.content.length,s.push(p)}}let u=mu(i.records,r,n);return{kind:"search",hits:Array.isArray(i.hits)?(i.hits??[]).slice(0,40).flatMap(f=>{if(!f||typeof f!="object"||Array.isArray(f))return r(),[];try{let p=Gt(f.record);if(p.projectId!==n)throw new Error("Project mismatch");let m=f.score;return m!==void 0&&(typeof m!="number"||!Number.isFinite(m))?(r(),[]):[{record:p,...m===void 0?{}:{score:m}}]}catch{return r(),[]}}):u.map(f=>({record:f})),results:s,records:u,truncated:i.truncated===!0,diagnostics:o}}function Wx(e,t,r,n){let i=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!i||typeof i!="object"||Array.isArray(i))return r(),null;let a=i.record,o;if(a===null)o=null;else if(a!==void 0)try{if(o=Gt(a),o.projectId!==n)throw new Error("Project mismatch")}catch{r()}return{kind:t.kind,changed:i.changed===!0,...o===void 0?{}:{record:o},...Array.isArray(i.records)?{records:mu(i.records,r,n)}:{},diagnostics:vu(i.diagnostics)}}var Fo=class{options;projectId;constructor(t){this.options=t,this.projectId=t.projectId??(t.projectRoot?wm(t.projectRoot):"project")}async status(){let t=this.options.config.token_env;if(t&&!this.token()){let a={code:"remote-token",message:`Remote Project Knowledge 未配置环境变量 ${t}。`};return this.report(a.code,a.message),{provider:"remote",healthy:!1,writable:!1,diagnostics:[a]}}let r=await this.request("status",{});if(r===null)return{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let n={value:!1},i=Vx(r,()=>{n.value=!0});return!i||n.value?(this.report("remote-schema","Remote Project Knowledge status 响应格式无效。"),{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge status 响应格式无效。"}]}):i}async query(t){let r=t.kind==="search"?this.projectId:t.projectId??this.projectId,n=await this.request("query",Mx(t),t.kind==="search"?void 0:t.projectId);if(n===null)return Im(t);let i={value:!1},a=qx(n,t,()=>{i.value=!0},r);return!a||i.value?(this.report("remote-schema","Remote Project Knowledge query 响应包含无效数据。"),Im(t)):a}async apply(t){let r=(t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId)??this.projectId,n=await this.request("apply",Bx(t),t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId);if(n===null)return{kind:t.kind,changed:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let i={value:!1},a=Wx(n,t,()=>{i.value=!0},r);return!a||i.value?(this.report("remote-schema","Remote Project Knowledge apply 响应格式无效。"),{kind:t.kind,changed:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge apply 响应格式无效。"}]}):a}async request(t,r,n=this.projectId){let i=this.options.config.token_env,a=this.token();if(i&&!a)return this.report("remote-token",`Remote Project Knowledge 未配置环境变量 ${i}。`),null;let o={schema:"comet.project-knowledge.provider.v1",operation:t,...this.options.config.scope?{scope:this.options.config.scope}:{},projectId:I(n,128,!0)??this.projectId,input:r},s=JSON.stringify(o);if(new TextEncoder().encode(s).byteLength>Dx)return this.report("remote-request-size","Remote Project Knowledge 请求超过大小限制。"),null;try{let{response:c,bytes:l}=await bm({url:this.options.config.endpoint,timeoutMs:this.options.config.timeout_ms,maxResponseBytes:jx,fetch:this.options.fetch,init:{method:"POST",redirect:"error",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:s}});if(!c.ok)return this.report("remote-status",`Remote Project Knowledge 返回 HTTP ${c.status}。`),null;try{let u=JSON.parse(new TextDecoder().decode(l));return zx(u,t,o.projectId)?u.result:(this.report("remote-schema","Remote Project Knowledge 响应 envelope 无效。"),null)}catch{return this.report("remote-json","Remote Project Knowledge 返回了无效 JSON。"),null}}catch(c){return this.report("remote-failed",c instanceof bt&&c.code==="timeout"?"Remote Project Knowledge 请求超时。":"Remote Project Knowledge 请求失败。"),null}}report(t,r){this.options.reportDiagnostic?.({code:t,message:r})}token(){let t=this.options.config.token_env;return t?this.options.env?.[t]??process.env[t]:void 0}};function zx(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.schema==="comet.project-knowledge.provider.v1"&&n.operation===t&&n.projectId===r&&Object.prototype.hasOwnProperty.call(n,"result")}function Im(e){return e.kind==="list"?{kind:"list",records:[],truncated:!1,diagnostics:yi()}:e.kind==="get"?{kind:"get",record:null,diagnostics:yi()}:e.kind==="expand"?{kind:"expand",record:null,diagnostics:yi()}:e.kind==="manifest"?{kind:"manifest",items:[],truncated:!1,diagnostics:yi()}:{kind:"search",hits:[],results:[],records:[],truncated:!1,diagnostics:yi()}}var Om=512,gu=256*1024,Dm=8*1024*1024,Gx=2e3,Lm=G.join(".comet","runtime","native","capability-discovery-cache.json"),Ni="comet.native.capability-cache.v1",Bm=512*1024,Mm=32;function wu(e,t){let r=G.relative(G.resolve(e),G.resolve(t));return r===""||!G.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${G.sep}`)}function Kx(e,t){return G.relative(e,t).replaceAll(G.sep,"/")}function Jx(e,t,r){e?.({code:t,message:r})}async function Ux(e,t){if(!wu(t,e))return!1;try{let r=await tn.lstat(e);return!r.isDirectory()||r.isSymbolicLink()?!1:wu(await tn.realpath(t),await tn.realpath(e))}catch{return!1}}async function bu(e){let t=G.resolve(e.projectRoot),r=Date.now()+Gx,n=[],i=!0,a=0,o=async(c,l)=>{if(Date.now()>r){i=!1;return}if(!await Ux(c,t))return;let u=async d=>{if(Date.now()>r||n.length>=Om){i=!1;return}let f;try{f=await tn.readdir(d,{withFileTypes:!0})}catch{i=!1;return}for(let p of f.sort((m,h)=>m.name.localeCompare(h.name,"en"))){if(Date.now()>r){i=!1;return}if(p.isSymbolicLink())continue;let m=G.join(d,p.name);if(p.isDirectory()){await u(m);continue}if(!p.isFile()||!p.name.toLowerCase().endsWith(".md")||!wu(t,m))continue;let h=await tn.stat(m);if(h.size>gu)continue;if(a+h.size>Dm){i=!1;return}if(Date.now()>r){i=!1;return}let v=Kx(t,m),w;try{w=await Z(t,v,gu,{label:`${l} capability Spec`})}catch{i=!1;continue}if(a+=w.bytes.length,n.push({absolutePath:m,source:v,kind:l,size:h.size,mtimeMs:h.mtimeMs,contentHash:$m("sha256").update(w.bytes).digest("hex")}),n.length>=Om){i=!1;return}}};await u(c)};await o(G.resolve(t,...e.scope.currentSpecRoot.split("/")),"native-spec"),await o(G.resolve(t,...e.scope.archiveRoot.split("/")),"native-archive"),n.sort((c,l)=>c.source.localeCompare(l.source,"en"));let s=$m("sha256").update(JSON.stringify(n.map(({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})=>({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})))).digest("hex");return i||Jx(e.reportDiagnostic,"capability-corpus-limit","能力候选语料发现达到时间或文件数量上限,当前结果可能不完整。"),{sources:n,fingerprint:s,complete:i}}function Hm(e){return/^(?:#)\s+(.+)$/mu.exec(e)?.[1]?.trim()}function Yx(e,t,r){let n=`${t}
|
|
216
|
+
${e}`.toLocaleLowerCase();return r.reduce((i,a)=>i+(n.includes(a.toLocaleLowerCase())?1:0),0)}var yu=class{constructor(t,r,n){this.projectRoot=t;this.manifest=r;this.reportDiagnostic=n}projectRoot;manifest;reportDiagnostic;async status(){return{provider:"local",healthy:!0,writable:!1,diagnostics:[]}}async query(t){if(t.kind!=="search")throw new Error("Native capability discovery only supports search queries");let r=[],n=[],i=0;for(let a of this.manifest.sources){if(i+a.size>Dm){r.push({code:"capability-corpus-bytes",message:"能力候选语料达到总字节预算,剩余来源不会参与本次召回。"});break}try{let o=await Z(this.projectRoot,a.source,gu,{label:`${a.kind} capability Spec`});i+=o.bytes.length;let s=o.bytes.toString("utf8"),c=Yx(s,a.source,t.query.terms);if(c===0)continue;let l={absolutePath:a.absolutePath,source:a.source,kind:a.kind};n.push({content:s,source:a.source,...Hm(s)?{title:Hm(s)}:{},score:c,document:l})}catch(o){let s={code:"capability-corpus-read",message:`能力候选来源无法读取,已跳过 ${a.source}:${o instanceof Error?o.message:String(o)}`};r.push(s),this.reportDiagnostic?.(s)}}return n.sort((a,o)=>o.score-a.score||a.source.localeCompare(o.source)),{kind:"search",hits:[],results:n,records:[],truncated:!this.manifest.complete,diagnostics:r}}async apply(t){throw new Error("Native capability discovery is read-only")}};async function Fm(e){let r=(await fr(e.projectRoot))?.knowledge;if(r?.provider==="remote"){if(!r.remote)throw new Error("Configured remote Project Knowledge provider is missing remote settings");return new Fo({config:r.remote,projectRoot:e.projectRoot,...e.reportDiagnostic?{reportDiagnostic:e.reportDiagnostic}:{}})}let n=await bu(e);return new yu(G.resolve(e.projectRoot),n,e.reportDiagnostic)}function Vm(e){return JSON.stringify({workflow:e.scope.workflow,currentSpecRoot:e.scope.currentSpecRoot,archiveRoot:e.scope.archiveRoot,task:e.task.trim()})}function Xx(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.workflow==="native"&&(t.query===null||typeof t.query=="object"&&t.query!==null)&&Array.isArray(t.candidates)&&t.candidates.length<=5&&(t.associationDraft===null||typeof t.associationDraft=="object"&&t.associationDraft!==null)&&Array.isArray(t.diagnostics)&&typeof t.searched=="boolean"&&t.providerLimit===40}function Qx(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema!==Ni||!Array.isArray(t.entries)||t.entries.length>Mm)return null;let r=[];for(let n of t.entries){if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n;if(typeof i.key!="string"||typeof i.fingerprint!="string"||!Xx(i.result))return null;r.push({key:i.key,fingerprint:i.fingerprint,result:i.result})}return{schema:Ni,entries:r}}async function qm(e){try{let t=await tn.readFile(G.join(e,Lm),"utf8");return Buffer.byteLength(t,"utf8")>Bm?null:Qx(JSON.parse(t))}catch{return null}}async function Wm(e){let t=G.resolve(e.projectRoot);if((await fr(t))?.knowledge?.provider==="remote")return null;let n=await bu({projectRoot:t,scope:e.scope});return n.complete?(await qm(t))?.entries.find(o=>o.key===Vm(e)&&o.fingerprint===n.fingerprint)?.result??null:null}async function zm(e){let t=G.resolve(e.projectRoot);if((await fr(t))?.knowledge?.provider==="remote")return;let n=await bu({projectRoot:t,scope:e.scope});if(!n.complete)return;let i=await qm(t)??{schema:Ni,entries:[]},a=Vm(e),o=[{key:a,fingerprint:n.fingerprint,result:e.result},...i.entries.filter(l=>!(l.key===a&&l.fingerprint===n.fingerprint))].slice(0,Mm),s=JSON.stringify({schema:Ni,entries:o});if(Buffer.byteLength(s,"utf8")>Bm)return;let{atomicWriteJson:c}=await Promise.resolve().then(()=>(B(),Jh));await c(G.join(t,Lm),{schema:Ni,entries:o},{containedRoot:G.join(t,".comet","runtime","native")})}L();Si();mr();function U(e,t,r){return e.language==="zh-CN"?r:t}function nC(e,t,r,n){let i=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:U(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:U(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:U(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return i(U(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(U(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"){let a=n==="confirmed"?U(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):U(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return i(`${a} ${U(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:U(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:U(e,"Accept the result","接受结果"),agentInstruction:U(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=Wo)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i(U(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i(U(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function iC(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function aC(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:n,name:i,description:a})=>({name:i,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",n,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:U(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:U(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Ym(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function vr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Km(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function oC(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Jm(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function sC(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function cC(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function nt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Ym({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[vr("summary","--summary"),oC(e.name,e.flag)]}}function Um(e,t){return t.some(n=>/^verification\.md is (?:missing|stale|invalid)$/u.test(n))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:U(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function lC(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function zo(e){return[nt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),nt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function uC(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(n=>{let i=n.response?.kind??n.kind;return{...r,name:i,required:!1,exclusiveGroup:"runner-input",description:t[i],template:n}}):[r])}function Xm(e,t,r={}){let n=sC(t)&&e.coordination_mode===void 0,i=nC(e,n,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:i.required,userCommunication:i},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...n?["coordination-choice"]:[]],inputOptions:[vr("summary","--summary")],commandAlternatives:n?Gm.map(s=>{let c=nt({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,Jm("coordination-mode","--coordination-mode",[s])]}}):[nt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=nt({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],nt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...zo({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[nt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),nt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[nt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...zo({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:zo({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:zo({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Ym({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:cC({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,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:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"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:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[Km()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Wo)??null,f=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:U(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&f===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:f!==null?[f]:[vr("summary","--summary")],runnerAction:o("none")}}return{...a,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:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=Km();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${U(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:uC([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Um(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>lC(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:Um(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Jm("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...aC(e)],userCommunication:iC(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[nt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{promises as XC}from"node:fs";import $u from"node:path";Qr();Ko();import{execFileSync as yC}from"child_process";import bC from"fs";import gr from"path";import{AsyncLocalStorage as tv}from"node:async_hooks";Pi();var wr=new tv,rv=new tv;function nv(e){return wr.getStore()?e():wr.run(new Map,e)}function NC(e){let t=wr.getStore();for(let r of e)t?.set(Jt(r.root),e);return e}function Ut(e,t){return gi(()=>yC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function it(e,t){return Jt(e)===Jt(t)}function Jt(e){let t=gr.resolve(e);try{let r=bC.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ge(e){try{let t=rv.getStore()?.get(Jt(e)),r=wr.getStore()?.get(t??Jt(e));if(r){let c=ev(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let n=gr.resolve(Ut(e,["rev-parse","--show-toplevel"])),i=wr.getStore()?.get(Jt(n))??iv(e),a=ev(n,i);if(wr.getStore()&&a)return a;let o=i[0]?.root??n,s=null;try{s=Ut(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!it(n,o),currentWorktreeRoot:n,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Jo(e){try{let t=wr.getStore()?.get(rv.getStore()?.get(Jt(e))??Jt(e));return t?t.map(r=>({...r})):(Ut(e,["rev-parse","--is-inside-work-tree"]),iv(e))}catch{return[]}}function iv(e){let t=kC(Ut(e,["worktree","list","--porcelain","-z"]));return NC(t),t.map(r=>({...r}))}function kC(e){let t=e.split("\0"),r=[],n=null;for(let i of t)i.startsWith("worktree ")?(n&&r.push(n),n={root:gr.resolve(i.slice(9)),branch:null,detached:!1}):n&&i.startsWith("branch refs/heads/")?n.branch=i.slice(18):n&&i==="detached"&&(n.detached=!0);return n&&r.push(n),r}function yr(e){return Jo(e).map(t=>t.root)}function ev(e,t){let r=t.find(a=>it(gr.resolve(a.root),gr.resolve(e)));if(!r)return null;let n=gr.resolve(t[0].root),i=gr.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!it(n,i),currentWorktreeRoot:i,primaryWorktreeRoot:n,currentBranch:r.branch}}function av(e){try{return Ut(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function nn(e,t){try{return Ut(e,["check-ref-format","--branch",t]),Ut(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function br(e,t){try{let r=Ut(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ze();B();Si();import{promises as SC}from"node:fs";import EC from"node:os";import Ii from"node:path";function _i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ai(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function de(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function an(e,t){return e===null?null:de(e,t)}function on(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function xC(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 CC(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function sn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Cu(e,t){if(e===null)return null;let r=de(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function PC(e,t){let r=de(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Pu(e,t){let r=de(e,t);if(!Ii.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ii.resolve(r)}function RC(e,t){let r=`Native local checks[${t}]`,n=_i(e,r);if(Ai(n,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(n.argv)||n.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let i=n.argv.map((u,d)=>de(u,`${r}.argv[${d}]`,!0)),a=sn(n.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Cu(n.startedAt,`${r}.startedAt`),s=Cu(n.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=on(n.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(n,"activeProcess"))if(n.activeProcess===null)l=null;else{let u=_i(n.activeProcess,`${r}.activeProcess`),d=sn(u.status,["starting","running"],`${r}.activeProcess.status`);if(Ai(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:on(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:de(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:de(n.id,`${r}.id`),name:de(n.name,`${r}.name`),operationId:de(n.operationId,`${r}.operationId`),status:a,repeatable:CC(n.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:on(n.executionCount,`${r}.executionCount`),argv:i,cwd:Pu(n.cwd,`${r}.cwd`),exitCode:xC(n.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:de(n.log,`${r}.log`),...Object.hasOwn(n,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(n,"evidence")?{evidence:sn(n.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(n,"evidenceDigest")?{evidenceDigest:de(n.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function ov(e){let t="Native local execution state",r=_i(e,t);if(Ai(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==ki)throw new Error(`Native local execution schema must be ${ki}`);let n=_i(r.workspace,"Native local workspace");Ai(n,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let i=null;if(r.execution!==null){let o=_i(r.execution,"Native local execution");Ai(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Cu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");i={operationId:de(o.operationId,"Native local execution.operationId"),stage:sn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:sn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:an(o.executionId,"Native local execution.executionId"),status:sn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:on(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:PC(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:on(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:de(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(RC);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(i&&a.some(o=>o.operationId!==i.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:ki,change:de(r.change,"Native local change"),basedOnStateVersion:on(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:an(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:an(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:an(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:an(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Pu(n.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Pu(n.worktreeRoot,"Native local workspace.worktreeRoot"),branch:an(n.branch,"Native local workspace.branch"),...Object.hasOwn(n,"machineId")?{machineId:de(n.machineId,"Native local workspace.machineId")}:{}},execution:i,checks:a}}function Nr(e){return ov({schema:ki,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:Ii.resolve(e.projectRoot),worktreeRoot:Ii.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:EC.hostname()},execution:null,checks:[]})}async function kr(e,t,r={}){let n=ov(t);await SC.mkdir(Ii.dirname(e),{recursive:!0}),await ae(e,n,r)}Yt();L();var Ou=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dv="comet-state.yaml",fv="state.json";function ot(e,t){if(!Ou.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=$u.join(e.changesDir,t);if(!te(e.changesDir,r))throw new Error("Native change path escaped");return r}function Ti(e,t){return $u.join(ot(e,t),dv)}function Xt(e,t){return $u.join(Ve(e,t),fv)}async function Hu(e,t){try{let r=await XC.readFile(Ti(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function pv(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Er(e){return av(e)}function hv(e,t){if(!t)return;let r=ge(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Nt(e,t){return ju(Ti(e,t))}import{promises as Ir}from"node:fs";import cw from"node:path";function Mu(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Pr=Mu();function kv(e){Pr=e}var xr={exec:()=>null};function fn(e){let t=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=t[n];return i||(i=e(n),t[n]=i),i}}function R(e,t=""){let r=typeof e=="string"?e:e.source,n={replace:(i,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(se.caret,"$1"),r=r.replace(i,o),n},getRegex:()=>new RegExp(r,t)};return n}var QC=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),se={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:fn(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:fn(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:fn(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:fn(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:fn(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:fn(e=>new RegExp(`^ {0,${e}}>`))},ZC=/^(?:[ \t]*(?:\n|$))+/,eP=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,tP=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Oi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,rP=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Fu=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Sv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ev=R(Sv).replace(/bull/g,Fu).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),nP=R(Sv).replace(/bull/g,Fu).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Vu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,iP=/^[^\n]+/,qu=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,aP=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",qu).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),oP=R(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Fu).getRegex(),ns="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Wu=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,sP=R("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Wu).replace("tag",ns).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xv=e=>R(Vu).replace("hr",Oi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ns).getRegex(),cP=xv(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),lP=xv(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),uP=R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",lP).getRegex(),zu={blockquote:uP,code:eP,def:aP,fences:tP,heading:rP,hr:Oi,html:sP,lheading:Ev,list:oP,newline:ZC,paragraph:cP,table:xr,text:iP},mv=R("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Oi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ns).getRegex(),dP={...zu,lheading:nP,table:mv,paragraph:R(Vu).replace("hr",Oi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",mv).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ns).getRegex()},fP={...zu,html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Wu).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:xr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:R(Vu).replace("hr",Oi).replace("heading",` *#{1,6} *[^
|
|
217
|
+
]`).replace("lheading",Ev).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},pP=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,hP=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Cv=/^( {2,}|\\)\n(?!\s*$)/,mP=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,kt=/[\p{P}\p{S}]/u,pn=/[\s\p{P}\p{S}]/u,Hi=/[^\s\p{P}\p{S}]/u,vP=R(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,pn).getRegex(),gP=/[\p{Pi}\p{Ps}"']/u,Pv=/(?!~)[\p{P}\p{S}]/u,wP=/(?!~)[\s\p{P}\p{S}]/u,yP=/(?:[^\s\p{P}\p{S}]|~)/u,bP=R(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",QC?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Rv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,NP=R(Rv,"u").replace(/punct/g,kt).getRegex(),kP=R(Rv,"u").replace(/punct/g,Pv).getRegex(),SP=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,EP=R(SP,"u").replace(/openQuote/g,gP).replace(/punct/g,kt).getRegex(),_v="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",xP=R(_v,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),CP=R(_v,"gu").replace(/notPunctSpace/g,yP).replace(/punctSpace/g,wP).replace(/punct/g,Pv).getRegex(),PP="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",RP=R(PP,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),_P=R("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),AP="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",IP=R(AP,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),TP=R(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,kt).getRegex(),jP="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",$P=R(jP,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),OP=R(/\\(punct)/,"gu").replace(/punct/g,kt).getRegex(),HP=R(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),DP=R(Wu).replace("(?:-->|$)","-->").getRegex(),LP=R("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",DP).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),es=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,BP=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",es).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Av=R(/^!?\[(label)\]\[(ref)\]/).replace("label",es).replace("ref",qu).getRegex(),Iv=R(/^!?\[(ref)\](?:\[\])?/).replace("ref",qu).getRegex(),MP=R("reflink|nolink(?!\\()","g").replace("reflink",Av).replace("nolink",Iv).getRegex(),vv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Gu={_backpedal:xr,anyPunctuation:OP,autolink:HP,blockSkip:bP,br:Cv,code:hP,del:xr,delLDelim:xr,delRDelim:xr,emStrongLDelim:NP,emStrongRDelimAst:xP,emStrongRDelimUnd:_P,escape:pP,link:BP,nolink:Iv,punctuation:vP,reflink:Av,reflinkSearch:MP,tag:LP,text:mP,url:xr},FP={...Gu,emStrongLDelim:EP,emStrongRDelimAst:RP,emStrongRDelimUnd:IP,link:R(/^!?\[(label)\]\((.*?)\)/).replace("label",es).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",es).getRegex()},Du={...Gu,emStrongRDelimAst:CP,emStrongLDelim:kP,delLDelim:TP,delRDelim:$P,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",vv).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:R(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",vv).getRegex()},VP={...Du,br:R(Cv).replace("{2,}","*").getRegex(),text:R(Du.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Zo={normal:zu,gfm:dP,pedantic:fP},ji={normal:Gu,gfm:Du,breaks:VP,pedantic:FP},qP={"&":"&","<":"<",">":">",'"':""","'":"'"},gv=e=>qP[e];function st(e,t){if(t){if(se.escapeTest.test(e))return e.replace(se.escapeReplace,gv)}else if(se.escapeTestNoEncode.test(e))return e.replace(se.escapeReplaceNoEncode,gv);return e}function wv(e){try{e=encodeURI(e).replace(se.percentDecode,"%")}catch{return null}return e}function yv(e,t){let r=e.replace(se.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),n=r.split(se.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(se.slashPipe,"|");return n}function Qt(e,t,r){let n=e.length;if(n===0)return"";let i=0;for(;i<n;){let a=e.charAt(n-i-1);if(a===t&&!r)i++;else if(a!==t&&r)i++;else break}return e.slice(0,n-i)}function bv(e){let t=e.split(`
|
|
218
|
+
`),r=t.length-1;for(;r>=0&&se.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
219
|
+
`)}function WP(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===t[0])r++;else if(e[n]===t[1]&&(r--,r<0))return n;return r>0?-2:-1}function zP(e,t=0){let r=t,n="";for(let i of e)if(i===" "){let a=4-r%4;n+=" ".repeat(a),r+=a}else n+=i,r++;return n}function Nv(e,t,r,n,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";n.state.inLink=!0;let l=n.state.linkEmitted,u=n.state.inRawBlock;n.state.linkEmitted=!1;let d=n.inlineTokens(s),f=n.state.linkEmitted;if(n.state.linkEmitted=l,n.state.inLink=!1,!c){if(f){n.state.inRawBlock=u;return}n.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function GP(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let i=n[1];return t.split(`
|
|
220
|
+
`).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=i.length?a.slice(i.length):a}).join(`
|
|
221
|
+
`)}var ts=class{options;rules;lexer;constructor(e){this.options=e||Pr}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:bv(t[0]),n=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],n=GP(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let n=Qt(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:Qt(t[0],`
|
|
222
|
+
`),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Qt(t[0],`
|
|
223
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Qt(t[0],`
|
|
224
|
+
`).split(`
|
|
225
|
+
`),n="",i="",a=[];for(;r.length>0;){let o=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),o=!0;else if(!o)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
|
|
226
|
+
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
227
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
|
|
228
|
+
${l}`:l,i=i?`${i}
|
|
229
|
+
${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=d,r.length===0)break;let f=a.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let p=f,m=r.join(`
|
|
230
|
+
`),h=p.raw+`
|
|
231
|
+
`+m.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(h);a[a.length-1]=v,n=`${n}
|
|
232
|
+
${m}`,i=i.substring(0,i.length-p.text.length)+v.text;break}else if(f?.type==="list"){let p=f,m=p.raw+`
|
|
233
|
+
`+r.join(`
|
|
234
|
+
`),h=this.list(m);a[a.length-1]=h,n=n.substring(0,n.length-f.raw.length)+h.raw,i=i.substring(0,i.length-p.raw.length)+h.raw,r=m.substring(a.at(-1).raw.length).split(`
|
|
235
|
+
`);continue}}return{type:"blockquote",raw:n,tokens:a,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),n=r.length>1,i={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;e;){let c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let d=zP(t[2].split(`
|
|
236
|
+
`,1)[0],t[1].length),f=e.split(`
|
|
237
|
+
`,1)[0],p=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):p?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=t[1].length),p&&this.rules.other.blankLine.test(f)&&(l+=f+`
|
|
238
|
+
`,e=e.substring(f.length+1),c=!0),!c){let h=this.rules.other.nextBulletRegex(m),v=this.rules.other.hrRegex(m),w=this.rules.other.fencesBeginRegex(m),y=this.rules.other.headingBeginRegex(m),k=this.rules.other.htmlBeginRegex(m),E=this.rules.other.blockquoteBeginRegex(m);for(;e;){let x=e.split(`
|
|
239
|
+
`,1)[0],g;if(f=x,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),g=f):g=f.replace(this.rules.other.tabCharGlobal," "),w.test(f)||y.test(f)||k.test(f)||E.test(f)||h.test(f)||v.test(f))break;if(g.search(this.rules.other.nonSpaceChar)>=m||!f.trim())u+=`
|
|
240
|
+
`+g.slice(m);else{if(p||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||y.test(d)||v.test(d))break;u+=`
|
|
241
|
+
`+f}p=!f.trim(),l+=x+`
|
|
242
|
+
`,e=e.substring(x.length+1),d=g.slice(m)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),i.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),i.raw+=l}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c of i.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!i.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=u}for(let c of i.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,i.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(i.loose)for(let c of i.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=bv(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:Qt(t[0],`
|
|
243
|
+
`),href:n,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=yv(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
244
|
+
`):[],a={type:"table",raw:Qt(t[0],`
|
|
245
|
+
`),header:[],align:[],rows:[]};if(r.length===n.length){for(let o of n)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of i)a.rows.push(yv(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:Qt(t[0],`
|
|
246
|
+
`),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
|
|
247
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=Qt(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=WP(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(n);a&&(n=a[1],i=a[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?n=n.slice(1):n=n.slice(1,-1)),Nv(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[n.toLowerCase()];if(!i){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return Nv(r,i,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!(!n||!n[1]&&!n[2]&&!n[3]&&!n[4]||n[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[3])||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,a,o,s=i,c=0,l=n[0][0],u=r===l,d=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(n=d.exec(t))!==null;){if(a=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!a)continue;if(o=[...a].length,n[3]||n[4]){s+=o;continue}else if(n[5]||n[6]){if(i%3&&!((i+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let f=[...n[0]][0].length,p=e.slice(0,i+n.index+f+o);if(Math.min(i,o)%2){let h=p.slice(1,-1);return{type:"em",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}let m=p.slice(2,-2);return{type:"strong",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(r),i=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return n&&i&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let n=this.rules.inline.delLDelim.exec(e);if(n&&(!n[1]||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,a,o,s=i,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+i);(n=c.exec(t))!==null;){if(a=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!a||(o=[...a].length,o!==i))continue;if(n[3]||n[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let l=[...n[0]][0].length,u=e.slice(0,i+n.index+l+o),d=u.slice(i,-i);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,n;return t[2]==="@"?(r=t[1],n="mailto:"+r):(r=t[1],n=r),{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},Te=class Lu{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Pr,this.options.tokenizer=this.options.tokenizer||new ts,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:se,block:Zo.normal,inline:ji.normal};this.options.pedantic?(r.block=Zo.pedantic,r.inline=ji.pedantic):this.options.gfm&&(r.block=Zo.gfm,this.options.breaks?r.inline=ji.breaks:r.inline=ji.gfm),this.tokenizer.rules=r}static get rules(){return{block:Zo,inline:ji}}static lex(t,r){return new Lu(r).lex(t)}static lexInline(t,r){return new Lu(r).inlineTokens(t)}lex(t){t=t.replace(se.carriageReturn,`
|
|
248
|
+
`),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(se.tabCharGlobal," ").replace(se.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},t,r))?(t=t.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
|
|
249
|
+
`:r.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
250
|
+
`)?"":`
|
|
251
|
+
`)+a.raw,s.text+=`
|
|
252
|
+
`+a.text,this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
253
|
+
`)?"":`
|
|
254
|
+
`)+a.raw,s.text+=`
|
|
255
|
+
`+a.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},r.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),r.push(a);continue}let o=t;if(this.options.extensions?.startBlock){let s=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(o=t.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
|
|
256
|
+
`)?"":`
|
|
257
|
+
`)+a.raw,s.text+=`
|
|
258
|
+
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),n=o.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
259
|
+
`)?"":`
|
|
260
|
+
`)+a.raw,s.text+=`
|
|
261
|
+
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let n of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(n[0])&&t.charAt(n.index-1)!=="!")return!0;for(let n of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=n[0],a=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(a+1,-1)))&&!(a>1&&this.linkInText(i.slice(1,a-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let n=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};n=n.replace(s,c)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,a="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(a=""),i=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,n,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,n,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(f=>{d=f.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),i=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},rs=class{options;parser;constructor(e){this.options=e||Pr}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(se.notSpaceStart)?.[0],i=e.replace(se.endingNewline,"")+`
|
|
262
|
+
`;return n?'<pre><code class="language-'+st(n)+'">'+(r?i:st(i,!0))+`</code></pre>
|
|
263
|
+
`:"<pre><code>"+(r?i:st(i,!0))+`</code></pre>
|
|
264
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
265
|
+
${this.parser.parse(e)}</blockquote>
|
|
266
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
267
|
+
`}hr(e){return`<hr>
|
|
268
|
+
`}list(e){let t=e.ordered,r=e.start,n="";for(let o=0;o<e.items.length;o++){let s=e.items[o];n+=this.listitem(s)}let i=t?"ol":"ul",a=t&&r!==1?' start="'+r+'"':"";return"<"+i+a+`>
|
|
269
|
+
`+n+"</"+i+`>
|
|
270
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
271
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
272
|
+
`}table(e){let t="",r="";for(let i=0;i<e.header.length;i++)r+=this.tablecell(e.header[i]);t+=this.tablerow({text:r});let n="";for(let i=0;i<e.rows.length;i++){let a=e.rows[i];r="";for(let o=0;o<a.length;o++)r+=this.tablecell(a[o]);n+=this.tablerow({text:r})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
|
|
273
|
+
<thead>
|
|
274
|
+
`+t+`</thead>
|
|
275
|
+
`+n+`</table>
|
|
276
|
+
`}tablerow({text:e}){return`<tr>
|
|
277
|
+
${e}</tr>
|
|
278
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
279
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${st(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let n=this.parser.parseInline(r),i=wv(e);if(i===null)return n;e=i;let a='<a href="'+e+'"';return t&&(a+=' title="'+st(t)+'"'),a+=">"+n+"</a>",a}image({href:e,title:t,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let i=wv(e);if(i===null)return st(r);e=i;let a=`<img src="${e}" alt="${st(r)}"`;return t&&(a+=` title="${st(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:st(e.text)}},Ku=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ke=class Bu{options;renderer;textRenderer;constructor(t){this.options=t||Pr,this.options.renderer=this.options.renderer||new rs,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ku}static parse(t,r){return new Bu(r).parse(t)}static parseInline(t,r){return new Bu(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let n=0;n<t.length;n++){let i=t[n];if(this.options.extensions?.renderers?.[i.type]){let o=i,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=s||"";continue}}let a=i;switch(a.type){case"space":{r+=this.renderer.space(a);break}case"hr":{r+=this.renderer.hr(a);break}case"heading":{r+=this.renderer.heading(a);break}case"code":{r+=this.renderer.code(a);break}case"table":{r+=this.renderer.table(a);break}case"blockquote":{r+=this.renderer.blockquote(a);break}case"list":{r+=this.renderer.list(a);break}case"checkbox":{r+=this.renderer.checkbox(a);break}case"html":{r+=this.renderer.html(a);break}case"def":{r+=this.renderer.def(a);break}case"paragraph":{r+=this.renderer.paragraph(a);break}case"text":{r+=this.renderer.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<t.length;i++){let a=t[i];if(this.options.extensions?.renderers?.[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){n+=s||"";continue}}let o=a;switch(o.type){case"escape":{n+=r.text(o);break}case"html":{n+=r.html(o);break}case"link":{n+=r.link(o);break}case"image":{n+=r.image(o);break}case"checkbox":{n+=r.checkbox(o);break}case"strong":{n+=r.strong(o);break}case"em":{n+=r.em(o);break}case"codespan":{n+=r.codespan(o);break}case"br":{n+=r.br(o);break}case"del":{n+=r.del(o);break}case"text":{n+=r.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}},$i=class{options;block;constructor(e){this.options=e||Pr}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Te.lex:Te.lexInline}provideParser(e=this.block){return e?Ke.parse:Ke.parseInline}},KP=class{defaults=Mu();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ke;Renderer=rs;TextRenderer=Ku;Lexer=Te;Tokenizer=ts;Hooks=$i;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let n of e)switch(r=r.concat(t.call(this,n)),n.type){case"table":{let i=n;for(let a of i.header)r=r.concat(this.walkTokens(a.tokens,t));for(let a of i.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let i=n;r=r.concat(this.walkTokens(i.items,t));break}default:{let i=n;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(a=>{let o=i[a].flat(1/0);r=r.concat(this.walkTokens(o,t))}):i.tokens&&(r=r.concat(this.walkTokens(i.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let a=t.renderers[i.name];a?t.renderers[i.name]=function(...o){let s=i.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[i.level];a?a.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),n.extensions=t),r.renderer){let i=this.defaults.renderer||new rs(this.defaults);for(let a in r.renderer){if(!(a in i))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=i[o];i[o]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u||""}}n.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new ts(this.defaults);for(let a in r.tokenizer){if(!(a in i))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=i[o];i[o]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new $i;for(let a in r.hooks){if(!(a in i))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=i[o];$i.passThroughHooks.has(a)?i[o]=l=>{if(this.defaults.async&&$i.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(i,l);return c.call(i,d)})();let u=s.call(i,l);return c.call(i,u)}:i[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(i,l);return d===!1&&(d=await c.apply(i,l)),d})();let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,a=r.walkTokens;n.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),i&&(s=s.concat(i.call(this,o))),s}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Te.lex(e,t??this.defaults)}parser(e,t){return Ke.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let n={...r},i={...this.defaults,...n},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&n.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(t):t,s=await(i.hooks?await i.hooks.provideLexer(e):e?Te.lex:Te.lexInline)(o,i),c=i.hooks?await i.hooks.processAllTokens(s):s;i.walkTokens&&await Promise.all(this.walkTokens(c,i.walkTokens));let l=await(i.hooks?await i.hooks.provideParser(e):e?Ke.parse:Ke.parseInline)(c,i);return i.hooks?await i.hooks.postprocess(l):l})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let o=(i.hooks?i.hooks.provideLexer(e):e?Te.lex:Te.lexInline)(t,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let s=(i.hooks?i.hooks.provideParser(e):e?Ke.parse:Ke.parseInline)(o,i);return i.hooks&&(s=i.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(e,t){return r=>{if(r.message+=`
|
|
280
|
+
Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+st(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},Cr=new KP;function O(e,t){return Cr.parse(e,t)}O.options=O.setOptions=function(e){return Cr.setOptions(e),O.defaults=Cr.defaults,kv(O.defaults),O};O.getDefaults=Mu;O.defaults=Pr;function JP(...e){return Cr.use(...e),O.defaults=Cr.defaults,kv(O.defaults),O}O.use=JP;O.walkTokens=function(e,t){return Cr.walkTokens(e,t)};O.parseInline=Cr.parseInline;O.Parser=Ke;O.parser=Ke.parse;O.Renderer=rs;O.TextRenderer=Ku;O.Lexer=Te;O.lexer=Te.lex;O.Tokenizer=ts;O.Hooks=$i;O.parse=O;var LO=O.options,BO=O.setOptions,MO=O.walkTokens,FO=O.parseInline;var VO=Ke.parse,qO=Te.lex;B();Rr();var Ed=At(mt(),1);import{promises as Ts}from"fs";import Ye from"path";Ae();B();Rr();ke();ne();L();lt();Ui();ne();L();Jr();Vt();var tA=At(mt(),1);Jr();Vt();tt();tt();pr();ql();Jr();tt();import{promises as rA}from"node:fs";import nA from"node:path";var bn=".gitignore",md=4*1024*1024,gd="# >>> Comet managed project state >>>",jg="# <<< Comet managed project state <<<";function iA(e){return e.includes(`\r
|
|
200
281
|
`)?`\r
|
|
201
282
|
`:`
|
|
202
|
-
`}function
|
|
203
|
-
`,"utf8"),await
|
|
204
|
-
${t}`).digest("hex")}async function
|
|
205
|
-
${
|
|
206
|
-
${
|
|
207
|
-
${
|
|
283
|
+
`}function aA(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function oA(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function $g(e){let t=[],r=!1;for(let n of aA(e)){let i=oA(n);if(i===gd){if(r)throw new Error("Comet .gitignore managed block is malformed");r=!0;continue}if(i===jg){if(!r)throw new Error("Comet .gitignore managed block is malformed");r=!1;continue}r||t.push(n)}if(r)throw new Error("Comet .gitignore managed block is incomplete");return t.join("")}function Tg(e){let t=$g(e).split(/\r?\n/u).map(r=>r.trim());return t.includes(".comet/runtime/")&&t.includes(".comet/current-change.json")}function vd(e){let t=iA(e),r=$g(e);return r.length>0&&!/(?:\r\n|\n|\r)$/u.test(r)&&(r+=t),r+[gd,"!/.comet/","/.comet/*","!/.comet/config.yaml",jg,""].join(t)}async function wd(e){let t=nA.resolve(e),r=await gt(t,bn,{label:"project .gitignore",expected:"file"}),n="",i=new Uint8Array;if(r.exists&&(i=(await Z(t,bn,md,{label:"project .gitignore"})).bytes,n=Buffer.from(i).toString("utf8")),r.exists&&!n.includes(gd)&&Tg(n))return;let a=vd(n);if(a!==n){try{await hr(r.target,a,{containedRoot:t,exclusive:!r.exists,beforeCommit:r.exists?async()=>{if(!(await Z(t,bn,md,{label:"project .gitignore"})).bytes.equals(i))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await gt(t,bn,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}})}catch(o){let s=o instanceof Error&&o.message==="Project .gitignore was created before commit; rerun initialization";if(r.exists||o.code!=="EEXIST"&&!s)throw o;let c=await Z(t,bn,md,{label:"project .gitignore"}),l=Buffer.from(c.bytes).toString("utf8");if(vd(l)!==l&&!Tg(l))throw o}await gt(t,bn,{label:"project .gitignore",expected:"file"}),await rA.access(r.target)}}import{AsyncLocalStorage as sA}from"node:async_hooks";var cA=new sA;function lA(){let e=cA.getStore();return e?.active?e:null}function uA(e,t){let r=e;for(let n of t)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function Og(e,t){return(...r)=>{let n=lA();if(n===null)return t(...r);let i=uA(`async:${e}`,r),a=n.entries.get(i);if(a)return a.value;let o=t(...r).catch(s=>{throw n.entries.get(i)?.value===o&&n.entries.delete(i),s});return n.entries.set(i,{value:o}),o}}pr();var YD=Og("hookWritePolicy",async e=>(await fr(e))?.hook??{allow_paths:[]});di();import{randomUUID as dA}from"node:crypto";import{promises as Cs}from"node:fs";import Dg from"node:path";var Ps="comet.selection.v2",fA=16*1024;function yd(e){return Dg.join(e,".comet","current-change.json")}function pA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Hg(e){return e===null||typeof e=="string"}function hA(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!pA(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&&!Hg(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ps,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ps)throw new Error(`current change selection schema must be ${Ps}`);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(!Hg(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 bd(e,t){let r=hA(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let n=yd(e),i=`${n}.${dA()}.tmp`;await Cs.mkdir(Dg.dirname(n),{recursive:!0});try{await Cs.writeFile(i,`${JSON.stringify(r.selection,null,2)}
|
|
284
|
+
`,"utf8"),await Cs.rename(i,n)}catch(a){throw await Cs.rm(i,{force:!0}),a}}Fl();li();var YL=Number.MAX_SAFE_INTEGER;B();rt();var l1={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import{createHash as yA}from"node:crypto";import{promises as Rs}from"node:fs";import Zt from"node:path";B();Ae();ne();L();var Yi=/^[a-f0-9]{64}$/u,Bg=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,bA=16*1024,kd=process.platform;function Vg(e,t){let r=Zt.relative(e,t);return Zt.isAbsolute(r)||r===".."||r.startsWith(`..${Zt.sep}`)?null:r.replaceAll("\\","/")||"."}function qg(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Wg(e,t){if(e.length===0||qg(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 r=Zt.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Sd(e,t){return yA("sha256").update(`${e}
|
|
285
|
+
${t}`).digest("hex")}async function Mg(e,t){let r=await Rs.realpath(t),n=await Rs.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let i=kd==="win32"?Zt.normalize(r).toLowerCase():r;return Sd(e,`${i}
|
|
286
|
+
${n.dev}
|
|
287
|
+
${n.ino}
|
|
288
|
+
${n.birthtimeMs}`)}async function Fg(e,t){let r=await Rs.realpath(t),n=await Rs.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let i=kd==="win32"?Zt.normalize(r).toLowerCase():r;return Sd(e,i)}function NA(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 Nd(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||qg(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function zg(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Nd(e.changeBranch,"Native workspace change branch"),Nd(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 kA(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${n.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Bg.test(t.baseCommit)||typeof t.targetCommit!="string"||!Bg.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Nd(t.targetBranch,"Native workspace Git target branch")}function _s(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(t).filter(o=>!r.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"||!Yi.test(String(t.projectRootId))||!Yi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");NA(t.capturedAt),Wg(t.nativeRootRef,"Native workspace root ref");let i=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(i!==a)throw new Error("Native workspace path identities must be provided together");if(i&&!Yi.test(String(t.projectRootPathId))||a&&!Yi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Yi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&kA(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(zg(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 SA(e,t){return Zt.join(Ne(e,t),"workspace.json")}function EA(e,t){let r=SA(e,t),n=qe(e,r),i=Vg(n,r);if(!i||i===".")throw new Error("Native workspace file escaped its root");return{root:n,ref:Wg(i,"Native workspace file ref")}}async function xA(e,t){try{let r=EA(e,t),n=await ue({root:r.root,ref:r.ref,maxBytes:bA});return JSON.parse(n.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function CA(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Vg(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ge(e.paths.projectRoot),n=r.isGitWorktree?br(e.paths.projectRoot,"HEAD"):null,i=e.binding?.targetBranch??r.currentBranch,a=i==null?null:br(e.paths.projectRoot,i),o=n!==null&&i!==null&&i!==void 0&&a!==null?{provider:"git",baseCommit:n,targetBranch:i,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Mg("comet.native.workspace-project-root.v2",e.paths.projectRoot),Mg("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Fg("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Fg("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&zg(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Sd("comet.native.workspace-session.v2",`${s}
|
|
208
289
|
${c}
|
|
209
|
-
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return
|
|
290
|
+
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return _s(p),p}async function Nn(e,t){let r=await xA(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(_s(r),r)}async function As(e){_s(e.identity);let t=await CA({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),kd==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):r.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:r}}async function Is(e){if(_s(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 As(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ge(e.paths.projectRoot);return e.identity.changeBranch===null?r.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}:r.isGitWorktree?r.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 ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.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 Gg(e,t){let r=await Nn(e,t);if(r===null)return null;let n=await Is({paths:e,identity:r});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return r}Vi();ms();ms();var js=class extends Error{constructor(r,n,i){super(`Native change ${r} revision conflict: expected ${n}, actual ${i}`);this.change=r;this.expectedRevision=n;this.actualRevision=i;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},kn=class extends Error{constructor(r,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=r;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},$s=class extends Error{constructor(r,n,i,a,o,s=null,c=null){super(`Native change ${r} 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=r;this.omittedCount=n;this.omittedByReason=i;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"},Y1=Li("en");function er(e,t){mn(t);let r=Ye.join(e.changesDir,t);if(!te(e.changesDir,r))throw new Error("Native change path escaped");return r}async function xd(e,t){let r=Ne(e,t),n=Ye.join(r,"schema-migration.json");await j(te(e.runtimeDir,n)?e.runtimeDir:e.nativeRoot,n);try{return await Ts.lstat(n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Jg(e,t=Ye.dirname(e)){let r=Ye.relative(t,e).split(Ye.sep).join("/"),n=await ue({root:t,ref:r,maxBytes:null,includeHash:!1}),i=(0,Ed.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${i.errors[0].message}`);return i.toJS()}async function _A(e,t){let r=Ye.join(er(e,t),Je);await j(e.nativeRoot,r);let n=hs(await Jg(r,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await xd(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 IA(e,n.state),n)}async function AA(e,t){let r=Ye.join(er(e,t),Je);await j(e.nativeRoot,r);let n=hs(await Jg(r,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return n}async function IA(e,t){if(await Ig(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function tr(e,t){let r=await _A(e,t);if(r.status==="migration-required")throw new hn(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Ct(r.schema,r.minimumRuntimeVersion);return await Gg(e,t),r.state}async function TA(e){let t;try{let n=await Ji({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await n.verify(),t=n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}return t.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort()}async function Ug(e){let t=[];for(let r of await TA(e)){let n=await AA(e,r);if(!n.state){if(await Kg(e,r))continue;t.push(r);continue}if(n.state.archived)continue;let i=await Nn(e,r);if(!(!i&&await Kg(e,r))){if(i?.schema==="comet.native.workspace.v3"){if((await Is({paths:e,identity:i})).code==="workspace-binding-root-changed")continue}else if(i&&(await As({paths:e,identity:i})).state==="drifted")continue;t.push(r)}}return t}async function Kg(e,t){for(let r of yr(e.projectRoot))if(!it(r,e.projectRoot))try{let n=await oe(r);if(!n)continue;let i=await yt(r,n.native.artifact_root),a=Ye.join(i.changesDir,t),o=Ye.join(a,"comet-state.yaml");try{let l=await Ts.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ts.readFile(Ye.join(Ve(i,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&it(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await Ts.access(Ye.join(a,Je));let s=await Nn(i,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Is({paths:i,identity:s})).state==="aligned")return!0;continue}if((await As({paths:i,identity:s})).state!=="drifted")return!0}catch{}return!1}Ae();ut();L();var $A=["outcome","scope","nonGoals","acceptanceExamples"],cB=[...$A,"constraints","decisions","openQuestions","verificationExpectations"];var Xi=class extends Error{constructor(r,n,i){super(r);this.findings=n;this.change=i;this.name="NativeDocumentConstraintError"}findings;change};Ae();J();var lI=At(mt(),1);ze();Ae();J();ke();L();Yt();Os();Os();mr();rr();ze();ss();B();J();Hs();ne();L();Yg();mr();rr();Ls();ze();import{promises as ta}from"node:fs";import ye from"node:path";ke();Ls();Fi();L();var nr=class extends Error{constructor(r,n,i){super(r,i);this.preparation=n;this.name="NativeWorkspacePreparationError"}preparation};function ew(e,t){let r=ye.relative(e,t);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function Qg(e){return JSON.stringify(e.native)}async function Bs(e,t){let r=await oe(e);if(r&&t){if(Qg(r)!==Qg(t))throw new Error(`Native worktree configuration differs from the source project: ${ye.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await hi(e,t),await Ds(e),!0):!1}async function GA(e,t){if(!ew(e,t))return!1;let n=`/${ye.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,i=re(e,["rev-parse","--git-common-dir"]),a=ye.resolve(e,i),o=ye.join(a,"info","exclude"),s="";try{s=await ta.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(n))return!1;await ta.mkdir(ye.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
210
291
|
`)?"":`
|
|
211
|
-
`;return await
|
|
212
|
-
`,"utf8"),!0}function
|
|
292
|
+
`;return await ta.appendFile(o,`${c}${n}
|
|
293
|
+
`,"utf8"),!0}function KA(e,t,r){let n=ye.resolve(e,r??ye.join(".worktrees",t)),i=ye.resolve(e,re(e,["rev-parse","--git-common-dir"]));if(ew(i,n))throw new Error("Native worktree path cannot be inside the Git common directory");if(yr(e).some(a=>it(a,n)))throw new Error(`Native worktree path is already registered: ${n}`);return n}async function JA(e){try{throw await ta.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Zg(e){try{return await ta.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Rd(e){let t=ye.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let n=ge(t);if(n.isGitWorktree&&n.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:n.currentBranch,targetBranch:n.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:n.currentBranch,targetBranch:n.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await yt(t,e.sourceConfig?.native.artifact_root??"docs");return Yv([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let n=ge(t);if(!n.isGitWorktree||n.currentBranch===null||n.primaryWorktreeRoot===null||n.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let i=e.changeBranch??`comet/${e.name}`;du(t,i);let a=n.currentBranch===i,o=e.targetBranch??(a?void 0:n.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(du(t,o),!nn(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!uu(t))throw new Error("Native branch isolation requires a clean current working directory");if(nn(t,i))throw new Error(`Native change branch already exists: ${i}`);re(t,["switch","-c",i,o]),p=!0}let m;try{m=await Bs(t,e.sourceConfig)}catch(h){throw new nr(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:i,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:i,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:i,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!n.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?ye.resolve(n.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!it(p,n.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${n.currentWorktreeRoot}`);let m;try{m=await Bs(t,e.sourceConfig)}catch(h){throw new nr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:i,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:i,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:i,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Jo(n.primaryWorktreeRoot),c=s.find(p=>p.branch===i);if(c&&await Zg(c.root)){let p=e.worktreePath?ye.resolve(n.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!it(p,c.root))throw new Error(`Native worktree branch ${i} is already checked out at ${c.root}`);let m;try{m=await Bs(c.root,e.sourceConfig)}catch(h){throw new nr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:i,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:i,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:i,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await Zg(c.root)&&(re(n.primaryWorktreeRoot,["worktree","prune"]),s=Jo(n.primaryWorktreeRoot));let l=nn(t,i);if(s.some(p=>p.branch===i))throw new Error(`Native change branch ${i} is already registered to a worktree`);let u=KA(n.primaryWorktreeRoot,e.name,e.worktreePath);await JA(u);let d=await GA(n.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:i,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{re(n.primaryWorktreeRoot,l?["worktree","add",u,i]:["worktree","add","-b",i,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Bs(u,e.sourceConfig)}catch(p){throw new nr(`Native worktree preparation is incomplete: ${p.message}`,f,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:i,targetBranch:o},preparation:f}})}ze();ke();ne();mr();rr();Uo();Yt();_r();xi();qo();ne();ad();Do();Yt();_r();B();Rr();xi();L();Rr();Cn();ke();Yt();_r();rr();var CI=Li("en",{compact:!0});async function Td(e){return X(e.paths,`create portable change ${e.name}`,async()=>{if(!Ou.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await oe(e.paths.projectRoot)===null&&await hi(e.paths.projectRoot,e.initialProjectConfig),hv(e.paths.projectRoot,e.workspaceBinding);let t=(await Ug(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new kn(e.workspaceBinding?.isolation??"current",t);let r=ot(e.paths,e.name),n=Ve(e.paths,e.name);await Promise.all([j(e.paths.nativeRoot,r),j(e.paths.runtimeDir,n)]);let i=!1,a=!1;try{await Ir.mkdir(e.paths.changesDir,{recursive:!0}),await Ir.mkdir(r,{recursive:!1}),i=!0,await Ir.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await Ir.mkdir(n,{recursive:!1}),a=!0,await Ir.mkdir(cw.join(r,"specs"),{recursive:!0}),await ee(cw.join(r,"brief.md"),Li(e.language,{compact:!0}));let o=cv({name:e.name,language:e.language,workspace:pv(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await lv(Ti(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await kr(Xt(e.paths,e.name),Nr({portableState:o,projectRoot:e.paths.projectRoot,branch:Er(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await Ir.rm(n,{recursive:!0,force:!0}),i&&await Ir.rm(r,{recursive:!0,force:!0}),o}})}ke();ne();mr();rr();Yt();_r();ze();ss();J();ze();tt();B();var uq=8*1024*1024;Hs();ne();_r();L();var jq=1024*1024*1024;ne();qo();xi();rr();ne();rr();ne();cd();ke();ne();var Ez=16*1024;async function pw(e,t){return X(e,`select change ${t}`,async()=>{mn(t),await Hu(e,t)?await Nt(e,t):await tr(e,t),await bd(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}Ls();di();import ia from"path";import{realpathSync as vT}from"fs";function hw(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},n=r(e),i=r(n.entry),a=r(n.state??i.state??n),o=r(n.preparation??n.workspace??i.workspace),s=r(n.continuation??i.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var _t={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mw(e){return e?e.command?`${_t.next} ${e.command}`:e.ask_user?`${_t.next} ${e.ask_user}`:null:null}function vw(e,t){let r=[e.summary],n=mw(e.next);return n&&r.push(n),e.user_message&&r.push("",_t.relay,e.user_message),t!==void 0&&r.push("",_t.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
213
294
|
`)}
|
|
214
|
-
`}function
|
|
215
|
-
`)}
|
|
216
|
-
`)}}let r=t.continuation;if(
|
|
295
|
+
`}function gw(e,t,r){let n=[e.summary],i=mw(e.next);return i&&n.push(i),e.user_message&&n.push("",_t.relay,e.user_message),n.push("",`${_t.detail} ${t}`),r!==void 0&&n.push("",_t.details,JSON.stringify(r,null,2)),n.join(`
|
|
296
|
+
`)}J();Ae();J();var _I=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});Cn();lt();ke();L();B();ut();Fi();ne();L();lt();Ar();J();J();Ms();xn();ut();var ww={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:[]},II=Pe("comet-native-runtime:v3:scope-reopen"),f2=[{skillVersion:"3",skillHash:Pe("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Pe("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Pe("comet-native-runtime:v1")}];ut();ut();Vi();var bw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],G2=new Set(bw),DI=new Set([...bw,"minimum_runtime_version","revision"]),K2=new Set([...DI,"operation"]),LI=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),J2=new Set([...LI,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);vs();Ae();Ae();vs();J();var Z2={maxAcceptanceCriteria:ag.maxCriteria};Cn();Ui();xn();Ms();import{execFile as JI}from"node:child_process";Qr();Pi();Cd();import{promisify as UI}from"node:util";B();ut();L();lt();vi();Ar();ne();B();Ad();L();rt();Cn();ne();Ar();var na=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Ui();Fs();xn();var rK=64*1024;var nK=3600*1e3;var iK=UI(JI);Fs();var qs=class extends Error{details;constructor(t){let r=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(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};ut();lt();B();rt();L();lt();Ss();B();Rr();Cn();var rJ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});ut();Fi();ne();L();lt();Ss();var Ws=class extends Error{constructor(r,n,i,a){super(`Canonical spec conflict for ${r}: expected ${n??"(missing)"}, actual ${i??"(missing)"}`);this.capability=r;this.expectedHash=n;this.actualHash=i;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},zs=class extends Error{constructor(r,n=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(n);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};L();ke();function C(e,t,r){return e==="zh-CN"?r:t}var jd={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Sw(e,t){return typeof e=="string"&&jd[e]?C(t,jd[e].en,jd[e].zh):typeof e=="string"?e:""}function $d(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function tT(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let n=r.result;if(n!=="passed"&&n!=="failed"&&n!=="blocked"&&n!=="pending")return null;t[n]+=1}return t}function Ew(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let n=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${n} (${r.join(", ")})`:n}function xw(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Od(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function rT(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function nT(e,t,r){let n=Od(e),i=[];r&&i.push(r);let a=C(n,`Change ${e.change}`,`需求 ${e.change}`),o=Sw(e.phase,n),s=rT(e.disposition,e.userCommunication.required,n);i.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&i.push(Ew(t,n));let c=e.userCommunication,l=Cw(e,n);return{summary:i.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Cw(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:C(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function iT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function aT(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",n=Sw(e.phase,t),i=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=$d(e.acceptance)?`${C(t,", ",",")}${Ew(e.acceptance,t)}`:"";return` ${r} · ${n||String(e.phase??"?")} · ${i}${a}`}function oT(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function sT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function cT(e){if(e.healthy){let n=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),i=lT(e.continuation);return i?{summary:n,next:i}:{summary:n}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:C("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function lT(e){return xw(e)?Cw(e,Od(e)):void 0}function Pw(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(sT(t))return cT(t);if(iT(t)){let n=oT(t.items);return{summary:[t.total===t.items.length?C(n,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(n,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>aT(a,n))].join(`
|
|
297
|
+
`)}}let r=t.continuation;if(xw(r)){let n=Od(r),i=nT(r,uT(t),fT(t,n));return dT(t)==="unconfirmed"?{...i,summary:`${i.summary}${C(n,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:i}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let n=t.language==="zh-CN"?"zh-CN":"en",i="pendingRootMove"in t;return{summary:C(n,i?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,i?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function uT(e){if($d(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if($d(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return tT(r.acceptance)}return null}function dT(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function fT(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Rw(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:C("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:C("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Vo();Uo();var _w=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Hd=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","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:_w,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
|
|
217
298
|
comet native spec remove <change-name> <capability>
|
|
218
299
|
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],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."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},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, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with canonical artifact paths and local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary 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> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
219
300
|
comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
|
|
220
|
-
comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, 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 the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session
|
|
221
|
-
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 Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--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, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; 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
|
|
301
|
+
comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, 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 the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request With --accept-result, record the explicitly chosen isolated-workspace finish in the same guarded decision.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, verification_checks, known_limits, optional review. acceptance_review must cover every confirmed ID exactly once with id, status, evidence (concrete references or observations), and note. Only implemented-with-evidence with nonempty evidence is ready for handoff; implemented-no-evidence, not-implemented, and known-fail remain in Build. This Builder declaration does not replace independent verification. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan returns the Verifier dispatch immediately. Completed Runtime checks can carry to a new candidate only when the implementation, confirmed documents, plan, workspace, environment, and saved evidence still match. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," 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."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". 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 --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','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] [--commit-message <text>] [--merge-message <text>]
|
|
302
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--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, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; 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 Gs(e,t){return`${e}:
|
|
222
303
|
${t.map(r=>` ${r}`).join(`
|
|
223
|
-
`)}`}function
|
|
224
|
-
${r.output}`),r.examples&&
|
|
304
|
+
`)}`}function pT(e){let t=e.filter(n=>n!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Hd[r]||t.length>1&&Hd[t[0]]?.subcommands?r:t[0]}function hT(e=[]){let t=pT(e),r=Hd[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let n=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&n.push("",Gs("Agent Quick Start",r.agentQuickStart)),r.subcommands&&n.push("",Gs("Commands",r.subcommands));let i=t===""?r.options:[...r.options??[],..._w];return i&&i.length>0&&n.push("",Gs("Options",i)),n.push("",`Output:
|
|
305
|
+
${r.output}`),r.examples&&n.push("",Gs("Examples",r.examples)),t===""&&n.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${n.join(`
|
|
225
306
|
`)}
|
|
226
|
-
`}}var
|
|
227
|
-
`}function
|
|
228
|
-
`}:e.error?{exitCode:e.exitCode,stderr:
|
|
229
|
-
${
|
|
307
|
+
`}}var mT=hT().usage;var pU=10*1024*1024,Xe=class extends Error{};function Ld(e,t){let r=e.flatMap((n,i)=>n===t?[i]:[]);if(r.length>1)throw new Xe(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function ft(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Xe(`${t} may only be provided once`);if(r.length===0)return;let n=r[0],i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Xe(`${t} requires a value`);return e.splice(n,2),i}function Iw(e){if(e.length>0)throw new Xe(`Unexpected argument: ${e[0]}`)}function Tw(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Xe(`${t} is required`);return r}function jw(e,t="en"){let r=ft(e,"--language")??t;if(r!=="en"&&r!=="zh-CN")throw new Xe("--language must be en or zh-CN");return r}function Dd(e,t){let r=ia.normalize(Aw(e)),n=ia.normalize(Aw(t));return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function Aw(e){let t=ia.resolve(e);try{return vT.native(t)}catch{return t}}function gT(e,t){let r=ia.resolve(t,e),n=ge(t);if(!n.isSecondaryWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null)return r;let i=ge(r);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Dd(n.primaryWorktreeRoot,i.primaryWorktreeRoot)||Dd(n.currentWorktreeRoot,i.currentWorktreeRoot)?r:Dd(t,n.currentWorktreeRoot)?ia.resolve(t):n.currentWorktreeRoot}async function $w(e,t=process.cwd()){return e?gT(e,t):Gl(t)}function Ow(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}function Hw(e){return JSON.stringify(e,null,2)+`
|
|
308
|
+
`}function Dw(e,t,r){return{command:e,exitCode:0,data:t,text:r??Hw(t)}}function wT(e,t){if(t instanceof Xi)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof cn)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof Ei)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Xe)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Ws)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 zs)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof js)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 kn)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 nr)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof $s)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 qs)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof na)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Lw(e,t){let r=wT(e,t),n=r.error;if(!n)return r;let i=Rw({code:n.code,message:n.message,data:r.data});return i?{...r,envelope:i}:r}function yT(e,t,r=!1){let n=e.envelope??Pw(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:hw(e.data,e.executionCwd),...n===void 0?{}:{summary:n.summary,...n.next===void 0?{}:{next:n.next},...n.user_message===void 0?{}:{user_message:n.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
309
|
+
`}:e.error?{exitCode:e.exitCode,stderr:n?gw(n,e.error.message,r?e.data:void 0):e.error.message}:n?{exitCode:e.exitCode,stdout:vw(n,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Hw(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
310
|
+
${_t.details}
|
|
230
311
|
${JSON.stringify(e.data,null,2)}
|
|
231
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function
|
|
232
|
-
`)}}async function
|
|
312
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function bT(e,t,r=!1){let n=yT(e,t,r),i=!1;if(n.stdout?.trim())try{let a=JSON.parse(n.stdout);i=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{i=!1}return{output:n,structuredDataVisible:i}}function Bw(e,t,r=!1){return bT(e,t,r).output}async function kT(e){let t=await ue({root:e.paths.specsDir,ref:`${e.capability}/spec.md`,maxBytes:null,includeHash:!1}),r=e.capability.split("/"),n=ot(e.paths,e.changeName),i=`specs/${e.capability}/spec.md`,a=`specs/${e.capability}/delta.yaml`;await NT.mkdir(Ks.join(n,"specs",...r),{recursive:!0}),await ee(Ks.join(n,...i.split("/")),t.text,{containedRoot:e.paths.nativeRoot});let o=zt(t.text),s=ou(t.text),c={schema:"comet.native.delta.v1",capability:e.capability,base_hash:o,base_version:1,legacy_hash:Ho(t.text),base_requirements:Object.fromEntries(s.requirements.map(l=>[l.id,zt(l.raw)])),operations:[]};return await ee(Ks.join(n,...a.split("/")),au(c),{containedRoot:e.paths.nativeRoot}),{specSource:i,deltaSource:a,baseHash:o}}async function ST(e,t,r,n){if(!r&&!n)return null;let i=[],a={workflow:"native",currentSpecRoot:`${t}/comet/specs`,archiveRoot:`${t}/comet/archive`};try{if(r&&!n){let l=await Wm({projectRoot:e,scope:a,task:r});if(l)return l}let o=n?void 0:await Fm({projectRoot:e,scope:a,reportDiagnostic:l=>i.push(l)}),s=await om({projectRoot:e,scope:a,...o?{provider:o}:{},...r?{task:r}:{},...n?{capability:n}:{}}),c={...s,diagnostics:[...i,...s.diagnostics]};return r&&!n&&await zm({projectRoot:e,scope:a,task:r,result:c}),c}catch(o){if(n)throw o;return{workflow:"native",query:null,candidates:[],associationDraft:null,diagnostics:[...i,{code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${o instanceof Error?o.message:String(o)}`}],searched:!!r,providerLimit:40}}}async function Mw(e,t){let r=Tw(e,"change name"),n=await oe(t),i=jw(e,n?.native.language??"en"),a=ft(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new Xe("--isolation must be current, branch, or worktree");let o=ft(e,"--change-branch"),s=ft(e,"--target-branch"),c=ft(e,"--worktree-path"),l=ft(e,"--task"),u=ft(e,"--capability");Iw(e);let d=n;if(n?.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);let f=await Rd({projectRoot:t,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:d});t=f.projectRoot,n=await oe(t);let p=n===null?Qh("docs",i):void 0;if(n||(n=p),n.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);let m=await yt(t,n.native.artifact_root);await Yh(m),await wd(t);let h=await ST(t,n.native.artifact_root,l,u),v=await Td({paths:m,name:r,language:i,workspaceBinding:f.binding,...p?{initialProjectConfig:p}:{}}),w,y;return h?.associationDraft&&(y=await kT({paths:m,changeName:v.name,capability:h.associationDraft.capability}),w=Ks.join(ot(m,v.name),"capability-association.yaml"),await ee(w,sm(h.associationDraft),{containedRoot:m.nativeRoot})),await pw(m,v.name),p&&await Ds(t),{executionCwd:t,...Dw("new",{...v,artifacts:Xh(m,v.name),preparation:f.preparation,...h===null?{}:{capabilityDiscovery:h,...w===void 0?{}:{associationPath:w},...y===void 0?{}:{deltaProposal:y}},continuation:Xm(v)},`Created Native change ${v.name}
|
|
313
|
+
`)}}async function Fw(e,t,r=process.argv.slice(2)){let n=r.indexOf("--"),i=n<0?[...r]:r.slice(0,n),a=n<0?[]:r.slice(n),o=i.includes("--json"),s=i.includes("--verbose"),c,l;try{Ld(i,"--json"),Ld(i,"--verbose"),c=ft(i,"--project-root");let d=[...i,...a],f=async()=>{let p=await $w(c);return{executionCwd:p,...await t(d,p)}};l=Ow(e,d)?await nv(f):await f()}catch(d){l=Lw(e,d)}let u=Bw(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
233
314
|
`)?"":`
|
|
234
|
-
`)),u.exitCode}process.exitCode=await
|
|
315
|
+
`)),u.exitCode}process.exitCode=await Fw("new",Mw);
|