@rpamis/comet 0.4.3 → 0.4.4
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 +332 -332
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +109 -96
- 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 +173 -160
- 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 +269 -159
- 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 +272 -259
- package/assets/skills/comet/scripts/comet-state.mjs +204 -191
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +25 -25
- package/assets/skills/comet-archive/SKILL.md +4 -4
- 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 +7 -7
- package/assets/skills/comet-native/reference/clarification.md +4 -4
- 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 +230 -149
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +239 -161
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +232 -122
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +184 -107
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +219 -142
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +239 -161
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +205 -128
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +276 -195
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +204 -127
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +202 -125
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +203 -125
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +200 -123
- 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 +4 -4
- 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 +7 -7
- package/assets/skills-zh/comet-native/reference/clarification.md +4 -4
- 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/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/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-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-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-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 +3 -1
- package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifact-language.js +4 -11
- package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
- package/dist/domains/comet-native/native-artifacts.d.ts +8 -1
- package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifacts.js +14 -2
- 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 +56 -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 +61 -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 +10 -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/dashboard/web/assets/{abnfDiagram-VCTEODGH-qlcciI25.js → abnfDiagram-VCTEODGH-CFEU4PQU.js} +1 -1
- package/dist/domains/dashboard/web/assets/{arc-KVm4k9kp.js → arc-BeYYJor9.js} +1 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-YphM8Wtg.js +1 -0
- package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-C366RdBK.js → architectureDiagram-5GKGNRK7-CqTy4fyH.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-DAuTc2OO.js → blockDiagram-I7D4REHJ-SR_5S4SA.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-CFB0RZmL.js → c4Diagram-7LVT6UL2-DzphG2XS.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-BkwcGbYR.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-DTV6lyGQ.js → chunk-4HAMMTFA-BpthUtIs.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-DgJm4cEX.js → chunk-75Z2AOVW-CxAdhPhG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-NAtcgGZr.js → chunk-DU6HZSFF-5peVNfxp.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-BcFXHZMJ.js → chunk-F27PBJKO-CwG4xi2V.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-wNemar9b.js → chunk-GMAD6QVW-BuFFY783.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-BiVCDO9d.js → chunk-GVQU2GXP-OyUFmjE-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-D9GDj4b6.js → chunk-IMKFNOWR-DmTme45C.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-DkPl5vac.js → chunk-L3NEJ4N5-D6BHbKty.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-RbbxGqtJ.js → chunk-OSK3NFVY-CCz1v1Nv.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-B9_X57eT.js → chunk-P2QGCYS3-C1_7kDYS.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DE4bOH0D.js → chunk-POPQ4Y6H-buFKlAdG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Bo-W1iA1.js → chunk-PWAF6VOD-B_K6Jrsv.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BhLxs4rZ.js → chunk-SHT3W25Y-CRRLsXmS.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-BCXfn8uF.js → chunk-SVP7TREG-Q5zCQTul.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-DqSBgE5L.js → chunk-TICWLB2K-Zc5XaO5Z.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-Dbkt1xEZ.js → chunk-XXDRQBXY-BAIB2h_r.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DzpQhyL3.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DzpQhyL3.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-DrwNpMyX.js → cose-bilkent-JH36ORCC-C7jkFYhm.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-BbDlivxs.js → cynefin-OW5HDTMX-4yS-l7kx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DmLmRN42.js → cynefinDiagram-5FMLGOSQ-DAkfQ8jW.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-Cgm5DNgI.js → dagre-GXQ25YYZ-D3b16ruz.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-Bnht1X2m.js → diagram-S7CK7UJ4-BXZHtdNz.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-LELTI4PR.js → diagram-UQ7AKVKN-B4nIzofw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-Do0fZuNG.js → diagram-VSXAHHWV-B6d7KNj1.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-B0rZTUwt.js → diagram-VX7I27RA-CHr0Rg8a.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-wn8xCc_j.js → diagram-Z3DM3KII-BO2IxR9N.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dist-CYwDKy2m.js → dist-0wyW4qbm.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CMDOpP2T.js → ebnfDiagram-PWID7BFC-CHRK8Hyg.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-C2d43bdq.js → erDiagram-RLTQ6QDP-_HFHzZlc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{es-BzaOcXwu.js → es-kjndkyYX.js} +1 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-CG-cVTEg.js +1 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-C3RaJz-z.js +1 -0
- package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-hTH7TzhY.js → ganttDiagram-EL5Y4UJY-CxhSw1PI.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-C3CCywb-.js → gitGraph-4MIJSDKK-Cbw-3Dnk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-DW6jDckj.js → gitGraphDiagram-WWUBYQGX-Cx93hwtL.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-CTZPz_mx.js → index-CQb8j5OE.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--d4EMiIK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-7zk6ytVJ.js → infoDiagram-27XIBGKW-DMkRRNGB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CGDCTmCQ.js → ishikawaDiagram-5VMMS53U-CjKh_jHT.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-C8_L_e8a.js → journeyDiagram-3NMN7TZE-CG735M_M.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-D5x6qTgM.js → kanban-definition-UXKFOSKX-CgXFmhFM.js} +1 -1
- package/dist/domains/dashboard/web/assets/{line-DC93oja4.js → line-Bhf8l3gG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-81TNubkB.js → linear-YWT9mnmu.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid-parser.core-D60d8uy9.js → mermaid-parser.core-COzQ1kq0.js} +3 -3
- package/dist/domains/dashboard/web/assets/{mermaid.core-l4Wgjz2Q.js → mermaid.core-Cc1lMpx-.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-Dfqu1201.js → mindmap-definition-YA3MSWOX-B_VOgUSO.js} +1 -1
- package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CsFZBhTs.js → packet-AYTQ26CC-CXbJLNC9.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-myFMaA7n.js → pegDiagram-XKGWAZYB-BuS0hioo.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-FMuCTNSk.js → pie-WAS4IAKB-BEaGwdWZ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-CSR4B4Z1.js → pieDiagram-E7YTZNPT-DDzYv-_9.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-DExT--Ut.js} +1 -1
- package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-BZ-n7JtG.js → radar-RG4KPBEZ-C1JtzGr8.js} +1 -1
- package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CWVtRfHu.js → railroad-74A4TZTK-CMpkXATR.js} +1 -1
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-BM35gYWg.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CN60GGp0.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DRUSW4g7.js +1 -0
- package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-CBj7v1de.js → railroadDiagram-O6MQD6OU-BCE65sLR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-DSDgb54n.js → requirementDiagram-BXWQKSXE-CmyX3vGG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-1-oXLUAP.js → sankeyDiagram-P5KCCOFB-BFKrX2dv.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DAF4nGs_.js → sequenceDiagram-WJ2MYXX4-DqodS9W-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{src-CTWLVUqE.js → src-BVUP3QzK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-DzENBaJT.js → stateDiagram-D77RDMKH-nHai_EZh.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-BL6vE1m9.js +1 -0
- package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-CnxFUZJc.js → swimlanes-42K2YHIH-BODBARYN.js} +1 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-XHK_nuTj.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-KtvPzpZM.js → timeline-definition-24CTP7MA-RVnG8rgK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bdu3P9iY.js → treeView-Q6P3EWNA-B6lrg3KQ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-DFnn23JR.js → treemap-WGGIJYW6-CJfMKVf4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-BjpviP26.js → vennDiagram-4TSXK5OY-CZMWJiN7.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-CEo4a-j4.js → wardley-WFR3VGLG-BoUsbNlx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-Bf54n6im.js → wardleyDiagram-VM6X3IG4-BwBCykVb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-CU-hI0Cm.js → xychartDiagram-S5SC5T6Z-vutnbx57.js} +1 -1
- package/dist/domains/dashboard/web/index.html +2 -2
- 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/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/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 +32 -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/package.json +1 -1
- 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/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,148 +1,148 @@
|
|
|
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 Bw=Object.create;var Ks=Object.defineProperty;var Mw=Object.getOwnPropertyDescriptor;var Fw=Object.getOwnPropertyNames;var Vw=Object.getPrototypeOf,qw=Object.prototype.hasOwnProperty;var na=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var S=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(i){throw r=[i],i}};var N=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Ww=(t,e)=>{for(var r in e)Ks(t,r,{get:e[r],enumerable:!0})},zw=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fw(e))!qw.call(t,n)&&n!==r&&Ks(t,n,{get:()=>e[n],enumerable:!(i=Mw(e,n))||i.enumerable});return t};var At=(t,e,r)=>(r=t!=null?Bw(Vw(t)):{},zw(e||!t||!t.__esModule?Ks(r,"default",{value:t,enumerable:!0}):r,t));var A=N(Q=>{"use strict";var Js=Symbol.for("yaml.alias"),Bd=Symbol.for("yaml.document"),aa=Symbol.for("yaml.map"),Md=Symbol.for("yaml.pair"),Us=Symbol.for("yaml.scalar"),oa=Symbol.for("yaml.seq"),ft=Symbol.for("yaml.node.type"),Gw=t=>!!t&&typeof t=="object"&&t[ft]===Js,Kw=t=>!!t&&typeof t=="object"&&t[ft]===Bd,Jw=t=>!!t&&typeof t=="object"&&t[ft]===aa,Uw=t=>!!t&&typeof t=="object"&&t[ft]===Md,Fd=t=>!!t&&typeof t=="object"&&t[ft]===Us,Yw=t=>!!t&&typeof t=="object"&&t[ft]===oa;function Vd(t){if(t&&typeof t=="object")switch(t[ft]){case aa:case oa:return!0}return!1}function Xw(t){if(t&&typeof t=="object")switch(t[ft]){case Js:case aa:case Us:case oa:return!0}return!1}var Qw=t=>(Fd(t)||Vd(t))&&!!t.anchor;Q.ALIAS=Js;Q.DOC=Bd;Q.MAP=aa;Q.NODE_TYPE=ft;Q.PAIR=Md;Q.SCALAR=Us;Q.SEQ=oa;Q.hasAnchor=Qw;Q.isAlias=Gw;Q.isCollection=Vd;Q.isDocument=Kw;Q.isMap=Jw;Q.isNode=Xw;Q.isPair=Uw;Q.isScalar=Fd;Q.isSeq=Yw});var Ci=N(Ys=>{"use strict";var z=A(),he=Symbol("break visit"),qd=Symbol("skip children"),Qe=Symbol("remove node");function sa(t,e){let r=Wd(e);z.isDocument(t)?jr(null,t.contents,r,Object.freeze([t]))===Qe&&(t.contents=null):jr(null,t,r,Object.freeze([]))}sa.BREAK=he;sa.SKIP=qd;sa.REMOVE=Qe;function jr(t,e,r,i){let n=zd(t,e,r,i);if(z.isNode(n)||z.isPair(n))return Gd(t,i,n),jr(t,n,r,i);if(typeof n!="symbol"){if(z.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=jr(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Qe&&(e.items.splice(a,1),a-=1)}}}else if(z.isPair(e)){i=Object.freeze(i.concat(e));let a=jr("key",e.key,r,i);if(a===he)return he;a===Qe&&(e.key=null);let o=jr("value",e.value,r,i);if(o===he)return he;o===Qe&&(e.value=null)}}return n}async function ca(t,e){let r=Wd(e);z.isDocument(t)?await $r(null,t.contents,r,Object.freeze([t]))===Qe&&(t.contents=null):await $r(null,t,r,Object.freeze([]))}ca.BREAK=he;ca.SKIP=qd;ca.REMOVE=Qe;async function $r(t,e,r,i){let n=await zd(t,e,r,i);if(z.isNode(n)||z.isPair(n))return Gd(t,i,n),$r(t,n,r,i);if(typeof n!="symbol"){if(z.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=await $r(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Qe&&(e.items.splice(a,1),a-=1)}}}else if(z.isPair(e)){i=Object.freeze(i.concat(e));let a=await $r("key",e.key,r,i);if(a===he)return he;a===Qe&&(e.key=null);let o=await $r("value",e.value,r,i);if(o===he)return he;o===Qe&&(e.value=null)}}return n}function Wd(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function zd(t,e,r,i){if(typeof r=="function")return r(t,e,i);if(z.isMap(e))return r.Map?.(t,e,i);if(z.isSeq(e))return r.Seq?.(t,e,i);if(z.isPair(e))return r.Pair?.(t,e,i);if(z.isScalar(e))return r.Scalar?.(t,e,i);if(z.isAlias(e))return r.Alias?.(t,e,i)}function Gd(t,e,r){let i=e[e.length-1];if(z.isCollection(i))i.items[t]=r;else if(z.isPair(i))t==="key"?i.key=r:i.value=r;else if(z.isDocument(i))i.contents=r;else{let n=z.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ys.visit=sa;Ys.visitAsync=ca});var Xs=N(Jd=>{"use strict";var Kd=A(),Zw=Ci(),ey={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ty=t=>t.replace(/[!,[\]{}]/g,e=>ey[e]),Pi=class t{constructor(e,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,r)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,r){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;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 ${n}`,!0),!1}}tagName(e,r){if(e==="!")return"!";if(e[0]!=="!")return r(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=e.match(/^(.*!)([^!]*)$/s);n||r(`The ${e} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,i]of Object.entries(this.tags))if(e.startsWith(i))return r+ty(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(e&&i.length>0&&Kd.isNode(e.contents)){let a={};Zw.visit(e.contents,(o,s)=>{Kd.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!e||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
5
|
+
`)}};Pi.defaultYaml={explicit:!1,version:"1.2"};Pi.defaultTags={"!!":"tag:yaml.org,2002:"};Jd.Directives=Pi});var la=N(Ri=>{"use strict";var Ud=A(),ry=Ci();function iy(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(r)}return!0}function Yd(t){let e=new Set;return ry.visit(t,{Value(r,i){i.anchor&&e.add(i.anchor)}}),e}function Xd(t,e){for(let r=1;;++r){let i=`${t}${r}`;if(!e.has(i))return i}}function ny(t,e){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Yd(t));let o=Xd(e,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Ud.isScalar(o.node)||Ud.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:i}}Ri.anchorIsValid=iy;Ri.anchorNames=Yd;Ri.createNodeAnchors=ny;Ri.findNewAnchor=Xd});var Qs=N(Qd=>{"use strict";function _i(t,e,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=_i(t,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=_i(t,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=_i(t,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=_i(t,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return t.call(e,r,i)}Qd.applyReviver=_i});var It=N(ep=>{"use strict";var ay=A();function Zd(t,e,r){if(Array.isArray(t))return t.map((i,n)=>Zd(i,String(n),r));if(t&&typeof t.toJSON=="function"){if(!r||!ay.hasAnchor(t))return t.toJSON(e,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(t,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=t.toJSON(e,r);return r.onCreate&&r.onCreate(n),n}return typeof t=="bigint"&&!r?.keep?Number(t):t}ep.toJS=Zd});var ua=N(rp=>{"use strict";var oy=Qs(),tp=A(),sy=It(),Zs=class{constructor(e){Object.defineProperty(this,tp.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!tp.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=sy.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?oy.applyReviver(a,{"":s},"",s):s}};rp.NodeBase=Zs});var Ai=N(ip=>{"use strict";var cy=la(),ly=Ci(),Or=A(),uy=ua(),dy=It(),ec=class extends uy.NodeBase{constructor(e){super(Or.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],ly.visit(e,{Node:(a,o)=>{(Or.isAlias(o)||Or.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(e,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(dy.toJS(o,null,r),s=i.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=da(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,r,i){let n=`*${this.source}`;if(e){if(cy.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function da(t,e,r){if(Or.isAlias(e)){let i=e.resolve(t),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Or.isCollection(e)){let i=0;for(let n of e.items){let a=da(t,n,r);a>i&&(i=a)}return i}else if(Or.isPair(e)){let i=da(t,e.key,r),n=da(t,e.value,r);return Math.max(i,n)}return 1}ip.Alias=ec});var V=N(tc=>{"use strict";var py=A(),fy=ua(),hy=It(),my=t=>!t||typeof t!="function"&&typeof t!="object",Tt=class extends fy.NodeBase{constructor(e){super(py.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:hy.toJS(this.value,e,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";tc.Scalar=Tt;tc.isScalarValue=my});var Ii=N(ap=>{"use strict";var vy=Ai(),nr=A(),np=V(),gy="tag:yaml.org,2002:";function wy(t,e,r){if(e){let i=r.filter(a=>a.tag===e),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return r.find(i=>i.identify?.(t)&&!i.format)}function yy(t,e,r){if(nr.isDocument(t)&&(t=t.contents),nr.isNode(t))return t;if(nr.isPair(t)){let d=r.schema[nr.MAP].createNode?.(r.schema,null,r);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new vy.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=gy+e.slice(2));let l=wy(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new np.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[nr.MAP]:Symbol.iterator in Object(t)?o[nr.SEQ]:o[nr.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,t,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,t,r):new np.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}ap.createNode=yy});var fa=N(pa=>{"use strict";var by=Ii(),Ze=A(),Ny=ua();function rc(t,e,r){let i=r;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return by.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var op=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,ic=class extends Ny.NodeBase{constructor(e,r){super(e),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(e){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(i=>Ze.isNode(i)||Ze.isPair(i)?i.clone(e):i),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(op(e))this.add(r);else{let[i,...n]=e,a=this.get(i,!0);if(Ze.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,rc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(e){let[r,...i]=e;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ze.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(e,r){let[i,...n]=e,a=this.get(i,!0);return n.length===0?!r&&Ze.isScalar(a)?a.value:a:Ze.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!Ze.isPair(r))return!1;let i=r.value;return i==null||e&&Ze.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[r,...i]=e;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ze.isCollection(n)?n.hasIn(i):!1}setIn(e,r){let[i,...n]=e;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ze.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,rc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};pa.Collection=ic;pa.collectionFromPath=rc;pa.isEmptyPath=op});var Ti=N(ha=>{"use strict";var ky=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function nc(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Sy=(t,e,r)=>t.endsWith(`
|
|
6
|
+
`)?nc(r,e):r.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)r===
|
|
10
|
-
`&&
|
|
11
|
-
`&&E!==" "&&(
|
|
12
|
-
${
|
|
13
|
-
${
|
|
14
|
-
`);i=
|
|
15
|
-
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function
|
|
8
|
+
`+nc(r,e):(t.endsWith(" ")?"":" ")+r;ha.indentComment=nc;ha.lineComment=Sy;ha.stringifyComment=ky});var cp=N(ji=>{"use strict";var Ey="flow",ac="block",ma="quoted";function xy(t,e,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;n<a&&(a=0);let c=Math.max(1+a,1+n-e.length);if(t.length<=c)return t;let l=[],u={},d=n-e.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let p,f,m=!1,h=-1,v=-1,w=-1;r===ac&&(h=sp(t,h,e.length),h!==-1&&(d=h+c));for(let k;k=t[h+=1];){if(r===ma&&k==="\\"){switch(v=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(k===`
|
|
9
|
+
`)r===ac&&(h=sp(t,h,e.length)),d=h+e.length+c,p=void 0;else{if(k===" "&&f&&f!==" "&&f!==`
|
|
10
|
+
`&&f!==" "){let E=t[h+1];E&&E!==" "&&E!==`
|
|
11
|
+
`&&E!==" "&&(p=h)}if(h>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===ma){for(;f===" "||f===" ";)f=k,k=t[h+=1],m=!0;let E=h>w+1?h-2:v-1;if(u[E])return t;l.push(E),u[E]=!0,d=E+c,p=void 0}else m=!0}f=k}if(m&&s&&s(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let k=0;k<l.length;++k){let E=l[k],x=l[k+1]||t.length;E===0?y=`
|
|
12
|
+
${e}${t.slice(0,x)}`:(r===ma&&u[E]&&(y+=`${t[E]}\\`),y+=`
|
|
13
|
+
${e}${t.slice(E+1,x)}`)}return y}function sp(t,e,r){let i=e,n=e+1,a=t[n];for(;a===" "||a===" ";)if(e<n+r)a=t[++e];else{do a=t[++e];while(a&&a!==`
|
|
14
|
+
`);i=e,n=e+1,a=t[n]}return i}ji.FOLD_BLOCK=ac;ji.FOLD_FLOW=Ey;ji.FOLD_QUOTED=ma;ji.foldFlowLines=xy});var Oi=N(lp=>{"use strict";var De=V(),jt=cp(),ga=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),wa=t=>/^(%|---|\.\.\.)/m.test(t);function Cy(t,e,r){if(!e||e<0)return!1;let i=e-r,n=t.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(t[a]===`
|
|
15
|
+
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function $i(t,e){let r=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(wa(t)?" ":""),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(i||r[c+2]==='"'||r.length<n)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,i?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(
|
|
20
|
-
${r}`)+"'";return
|
|
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,i?o:jt.foldFlowLines(o,a,jt.FOLD_QUOTED,ga(e,!1))}function oc(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(t))return $i(t,e);let r=e.indent||(wa(t)?" ":""),i="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return e.implicitKey?i:jt.foldFlowLines(i,r,jt.FOLD_FLOW,ga(e,!1))}function Hr(t,e){let{singleQuote:r}=e.options,i;if(r===!1)i=$i;else{let n=t.includes('"'),a=t.includes("'");n&&!a?i=oc:a&&!n?i=$i:i=r?oc:$i}return i(t,e)}var sc;try{sc=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{sc=/\n+(?!\n|$)/g}function va({comment:t,type:e,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Hr(r,i);let l=i.indent||(i.forceBlockIndent||wa(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===De.Scalar.BLOCK_FOLDED?!1:e===De.Scalar.BLOCK_LITERAL?!0:!Cy(r,c,l.length);if(!r)return u?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let d,
|
|
26
|
-
`&&x!==" "&&x!==" ")break}let
|
|
27
|
-
`);m===-1?d="-":r===
|
|
28
|
-
`&&(
|
|
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(
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,
|
|
31
|
-
${l}${
|
|
32
|
-
${l}${y}${r}${
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let
|
|
37
|
-
${
|
|
38
|
-
${s}:`):(v=`${v}:`,
|
|
39
|
-
`:"",y){let
|
|
40
|
-
${
|
|
25
|
+
`;let d,p;for(p=r.length;p>0;--p){let x=r[p-1];if(x!==`
|
|
26
|
+
`&&x!==" "&&x!==" ")break}let f=r.substring(p),m=f.indexOf(`
|
|
27
|
+
`);m===-1?d="-":r===f||m!==f.length-1?(d="+",a&&a()):d="",f&&(r=r.slice(0,-f.length),f[f.length-1]===`
|
|
28
|
+
`&&(f=f.slice(0,-1)),f=f.replace(sc,`$&${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(t&&(E+=" "+s(t.replace(/ ?[\r\n]+/g," ")),n&&n()),!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,_=ga(i,!0);o!=="folded"&&e!==De.Scalar.BLOCK_FOLDED&&(_.onOverflow=()=>{g=!0});let b=jt.foldFlowLines(`${y}${x}${f}`,l,jt.FOLD_BLOCK,_);if(!g)return`>${E}
|
|
31
|
+
${l}${b}`}return r=r.replace(/\n+/g,`$&${l}`),`|${E}
|
|
32
|
+
${l}${y}${r}${f}`}function Py(t,e,r,i){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=e;if(s&&a.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return Hr(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?Hr(a,e):va(t,e,r,i);if(!s&&!u&&n!==De.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return va(t,e,r,i);if(wa(a)){if(c==="")return e.forceBlockIndent=!0,va(t,e,r,i);if(s&&c===l)return Hr(a,e)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:f,tags:m}=e.doc.schema;if(m.some(p)||f?.some(p))return Hr(a,e)}return s?d:jt.foldFlowLines(d,c,jt.FOLD_FLOW,ga(e,!1))}function Ry(t,e,r,i){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;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 n||a?Hr(o.value,e):va(o,e,r,i);case De.Scalar.QUOTE_DOUBLE:return $i(o.value,e);case De.Scalar.QUOTE_SINGLE:return oc(o.value,e);case De.Scalar.PLAIN:return Py(o,e,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,p=n&&u||d;if(l=c(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}lp.stringifyString=Ry});var Hi=N(cc=>{"use strict";var _y=la(),$t=A(),Ay=Ti(),Iy=Oi();function Ty(t,e){let r=Object.assign({blockQuote:!0,commentString:Ay.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function jy(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let r,i;if($t.isScalar(e)){i=e.value;let n=t.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===e.format)??n.find(a=>!a.format)}else i=e,r=t.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function $y(t,e,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=($t.isScalar(t)||$t.isCollection(t))&&t.anchor;a&&_y.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Oy(t,e,r,i){if($t.isPair(t))return t.toString(e,r,i);if($t.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=$t.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=jy(e.doc.schema.tags,a));let o=$y(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,r,i):$t.isScalar(a)?Iy.stringifyString(a,e,r,i):a.toString(e,r,i);return o?$t.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${e.indent}${s}`:s}cc.createStringifyContext=Ty;cc.stringify=Oy});var fp=N(pp=>{"use strict";var ht=A(),up=V(),dp=Hi(),Di=Ti();function Hy({key:t,value:e},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,p=ht.isNode(t)&&t.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(ht.isCollection(t)||!ht.isNode(t)&&typeof t=="object"){let _="With simple keys, collection cannot be used as a key value";throw new Error(_)}}let f=!d&&(!t||p&&e==null&&!r.inFlow||ht.isCollection(t)||(ht.isScalar(t)?t.type===up.Scalar.BLOCK_FOLDED||t.type===up.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(d||!a),indent:s+c});let m=!1,h=!1,v=dp.stringify(t,r,()=>m=!0,()=>h=!0);if(!f&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(r.inFlow){if(a||e==null)return m&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!d||e==null&&f)return v=`? ${v}`,p&&!m?v+=Di.lineComment(v,r.indent,l(p)):h&&n&&n(),v;m&&(p=null),f?(p&&(v+=Di.lineComment(v,r.indent,l(p))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,p&&(v+=Di.lineComment(v,r.indent,l(p))));let w,y,k;ht.isNode(e)?(w=!!e.spaceBefore,y=e.commentBefore,k=e.comment):(w=!1,y=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!f&&!p&&ht.isScalar(e)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!f&&ht.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let E=!1,x=dp.stringify(e,r,()=>E=!0,()=>h=!0),g=" ";if(p||w||y){if(g=w?`
|
|
39
|
+
`:"",y){let _=l(y);g+=`
|
|
40
|
+
${Di.indentComment(_,r.indent)}`}x===""&&!r.inFlow?g===`
|
|
41
41
|
`&&k&&(g=`
|
|
42
42
|
|
|
43
43
|
`):g+=`
|
|
44
|
-
${r.indent}`}else if(!
|
|
45
|
-
`),
|
|
44
|
+
${r.indent}`}else if(!f&&ht.isCollection(e)){let _=x[0],b=x.indexOf(`
|
|
45
|
+
`),T=b!==-1,ne=r.inFlow??e.flow??e.items.length===0;if(T||!ne){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&&i&&i():k&&!E?v+=
|
|
47
|
+
`)&&(g="");return v+=g+x,r.inFlow?E&&i&&i():k&&!E?v+=Di.lineComment(v,r.indent,l(k)):h&&n&&n(),v}pp.stringifyPair=Hy});var uc=N(lc=>{"use strict";var hp=na("process");function Dy(t,...e){t==="debug"&&console.log(...e)}function Ly(t,e){(t==="debug"||t==="warn")&&(typeof hp.emitWarning=="function"?hp.emitWarning(e):console.warn(e))}lc.debug=Dy;lc.warn=Ly});var Sa=N(ka=>{"use strict";var Na=A(),mp=V(),ya="<<",ba={identify:t=>t===ya||typeof t=="symbol"&&t.description===ya,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new mp.Scalar(Symbol(ya)),{addToJSMap:vp}),stringify:()=>ya},By=(t,e)=>(ba.identify(e)||Na.isScalar(e)&&(!e.type||e.type===mp.Scalar.PLAIN)&&ba.identify(e.value))&&t?.doc.schema.tags.some(r=>r.tag===ba.tag&&r.default);function vp(t,e,r){let i=gp(t,r);if(Na.isSeq(i))for(let n of i.items)dc(t,e,n);else if(Array.isArray(i))for(let n of i)dc(t,e,n);else dc(t,e,i)}function dc(t,e,r){let i=gp(t,r);if(!Na.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,t,Map);for(let[a,o]of n)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function gp(t,e){return t&&Na.isAlias(e)?e.resolve(t.doc,t):e}ka.addMergeToJSMap=vp;ka.isMergeKey=By;ka.merge=ba});var fc=N(bp=>{"use strict";var My=uc(),wp=Sa(),Fy=Hi(),yp=A(),pc=It();function Vy(t,e,{key:r,value:i}){if(yp.isNode(r)&&r.addToJSMap)r.addToJSMap(t,e,i);else if(wp.isMergeKey(t,r))wp.addMergeToJSMap(t,e,i);else{let n=pc.toJS(r,"",t);if(e instanceof Map)e.set(n,pc.toJS(i,n,t));else if(e instanceof Set)e.add(n);else{let a=qy(r,n,t),o=pc.toJS(i,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function qy(t,e,r){if(e===null)return"";if(typeof e!="object")return String(e);if(yp.isNode(t)&&r?.doc){let i=Fy.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=t.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),My.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 n}return JSON.stringify(e)}bp.addPairToJSMap=Vy});var Ot=N(hc=>{"use strict";var Np=Ii(),Wy=fp(),zy=fc(),Ea=A();function Gy(t,e,r){let i=Np.createNode(t,void 0,r),n=Np.createNode(e,void 0,r);return new xa(i,n)}var xa=class t{constructor(e,r=null){Object.defineProperty(this,Ea.NODE_TYPE,{value:Ea.PAIR}),this.key=e,this.value=r}clone(e){let{key:r,value:i}=this;return Ea.isNode(r)&&(r=r.clone(e)),Ea.isNode(i)&&(i=i.clone(e)),new t(r,i)}toJSON(e,r){let i=r?.mapAsMap?new Map:{};return zy.addPairToJSMap(r,i,this)}toString(e,r,i){return e?.doc?Wy.stringifyPair(this,e,r,i):JSON.stringify(this)}};hc.Pair=xa;hc.createPair=Gy});var mc=N(Sp=>{"use strict";var ar=A(),kp=Hi(),Ca=Ti();function Ky(t,e,r){return(e.inFlow??t.flow?Uy:Jy)(t,e,r)}function Jy({comment:t,items:e},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,p=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(ar.isNode(h))!d&&h.spaceBefore&&p.push(""),Pa(r,p,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&&p.push(""),Pa(r,p,y.commentBefore,d))}d=!1;let w=kp.stringify(h,u,()=>v=null,()=>d=!0);v&&(w+=Ca.lineComment(w,a,l(v))),d&&v&&(d=!1),p.push(i+w)}let f;if(p.length===0)f=n.start+n.end;else{f=p[0];for(let m=1;m<p.length;++m){let h=p[m];f+=h?`
|
|
48
48
|
${c}${h}`:`
|
|
49
|
-
`}}return
|
|
50
|
-
`+
|
|
51
|
-
`)),m<
|
|
49
|
+
`}}return t?(f+=`
|
|
50
|
+
`+Ca.indentComment(l(t),c),s&&s()):d&&o&&o(),f}function Uy({items:t},e,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;i+=a;let c=Object.assign({},e,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(ar.isNode(h))h.spaceBefore&&d.push(""),Pa(e,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(""),Pa(e,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=kp.stringify(h,c,()=>v=null);l||(l=d.length>u||w.includes(`
|
|
51
|
+
`)),m<t.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=d.reduce((y,k)=>y+k.length+2,2)+(w.length+2)>e.options.lineWidth)),l&&(w+=",")),v&&(w+=Ca.lineComment(w,i,s(v))),d.push(w),u=d.length}let{start:p,end:f}=r;if(d.length===0)return p+f;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=p;for(let h of d)m+=h?`
|
|
52
52
|
${a}${n}${h}`:`
|
|
53
53
|
`;return`${m}
|
|
54
|
-
${n}${
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${n}${f}`}else return`${p}${o}${d.join(" ")}${o}${f}`}function Pa({indent:t,options:{commentString:e}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Ca.indentComment(e(i),t);r.push(a.trimStart())}}Sp.stringifyCollection=Ky});var Dt=N(gc=>{"use strict";var Yy=mc(),Xy=fc(),Qy=fa(),Ht=A(),Ra=Ot(),Zy=V();function Li(t,e){let r=Ht.isScalar(e)?e.value:e;for(let i of t)if(Ht.isPair(i)&&(i.key===e||i.key===r||Ht.isScalar(i.key)&&i.key.value===r))return i}var vc=class extends Qy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ht.MAP,e),this.items=[]}static from(e,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(e),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||n)&&o.items.push(Ra.createPair(c,l,i))};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 e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,r){let i;Ht.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Ra.Pair(e,e?.value):i=new Ra.Pair(e.key,e.value);let n=Li(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Ht.isScalar(n.value)&&Zy.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(e){let r=Li(this.items,e);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(e,r){let n=Li(this.items,e)?.value;return(!r&&Ht.isScalar(n)?n.value:n)??void 0}has(e){return!!Li(this.items,e)}set(e,r){this.add(new Ra.Pair(e,r),!0)}toJSON(e,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)Xy.addPairToJSMap(r,n,a);return n}toString(e,r,i){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Ht.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Yy.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:r})}};gc.YAMLMap=vc;gc.findPair=Li});var Dr=N(xp=>{"use strict";var eb=A(),Ep=Dt(),tb={collection:"map",default:!0,nodeClass:Ep.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return eb.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,r)=>Ep.YAMLMap.from(t,e,r)};xp.map=tb});var Lt=N(Cp=>{"use strict";var rb=Ii(),ib=mc(),nb=fa(),Aa=A(),ab=V(),ob=It(),wc=class extends nb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Aa.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let r=_a(e);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(e,r){let i=_a(e);if(typeof i!="number")return;let n=this.items[i];return!r&&Aa.isScalar(n)?n.value:n}has(e){let r=_a(e);return typeof r=="number"&&r<this.items.length}set(e,r){let i=_a(e);if(typeof i!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[i];Aa.isScalar(n)&&ab.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(e,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(ob.toJS(a,String(n++),r));return i}toString(e,r,i){return e?ib.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(e,r,i){let{replacer:n}=i,a=new this(e);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(rb.createNode(s,void 0,i))}}return a}};function _a(t){let e=Aa.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Cp.YAMLSeq=wc});var Lr=N(Rp=>{"use strict";var sb=A(),Pp=Lt(),cb={collection:"seq",default:!0,nodeClass:Pp.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return sb.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,r)=>Pp.YAMLSeq.from(t,e,r)};Rp.seq=cb});var Bi=N(_p=>{"use strict";var lb=Oi(),ub={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,r,i){return e=Object.assign({actualString:!0},e),lb.stringifyString(t,e,r,i)}};_p.string=ub});var Ia=N(Tp=>{"use strict";var Ap=V(),Ip={identify:t=>t==null,createNode:()=>new Ap.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ap.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Ip.test.test(t)?t:e.options.nullStr};Tp.nullTag=Ip});var yc=N($p=>{"use strict";var db=V(),jp={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new db.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},r){if(t&&jp.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?r.options.trueStr:r.options.falseStr}};$p.boolTag=jp});var Br=N(Op=>{"use strict";function pb({format:t,minFractionDigits:e,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!t&&e&&(!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=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Op.stringifyNumber=pb});var Nc=N(Ta=>{"use strict";var fb=V(),bc=Br(),hb={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:bc.stringifyNumber},mb={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():bc.stringifyNumber(t)}},vb={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new fb.Scalar(parseFloat(t)),r=t.indexOf(".");return r!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-r-1),e},stringify:bc.stringifyNumber};Ta.float=vb;Ta.floatExp=mb;Ta.floatNaN=hb});var Sc=N($a=>{"use strict";var Hp=Br(),ja=t=>typeof t=="bigint"||Number.isInteger(t),kc=(t,e,r,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),r);function Dp(t,e,r){let{value:i}=t;return ja(i)&&i>=0?r+i.toString(e):Hp.stringifyNumber(t)}var gb={identify:t=>ja(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,r)=>kc(t,2,8,r),stringify:t=>Dp(t,8,"0o")},wb={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,r)=>kc(t,0,10,r),stringify:Hp.stringifyNumber},yb={identify:t=>ja(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,r)=>kc(t,2,16,r),stringify:t=>Dp(t,16,"0x")};$a.int=wb;$a.intHex=yb;$a.intOct=gb});var Bp=N(Lp=>{"use strict";var bb=Dr(),Nb=Ia(),kb=Lr(),Sb=Bi(),Eb=yc(),Ec=Nc(),xc=Sc(),xb=[bb.map,kb.seq,Sb.string,Nb.nullTag,Eb.boolTag,xc.intOct,xc.int,xc.intHex,Ec.floatNaN,Ec.floatExp,Ec.float];Lp.schema=xb});var Vp=N(Fp=>{"use strict";var Cb=V(),Pb=Dr(),Rb=Lr();function Mp(t){return typeof t=="bigint"||Number.isInteger(t)}var Oa=({value:t})=>JSON.stringify(t),_b=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Oa},{identify:t=>t==null,createNode:()=>new Cb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Oa},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Oa},{identify:Mp,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:r})=>r?BigInt(t):parseInt(t,10),stringify:({value:t})=>Mp(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Oa}],Ab={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Ib=[Pb.map,Rb.seq].concat(_b,Ab);Fp.schema=Ib});var Pc=N(qp=>{"use strict";var Mi=na("buffer"),Cc=V(),Tb=Oi(),jb={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Mi.Buffer=="function")return Mi.Buffer.from(t,"base64");if(typeof atob=="function"){let r=atob(t.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof Mi.Buffer=="function")s=o instanceof Mi.Buffer?o.toString("base64"):Mi.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Cc.Scalar.BLOCK_LITERAL),e!==Cc.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,p=0;d<l;++d,p+=c)u[d]=s.substr(p,c);s=u.join(e===Cc.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return Tb.stringifyString({comment:t,type:e,value:s},i,n,a)}};qp.binary=jb});var La=N(Da=>{"use strict";var Ha=A(),Rc=Ot(),$b=V(),Ob=Lt();function Wp(t,e){if(Ha.isSeq(t))for(let r=0;r<t.items.length;++r){let i=t.items[r];if(!Ha.isPair(i)){if(Ha.isMap(i)){i.items.length>1&&e("Each pair must have its own sequence indicator");let n=i.items[0]||new Rc.Pair(new $b.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
|
|
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(
|
|
57
|
+
${a.comment}`:i.comment}i=n}t.items[r]=Ha.isPair(i)?i:new Rc.Pair(i)}}else e("Expected a sequence for this tag");return t}function zp(t,e,r){let{replacer:i}=r,n=new Ob.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Rc.createPair(s,c,r))}return n}var Hb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Wp,createNode:zp};Da.createPairs=zp;Da.pairs=Hb;Da.resolvePairs=Wp});var Ic=N(Ac=>{"use strict";var Gp=A(),_c=It(),Fi=Dt(),Db=Lt(),Kp=La(),or=class t extends Db.YAMLSeq{constructor(){super(),this.add=Fi.YAMLMap.prototype.add.bind(this),this.delete=Fi.YAMLMap.prototype.delete.bind(this),this.get=Fi.YAMLMap.prototype.get.bind(this),this.has=Fi.YAMLMap.prototype.has.bind(this),this.set=Fi.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Gp.isPair(n)?(a=_c.toJS(n.key,"",r),o=_c.toJS(n.value,a,r)):a=_c.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(e,r,i){let n=Kp.createPairs(e,r,i),a=new this;return a.items=n.items,a}};or.tag="tag:yaml.org,2002:omap";var Lb={collection:"seq",identify:t=>t instanceof Map,nodeClass:or,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=Kp.resolvePairs(t,e),i=[];for(let{key:n}of r.items)Gp.isScalar(n)&&(i.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new or,r)},createNode:(t,e,r)=>or.from(t,e,r)};Ac.YAMLOMap=or;Ac.omap=Lb});var Qp=N(Tc=>{"use strict";var Jp=V();function Up({value:t,source:e},r){return e&&(t?Yp:Xp).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var Yp={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Jp.Scalar(!0),stringify:Up},Xp={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Jp.Scalar(!1),stringify:Up};Tc.falseTag=Xp;Tc.trueTag=Yp});var Zp=N(Ba=>{"use strict";var Bb=V(),jc=Br(),Mb={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:jc.stringifyNumber},Fb={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():jc.stringifyNumber(t)}},Vb={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new Bb.Scalar(parseFloat(t.replace(/_/g,""))),r=t.indexOf(".");if(r!==-1){let i=t.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:jc.stringifyNumber};Ba.float=Vb;Ba.floatExp=Fb;Ba.floatNaN=Mb});var tf=N(qi=>{"use strict";var ef=Br(),Vi=t=>typeof t=="bigint"||Number.isInteger(t);function Ma(t,e,r,{intAsBigInt:i}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(r){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,r);return n==="-"?-1*a:a}function $c(t,e,r){let{value:i}=t;if(Vi(i)){let n=i.toString(e);return i<0?"-"+r+n.substr(1):r+n}return ef.stringifyNumber(t)}var qb={identify:Vi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>Ma(t,2,2,r),stringify:t=>$c(t,2,"0b")},Wb={identify:Vi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>Ma(t,1,8,r),stringify:t=>$c(t,8,"0")},zb={identify:Vi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>Ma(t,0,10,r),stringify:ef.stringifyNumber},Gb={identify:Vi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>Ma(t,2,16,r),stringify:t=>$c(t,16,"0x")};qi.int=zb;qi.intBin=qb;qi.intHex=Gb;qi.intOct=Wb});var Hc=N(Oc=>{"use strict";var qa=A(),Fa=Ot(),Va=Dt(),sr=class t extends Va.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;qa.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new Fa.Pair(e.key,null):r=new Fa.Pair(e,null),Va.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let i=Va.findPair(this.items,e);return!r&&qa.isPair(i)?qa.isScalar(i.key)?i.key.value:i.key:i}set(e,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Va.findPair(this.items,e);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Fa.Pair(e))}toJSON(e,r){return super.toJSON(e,r,Set)}toString(e,r,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(e,r,i){let{replacer:n}=i,a=new this(e);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Fa.createPair(o,null,i));return a}};sr.tag="tag:yaml.org,2002:set";var Kb={collection:"map",identify:t=>t instanceof Set,nodeClass:sr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>sr.from(t,e,r),resolve(t,e){if(qa.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new sr,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Oc.YAMLSet=sr;Oc.set=Kb});var Lc=N(Wa=>{"use strict";var Jb=Br();function Dc(t,e){let r=t[0],i=r==="-"||r==="+"?t.substring(1):t,n=o=>e?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(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Jb.stringifyNumber(t);let i="";e<0&&(i="-",e*=r(-1));let n=r(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ub={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:r})=>Dc(t,r),stringify:rf},Yb={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Dc(t,!1),stringify:rf},nf={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(nf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let d=Dc(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Wa.floatTime=Yb;Wa.intTime=Ub;Wa.timestamp=nf});var sf=N(of=>{"use strict";var Xb=Dr(),Qb=Ia(),Zb=Lr(),eN=Bi(),tN=Pc(),af=Qp(),Bc=Zp(),za=tf(),rN=Sa(),iN=Ic(),nN=La(),aN=Hc(),Mc=Lc(),oN=[Xb.map,Zb.seq,eN.string,Qb.nullTag,af.trueTag,af.falseTag,za.intBin,za.intOct,za.int,za.intHex,Bc.floatNaN,Bc.floatExp,Bc.float,tN.binary,rN.merge,iN.omap,nN.pairs,aN.set,Mc.intTime,Mc.floatTime,Mc.timestamp];of.schema=oN});var gf=N(qc=>{"use strict";var df=Dr(),sN=Ia(),pf=Lr(),cN=Bi(),lN=yc(),Fc=Nc(),Vc=Sc(),uN=Bp(),dN=Vp(),ff=Pc(),Wi=Sa(),hf=Ic(),mf=La(),cf=sf(),vf=Hc(),Ga=Lc(),lf=new Map([["core",uN.schema],["failsafe",[df.map,pf.seq,cN.string]],["json",dN.schema],["yaml11",cf.schema],["yaml-1.1",cf.schema]]),uf={binary:ff.binary,bool:lN.boolTag,float:Fc.float,floatExp:Fc.floatExp,floatNaN:Fc.floatNaN,floatTime:Ga.floatTime,int:Vc.int,intHex:Vc.intHex,intOct:Vc.intOct,intTime:Ga.intTime,map:df.map,merge:Wi.merge,null:sN.nullTag,omap:hf.omap,pairs:mf.pairs,seq:pf.seq,set:vf.set,timestamp:Ga.timestamp},pN={"tag:yaml.org,2002:binary":ff.binary,"tag:yaml.org,2002:merge":Wi.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":Ga.timestamp};function fN(t,e,r){let i=lf.get(e);if(i&&!t)return r&&!i.includes(Wi.merge)?i.concat(Wi.merge):i.slice();let n=i;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(lf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return r&&(n=n.concat(Wi.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},[])}qc.coreKnownTags=pN;qc.getTags=fN});var Gc=N(wf=>{"use strict";var Wc=A(),hN=Dr(),mN=Lr(),vN=Bi(),Ka=gf(),gN=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,zc=class t{constructor({compat:e,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Ka.getTags(e,"compat"):e?Ka.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ka.coreKnownTags:{},this.tags=Ka.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Wc.MAP,{value:hN.map}),Object.defineProperty(this,Wc.SCALAR,{value:vN.string}),Object.defineProperty(this,Wc.SEQ,{value:mN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?gN:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};wf.Schema=zc});var bf=N(yf=>{"use strict";var wN=A(),Kc=Hi(),zi=Ti();function yN(t,e){let r=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(r.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&r.push("---");let n=Kc.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){r.length!==1&&r.unshift("");let c=a(t.commentBefore);r.unshift(zi.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(wN.isNode(t.contents)){if(t.contents.spaceBefore&&i&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(zi.indentComment(u,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Kc.stringify(t.contents,n,()=>s=null,c);s&&(l+=zi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Kc.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(zi.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(zi.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}yf.stringifyDocument=
|
|
60
|
+
`}yf.stringifyDocument=yN});var Gi=N(Nf=>{"use strict";var bN=Ai(),Mr=fa(),Re=A(),NN=Ot(),kN=It(),SN=Gc(),EN=bf(),Jc=la(),xN=Qs(),CN=Ii(),Uc=Xs(),Yc=class t{constructor(e,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Re.NODE_TYPE,{value:Re.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=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"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Uc.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,n,i)}clone(){let e=Object.create(t.prototype,{[Re.NODE_TYPE]:{value:Re.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Re.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Fr(this.contents)&&this.contents.add(e)}addIn(e,r){Fr(this.contents)&&this.contents.addIn(e,r)}createAlias(e,r){if(!e.anchor){let i=Jc.anchorNames(this);e.anchor=!r||i.has(r)?Jc.findNewAnchor(r||"a",i):r}return new bN.Alias(e.anchor)}createNode(e,r,i){let n;if(typeof r=="function")e=r.call({"":e},"",e),n=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)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:f}=Jc.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},h=CN.createNode(e,u,m);return s&&Re.isCollection(h)&&(h.flow=!0),p(),h}createPair(e,r,i={}){let n=this.createNode(e,null,i),a=this.createNode(r,null,i);return new NN.Pair(n,a)}delete(e){return Fr(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Mr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Fr(this.contents)?this.contents.deleteIn(e):!1}get(e,r){return Re.isCollection(this.contents)?this.contents.get(e,r):void 0}getIn(e,r){return Mr.isEmptyPath(e)?!r&&Re.isScalar(this.contents)?this.contents.value:this.contents:Re.isCollection(this.contents)?this.contents.getIn(e,r):void 0}has(e){return Re.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Mr.isEmptyPath(e)?this.contents!==void 0:Re.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,r){this.contents==null?this.contents=Mr.collectionFromPath(this.schema,[e],r):Fr(this.contents)&&this.contents.set(e,r)}setIn(e,r){Mr.isEmptyPath(e)?this.contents=r:this.contents==null?this.contents=Mr.collectionFromPath(this.schema,Array.from(e),r):Fr(this.contents)&&this.contents.setIn(e,r)}setSchema(e,r={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Uc.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Uc.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new SN.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=kN.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"?xN.applyReviver(o,{"":c},"",c):c}toJSON(e,r){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:r})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let r=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return EN.stringifyDocument(this,e)}};function Fr(t){if(Re.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Nf.Document=Yc});var Ui=N(Ji=>{"use strict";var Ki=class extends Error{constructor(e,r,i,n){super(),this.name=e,this.code=i,this.message=n,this.pos=r}},Xc=class extends Ki{constructor(e,r,i){super("YAMLParseError",e,r,i)}},Qc=class extends Ki{constructor(e,r,i){super("YAMLWarning",e,r,i)}},PN=(t,e)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>e.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=t.substring(e.lineStarts[i-1],e.lineStarts[i]).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)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(
|
|
67
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
68
|
-
`+k.comment:y.comment=k.comment);let E=new Pf.Pair(y);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}If.resolveBlockMap=
|
|
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=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}Lf.resolveFlowCollection=
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return
|
|
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 ${n.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(y?2:1),"BAD_INDENT",E),v=""}a===
|
|
75
|
-
`):v.length>c||w[0]===" "?(
|
|
76
|
-
`:!p
|
|
77
|
-
`&&(
|
|
65
|
+
`}};Ji.YAMLError=Ki;Ji.YAMLParseError=Xc;Ji.YAMLWarning=Qc;Ji.prettifyError=PN});var Yi=N(kf=>{"use strict";function RN(t,{flow:e,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",p="",f=!1,m=!1,h=null,v=null,w=null,y=null,k=null,E=null,x=null;for(let b of t)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":!e&&(r!=="doc-start"||i?.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+=p+T:d=T,p="",l=!1;break}case"newline":l?d?d+=b.source:(!E||r!=="seq-item-ind")&&(c=!0):p+=b.source,l=!0,f=!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 ${e??"collection"}`),E=b,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(e){k&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,u=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,u=!1}let g=t[t.length-1],_=g?g.offset+g.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:E,spaceBefore:c,comment:d,hasNewline:f,anchor:v,tag:w,newlineAfterProp:y,end:_,start:x??_}}kf.resolveProps=RN});var Ja=N(Sf=>{"use strict";function Zc(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
|
|
66
|
+
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let r of e.start)if(r.type==="newline")return!0;if(e.sep){for(let r of e.sep)if(r.type==="newline")return!0}if(Zc(e.key)||Zc(e.value))return!0}return!1;default:return!0}}Sf.containsNewline=Zc});var el=N(Ef=>{"use strict";var _N=Ja();function AN(t,e,r){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&_N.containsNewline(e)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ef.flowIndentCheck=AN});var tl=N(Cf=>{"use strict";var xf=A();function IN(t,e,r){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||xf.isScalar(a)&&xf.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,r))}Cf.mapIncludes=IN});var Tf=N(If=>{"use strict";var Pf=Ot(),TN=Dt(),Rf=Yi(),jN=Ja(),_f=el(),$N=tl(),Af="All mapping items must start at the same column";function ON({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??TN.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:p,sep:f,value:m}=u,h=Rf.resolveProps(d,{indicator:"explicit-key-ind",next:p??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(p&&(p.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==i.indent&&n(c,"BAD_INDENT",Af)),!h.anchor&&!h.tag&&!f){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||jN.containsNewline(p))&&n(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",Af);r.atKey=!0;let w=h.end,y=p?t(r,p,h,n):e(r,w,d,null,h,n);r.schema.compat&&_f.flowIndentCheck(i.indent,p,n),r.atKey=!1,$N.mapIncludes(r,s.items,y)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let k=Rf.resolveProps(f??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:n,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=m?t(r,m,k,n):e(r,c,f,null,k,n);r.schema.compat&&_f.flowIndentCheck(i.indent,m,n),c=E.range[2];let x=new Pf.Pair(y,E);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(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 Pf.Pair(y);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}If.resolveBlockMap=ON});var $f=N(jf=>{"use strict";var HN=Lt(),DN=Yi(),LN=el();function BN({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??HN.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let p=DN.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?n(p.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(s.comment=p.comment);continue}let f=d?t(r,d,p,n):e(r,p.end,u,null,p,n);r.schema.compat&&LN.flowIndentCheck(i.indent,d,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}jf.resolveBlockSeq=BN});var Vr=N(Of=>{"use strict";function MN(t,e,r,i){let n="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}Of.resolveEnd=MN});var Bf=N(Lf=>{"use strict";var FN=A(),VN=Ot(),Hf=Dt(),qN=Lt(),WN=Vr(),Df=Yi(),zN=Ja(),GN=tl(),rl="Block collections are not allowed within flow collections",il=t=>t&&(t.type==="block-map"||t.type==="block-seq");function KN({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Hf.YAMLMap:qN.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let w=i.items[v],{start:y,key:k,sep:E,value:x}=w,g=Df.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:k??E?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!E&&!x){v===0&&g.comma?n(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(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&&zN.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)g.comma&&n(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(g.comma||n(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];FN.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?t(r,x,g,n):e(r,g.end,E,null,g,n);l.items.push(_),d=_.range[2],il(x)&&n(_.range,"BLOCK_IN_FLOW",rl)}else{r.atKey=!0;let _=g.end,b=k?t(r,k,g,n):e(r,_,y,null,g,n);il(k)&&n(b.range,"BLOCK_IN_FLOW",rl),r.atKey=!1;let T=Df.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:x,offset:b.range[2],onError:n,parentIndent:i.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"){n(W,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<T.found.offset-1024&&n(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]===":"?n(x,"MISSING_CHAR",`Missing space after : in ${s}`):n(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ne=x?t(r,x,T,n):T.found?e(r,T.end,E,null,T,n):null;ne?il(x)&&n(ne.range,"BLOCK_IN_FLOW",rl):T.comment&&(b.comment?b.comment+=`
|
|
71
|
+
`+T.comment:b.comment=T.comment);let Tr=new VN.Pair(b,ne);if(r.options.keepSourceTokens&&(Tr.srcToken=w),o){let W=l;GN.mapIncludes(r,W.items,b)&&n(_,"DUPLICATE_KEY","Map keys must be unique"),W.items.push(Tr)}else{let W=new Hf.YAMLMap(r.schema);W.flow=!0,W.items.push(Tr);let Ld=(ne??b).range;W.range=[b.range[0],Ld[1],Ld[2]],l.items.push(W)}d=ne?ne.range[2]:T.end}}let p=o?"}":"]",[f,...m]=i.end,h=d;if(f?.source===p)h=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),w=u?`${v} must end with a ${p}`:`${v} in block collection must be sufficiently indented and end with a ${p}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",w),f&&f.source.length!==1&&m.unshift(f)}if(m.length>0){let v=WN.resolveEnd(m,h,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}Lf.resolveFlowCollection=KN});var Ff=N(Mf=>{"use strict";var JN=A(),UN=V(),YN=Dt(),XN=Lt(),QN=Tf(),ZN=$f(),ek=Bf();function nl(t,e,r,i,n,a){let o=r.type==="block-map"?QN.resolveBlockMap(t,e,r,i,a):r.type==="block-seq"?ZN.resolveBlockSeq(t,e,r,i,a):ek.resolveFlowCollection(t,e,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function tk(t,e,r,i,n){let a=i.tag,o=a?e.directives.tagName(a.source,p=>n(a,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:f}=i,m=p&&a?p.offset>a.offset?p:a:p??a;m&&(!f||f.offset<m.offset)&&n(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===YN.YAMLMap.tagName&&s==="map"||o===XN.YAMLSeq.tagName&&s==="seq")return nl(t,e,r,n,o);let c=e.schema.tags.find(p=>p.tag===o&&p.collection===s);if(!c){let p=e.schema.knownTags[o];if(p?.collection===s)e.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?n(a,"BAD_COLLECTION_TYPE",`${p.tag} used for ${s} collection, but expects ${p.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),nl(t,e,r,n,o)}let l=nl(t,e,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),e.options)??l,d=JN.isNode(u)?u:new UN.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Mf.composeCollection=tk});var ol=N(Vf=>{"use strict";var al=V();function rk(t,e,r){let i=e.offset,n=ik(e,t.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?al.Scalar.BLOCK_FOLDED:al.Scalar.BLOCK_LITERAL,o=e.source?nk(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return e.source&&(v+=e.source.length),{value:h,type:a,comment:n.comment,range:[i,v,v]}}let c=e.indent+n.indent,l=e.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,w]=o[h];if(w===""||w==="\r")n.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"),n.indent===0&&(c=v.length),u=h,c===0&&!t.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="",p="",f=!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 ${n.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(y?2:1),"BAD_INDENT",E),v=""}a===al.Scalar.BLOCK_LITERAL?(d+=p+v.slice(c)+w,p=`
|
|
75
|
+
`):v.length>c||w[0]===" "?(p===" "?p=`
|
|
76
|
+
`:!f&&p===`
|
|
77
|
+
`&&(p=`
|
|
78
78
|
|
|
79
|
-
`),d+=
|
|
80
|
-
`,
|
|
79
|
+
`),d+=p+v.slice(c)+w,p=`
|
|
80
|
+
`,f=!0):w===""?p===`
|
|
81
81
|
`?d+=`
|
|
82
|
-
`:
|
|
83
|
-
`:(d+=
|
|
82
|
+
`:p=`
|
|
83
|
+
`:(d+=p+w,p=" ",f=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
|
|
84
84
|
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let m=i+n.length+
|
|
87
|
+
`}let m=i+n.length+e.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function ik({offset:t,props:e},r,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],a=n[0],o=0,s="",c=-1;for(let p=1;p<n.length;++p){let f=n[p];if(!s&&(f==="-"||f==="+"))s=f;else{let m=Number(f);!o&&m?o=m:c===-1&&(c=t+p)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let p=1;p<e.length;++p){let f=e[p];switch(f.type){case"space":l=!0;case"newline":d+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),d+=f.source.length;break;default:{let m=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",m);let h=f.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function nk(t){let e=t.split(/\n( *)/),r=e[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<e.length;o+=2)a.push([e[o],e[o+1]]);return a}Vf.resolveBlockScalar=rk});var cl=N(Wf=>{"use strict";var sl=V(),ak=Vr();function ok(t,e,r){let{offset:i,type:n,source:a,end:o}=t,s,c,l=(p,f,m)=>r(i+p,f,m);switch(n){case"scalar":s=sl.Scalar.PLAIN,c=sk(a,l);break;case"single-quoted-scalar":s=sl.Scalar.QUOTE_SINGLE,c=ck(a,l);break;case"double-quoted-scalar":s=sl.Scalar.QUOTE_DOUBLE,c=lk(a,l);break;default:return r(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=ak.resolveEnd(o,u,e,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function sk(t,e){let r="";switch(t[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 ${t[0]}`;break}case"@":case"`":{r=`reserved character ${t[0]}`;break}}return r&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),qf(t)}function ck(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),qf(t.slice(1,-1)).replace(/''/g,"'")}function qf(t){let e,r;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
|
-
`,"sy")}catch{
|
|
89
|
+
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=e.exec(t);if(!i)return t;let n=i[1],a=" ",o=e.lastIndex;for(r.lastIndex=o;i=r.exec(t);)i[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(
|
|
91
|
+
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(t),n+a+(i?.[1]??"")}function lk(t,e){let r="";for(let i=1;i<t.length-1;++i){let n=t[i];if(!(n==="\r"&&t[i+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
94
|
-
`)for(a=
|
|
95
|
-
`)for(a=
|
|
96
|
-
`&&!(o==="\r"&&
|
|
97
|
-
`)&&(r+=i>a?
|
|
98
|
-
`||i==="\r")&&!(i==="\r"&&e
|
|
93
|
+
`){let{fold:a,offset:o}=uk(t,i);r+=a,i=o}else if(n==="\\"){let a=t[++i],o=dk[a];if(o)r+=o;else if(a===`
|
|
94
|
+
`)for(a=t[i+1];a===" "||a===" ";)a=t[++i+1];else if(a==="\r"&&t[i+1]===`
|
|
95
|
+
`)for(a=t[++i+1];a===" "||a===" ";)a=t[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=pk(t,i+1,s,e),i+=s}else{let s=t.substr(i-1,2);e(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=t[i+1];for(;o===" "||o===" ";)o=t[++i+1];o!==`
|
|
96
|
+
`&&!(o==="\r"&&t[i+2]===`
|
|
97
|
+
`)&&(r+=i>a?t.slice(a,i+1):n)}else r+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),r}function uk(t,e){let r="",i=t[e+1];for(;(i===" "||i===" "||i===`
|
|
98
|
+
`||i==="\r")&&!(i==="\r"&&t[e+2]!==`
|
|
99
99
|
`);)i===`
|
|
100
100
|
`&&(r+=`
|
|
101
|
-
`),
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),e+=1,i=t[e+1];return r||(r=" "),{fold:r,offset:e}}var dk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function pk(t,e,r,i){let n=t.substr(e,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,r+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Wf.resolveFlowScalar=ok});var Kf=N(Gf=>{"use strict";var cr=A(),zf=V(),fk=ol(),hk=cl();function mk(t,e,r,i){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?fk.resolveBlockScalar(t,e,i):hk.resolveFlowScalar(e,t.options.strict,i),c=r?t.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[cr.SCALAR]:c?l=vk(t.schema,n,c,r,i):e.type==="scalar"?l=gk(t,n,e,i):l=t.schema[cr.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??e,"TAG_RESOLVE_FAILED",p),t.options);u=cr.isScalar(d)?d:new zf.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??e,"TAG_RESOLVE_FAILED",p),u=new zf.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function vk(t,e,r,i,n){if(r==="!")return t[cr.SCALAR];let a=[];for(let s of t.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(e))return s;let o=t.knownTags[r];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),t[cr.SCALAR])}function gk({atKey:t,directives:e,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(i))||r[cr.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[cr.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Gf.composeScalar=mk});var Uf=N(Jf=>{"use strict";function wk(t,e,r){if(e){r??(r=e.length);for(let i=r-1;i>=0;--i){let n=e[i];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++i];n?.type==="space";)t+=n.source.length,n=e[++i];break}}return t}Jf.emptyScalarPosition=wk});var Qf=N(ul=>{"use strict";var yk=Ai(),bk=A(),Nk=Ff(),Yf=Kf(),kk=Vr(),Sk=Uf(),Ek={composeNode:Xf,composeEmptyNode:ll};function Xf(t,e,r,i){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(e.type){case"alias":l=xk(t,e,i),(s||c)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Yf.composeScalar(t,e,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Nk.composeCollection(Ek,t,e,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(e,"RESOURCE_EXHAUSTION",p)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=ll(t,e.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!bk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&u&&(l.srcToken=e),l}function ll(t,e,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Sk.emptyScalarPosition(e,r,i),indent:-1,source:""},d=Yf.composeScalar(t,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function xk({options:t},{offset:e,source:r,end:i},n){let a=new yk.Alias(r.substring(1));a.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(e+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+r.length,s=kk.resolveEnd(i,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}ul.composeEmptyNode=ll;ul.composeNode=Xf});var th=N(eh=>{"use strict";var Ck=Gi(),Zf=Qf(),Pk=Vr(),Rk=Yi();function _k(t,e,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new Ck.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Rk.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Zf.composeNode(l,n,u,o):Zf.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=Pk.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}eh.composeDoc=_k});var pl=N(nh=>{"use strict";var Ak=na("process"),Ik=Xs(),Tk=Gi(),Xi=Ui(),rh=A(),jk=th(),$k=Vr();function Qi(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:r}=t;return[e,e+(typeof r=="string"?r.length:1)]}function ih(t){let e="",r=!1,i=!1;for(let n=0;n<t.length;++n){let a=t[n];switch(a[0]){case"#":e+=(e===""?"":i?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":
|
|
106
|
-
${i}`:i;else if(n||
|
|
105
|
+
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":t[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:e,afterEmptyLine:i}}var dl=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Qi(r);a?this.warnings.push(new Xi.YAMLWarning(o,i,n)):this.errors.push(new Xi.YAMLParseError(o,i,n))},this.directives=new Ik.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,r){let{comment:i,afterEmptyLine:n}=ih(this.prelude);if(i){let a=e.contents;if(r)e.comment=e.comment?`${e.comment}
|
|
106
|
+
${i}`:i;else if(n||e.directives.docStart||!a)e.commentBefore=i;else if(rh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];rh.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
|
|
107
107
|
${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
|
|
108
|
-
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)
|
|
109
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:ih(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,r=!1,i=-1){for(let n of e)yield*this.next(n);yield*this.end(r,i)}*next(e){switch(Ak.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(r,i,n)=>{let a=Qi(e);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let r=jk.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(e,"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(e.source);break;case"error":{let r=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Xi.YAMLParseError(Qi(e),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Xi.YAMLParseError(Qi(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=$k.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Xi.YAMLParseError(Qi(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),n=new Tk.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};nh.Composer=dl});var sh=N(Ua=>{"use strict";var Ok=ol(),Hk=cl(),Dk=Ui(),ah=Oi();function Lk(t,e=!0,r){if(t){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new Dk.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Hk.resolveFlowScalar(t,e,i);case"block-scalar":return Ok.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Bk(t,e){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=ah.stringifyString({type:o,value:t},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,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
|
-
`,
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:i,props:
|
|
114
|
-
`),i=
|
|
115
|
-
`;if(
|
|
116
|
-
`});for(let c of Object.keys(
|
|
117
|
-
`};delete
|
|
112
|
+
`,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return oh(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function Mk(t,e,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in t?t.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=ah.stringifyString({type:o,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Fk(t,c);break;case'"':fl(t,c,"double-quoted-scalar");break;case"'":fl(t,c,"single-quoted-scalar");break;default:fl(t,c,"scalar")}}function Fk(t,e){let r=e.indexOf(`
|
|
114
|
+
`),i=e.substring(0,r),n=e.substring(r+1)+`
|
|
115
|
+
`;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,t.source=n}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];oh(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:n})}}function oh(t,e){if(e)for(let r of e)switch(r.type){case"space":case"comment":t.push(r);break;case"newline":return t.push(r),!0}return!1}function fl(t,e,r){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=r,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),n=e.length;t.props[0].type==="block-scalar-header"&&(n-=t.props[0].source.length);for(let a of i)a.offset+=n;delete t.props,Object.assign(t,{type:r,source:e,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
|
|
117
|
+
`};delete t.items,Object.assign(t,{type:r,source:e,end:[n]});break}default:{let i="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:r,indent:i,source:e,end:n})}}}Ua.createScalarToken=Bk;Ua.resolveAsScalar=Lk;Ua.setScalarValue=Mk});var lh=N(ch=>{"use strict";var Vk=t=>"type"in t?Xa(t):Ya(t);function Xa(t){switch(t.type){case"block-scalar":{let e="";for(let r of t.props)e+=Xa(r);return e+t.source}case"block-map":case"block-seq":{let e="";for(let r of t.items)e+=Ya(r);return e}case"flow-collection":{let e=t.start.source;for(let r of t.items)e+=Ya(r);for(let r of t.end)e+=r.source;return e}case"document":{let e=Ya(t);if(t.end)for(let r of t.end)e+=r.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let r of t.end)e+=r.source;return e}}}function Ya({start:t,key:e,sep:r,value:i}){let n="";for(let a of t)n+=a.source;if(e&&(n+=Xa(e)),r)for(let a of r)n+=a.source;return i&&(n+=Xa(i)),n}ch.stringify=Vk});var fh=N(ph=>{"use strict";var hl=Symbol("break visit"),qk=Symbol("skip children"),uh=Symbol("remove item");function lr(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),dh(Object.freeze([]),t,e)}lr.BREAK=hl;lr.SKIP=qk;lr.REMOVE=uh;lr.itemAtPath=(t,e)=>{let r=t;for(let[i,n]of e){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};lr.parentCollection=(t,e)=>{let r=lr.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function dh(t,e,r){let i=r(e,t);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=dh(Object.freeze(t.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===hl)return hl;s===uh&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(e,t))}}return typeof i=="function"?i(e,t):i}ph.visit=lr});var Qa=N(me=>{"use strict";var ml=sh(),Wk=lh(),zk=fh(),vl="\uFEFF",gl="",wl="",yl="",Gk=t=>!!t&&"items"in t,Kk=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Jk(t){switch(t){case vl:return"<BOM>";case gl:return"<DOC>";case wl:return"<FLOW_END>";case yl:return"<SCALAR>";default:return JSON.stringify(t)}}function Uk(t){switch(t){case vl:return"byte-order-mark";case gl:return"doc-mode";case wl:return"flow-error-end";case yl:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
122
|
-
`?!0:r==="\r"?this.buffer[
|
|
123
|
-
`:!1}charAt(
|
|
124
|
-
`||!n&&!this.atEnd)return
|
|
125
|
-
`||i>=this.indentNext||!r&&!this.atEnd?
|
|
126
|
-
`,this.pos),this.lineEndPos=
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}me.createScalarToken=ml.createScalarToken;me.resolveAsScalar=ml.resolveAsScalar;me.setScalarValue=ml.setScalarValue;me.stringify=Wk.stringify;me.visit=zk.visit;me.BOM=vl;me.DOCUMENT=gl;me.FLOW_END=wl;me.SCALAR=yl;me.isCollection=Gk;me.isScalar=Kk;me.prettyToken=Jk;me.tokenType=Uk});var kl=N(mh=>{"use strict";var Zi=Qa();function Le(t){switch(t){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var hh=new Set("0123456789ABCDEFabcdef"),Yk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Za=new Set(",[]{}"),Xk=new Set(` ,[]{}
|
|
121
|
+
\r `),bl=t=>!t||Xk.has(t),Nl=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,r=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,r=this.buffer[e];for(;r===" "||r===" ";)r=this.buffer[++e];return!r||r==="#"||r===`
|
|
122
|
+
`?!0:r==="\r"?this.buffer[e+1]===`
|
|
123
|
+
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let r=this.buffer[e];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+e];if(r==="\r"){let n=this.buffer[i+e+1];if(n===`
|
|
124
|
+
`||!n&&!this.atEnd)return e+i+1}return r===`
|
|
125
|
+
`||i>=this.indentNext||!r&&!this.atEnd?e+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&Le(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Zi.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let r=e.length,i=e.indexOf("#");for(;i!==-1;){let a=e[i-1];if(a===" "||a===" "){r=i-1;break}else i=e.indexOf("#",i+1)}for(;;){let a=e[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-r),yield*this.pushNewline(),"stream"}return yield Zi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let 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[e,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Le(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(e[r]){case"#":yield*this.pushCount(e.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(bl),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,r,i=-1;do e=yield*this.pushNewline(),e>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(e+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Le(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Zi.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(bl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Le(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),r=this.buffer.indexOf(e,this.pos+1);if(e==="'")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 i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
128
|
-
`,a)}n!==-1&&(r=n-(i[n-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
|
|
129
|
-
`:
|
|
130
|
-
`)break}default:break e}if(!i&&!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(
|
|
131
|
-
`,a)}while(
|
|
132
|
-
`;)i=this.buffer[++n];
|
|
133
|
-
`&&a>=this.pos&&a+1+r>s)
|
|
128
|
+
`,a)}n!==-1&&(r=n-(i[n-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 e=this.pos;for(;;){let r=this.buffer[++e];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 e=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
129
|
+
`:e=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(!i&&!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(e+1);if(a===-1)break;e=this.buffer.indexOf(`
|
|
131
|
+
`,a)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let n=e+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
132
|
+
`;)i=this.buffer[++n];e=n-1}else if(!this.blockScalarKeep)do{let a=e-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
+
`&&a>=this.pos&&a+1+r>s)e=a;else break}while(!0);return yield Zi.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Le(a)||e&&Za.has(a))break;r=i}else if(Le(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(i+=1,n=`
|
|
135
|
-
`,a=this.buffer[i+1]):r=i),a==="#"||
|
|
136
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(
|
|
137
|
-
`?yield*this.pushCount(1):
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(
|
|
135
|
+
`,a=this.buffer[i+1]):r=i),a==="#"||e&&Za.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&Za.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Zi.SCALAR,yield*this.pushToIndex(r+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,r){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(bl),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Le(i)||r&&Za.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,r=this.buffer[e];for(;!Le(r)&&r!==">";)r=this.buffer[++e];return yield*this.pushToIndex(r===">"?e+1:e,!1)}else{let e=this.pos+1,r=this.buffer[e];for(;r;)if(Yk.has(r))r=this.buffer[++e];else if(r==="%"&&hh.has(this.buffer[e+1])&&hh.has(this.buffer[e+2]))r=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
137
|
+
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||e&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(e){let r=this.pos,i=this.buffer[r];for(;!e(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};mh.Lexer=Nl});var El=N(vh=>{"use strict";var Sl=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<e?r=a+1:i=a}if(this.lineStarts[r]===e)return{line:r+1,col:1};if(r===0)return{line:0,col:e};let n=this.lineStarts[r-1];return{line:r,col:e-n+1}}}};vh.LineCounter=Sl});var Cl=N(Nh=>{"use strict";var Qk=na("process"),gh=Qa(),Zk=kl();function Bt(t,e){for(let r=0;r<t.length;++r)if(t[r].type===e)return!0;return!1}function wh(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function bh(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function eo(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function qr(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function to(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let r=0;r<e.length;++r)t.push(e[r])}function yh(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Bt(e.start,"explicit-key-ind")&&!Bt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,bh(e.value)?e.value.end?to(e.value.end,e.sep):e.value.end=e.sep:to(e.start,e.sep),delete e.sep)}var xl=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Zk.Lexer,this.onNewLine=e}*parse(e,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(e,r))yield*this.next(i);r||(yield*this.end())}*next(e){if(this.source=e,Qk.env.LOG_TOKENS&&console.log("|",gh.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=gh.tokenType(e);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+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let i=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let r=e??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 i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&yh(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&wh(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{wh(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let r=eo(this.peek(2)),i=qr(r),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let 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(
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let r=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.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)e.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){to(n,r.start),n.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&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>e.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":n||r.value?(a.push(this.sourceToken),e.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):n||r.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)e.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(bh(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||n?e.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);n||r.value?(e.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(e);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 i&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let r=e.items[e.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){to(n,r.start),n.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=e.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;r.value||Bt(r.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let r=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?e.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?e.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 n=this.flowScalar(this.type);!r||r.value?e.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=eo(i),a=qr(n);yh(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let r=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
-
`,r)+1}return{type:
|
|
143
|
-
`)){let s=
|
|
142
|
+
`,r)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=eo(e),i=qr(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=eo(e),i=qr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Nh.Parser=xl});var Ch=N(tn=>{"use strict";var kh=pl(),eS=Gi(),en=Ui(),tS=uc(),rS=A(),iS=El(),Sh=Cl();function Eh(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new iS.LineCounter||null,prettyErrors:e}}function nS(t,e={}){let{lineCounter:r,prettyErrors:i}=Eh(e),n=new Sh.Parser(r?.addNewLine),a=new kh.Composer(e),o=Array.from(a.compose(n.parse(t)));if(i&&r)for(let s of o)s.errors.forEach(en.prettifyError(t,r)),s.warnings.forEach(en.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function xh(t,e={}){let{lineCounter:r,prettyErrors:i}=Eh(e),n=new Sh.Parser(r?.addNewLine),a=new kh.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new en.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(en.prettifyError(t,r)),o.warnings.forEach(en.prettifyError(t,r))),o}function aS(t,e,r){let i;typeof e=="function"?i=e:r===void 0&&e&&typeof e=="object"&&(r=e);let n=xh(t,r);if(!n)return null;if(n.warnings.forEach(a=>tS.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function oS(t,e,r){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:r===void 0&&e&&(r=e),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(t===void 0){let{keepUndefined:n}=r??e??{};if(!n)return}return rS.isDocument(t)&&!i?t.toString(r):new eS.Document(t,i,r).toString(r)}tn.parse=aS;tn.parseAllDocuments=nS;tn.parseDocument=xh;tn.stringify=oS});var mt=N($=>{"use strict";var sS=pl(),cS=Gi(),lS=Gc(),Pl=Ui(),uS=Ai(),Mt=A(),dS=Ot(),pS=V(),fS=Dt(),hS=Lt(),mS=Qa(),vS=kl(),gS=El(),wS=Cl(),ro=Ch(),Ph=Ci();$.Composer=sS.Composer;$.Document=cS.Document;$.Schema=lS.Schema;$.YAMLError=Pl.YAMLError;$.YAMLParseError=Pl.YAMLParseError;$.YAMLWarning=Pl.YAMLWarning;$.Alias=uS.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=dS.Pair;$.Scalar=pS.Scalar;$.YAMLMap=fS.YAMLMap;$.YAMLSeq=hS.YAMLSeq;$.CST=mS;$.Lexer=vS.Lexer;$.LineCounter=gS.LineCounter;$.Parser=wS.Parser;$.parse=ro.parse;$.parseAllDocuments=ro.parseAllDocuments;$.parseDocument=ro.parseDocument;$.stringify=ro.stringify;$.visit=Ph.visit;$.visitAsync=Ph.visitAsync});import Ft from"path";function jh(t,e){return Wr[e][t]}function SS(t,e,r,i){let n=/^(\s*)([a-z_]+):/u.exec(t);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Wr.en)return o;if(a===2&&e){let s=`${e}.${o}`;if(s in Wr.en)return s}if(a===4&&e==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Wr.en)return s}if(a===4&&e==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Wr.en)return s}if(a===2&&e===null&&o==="hook")return"hook";if(a===2&&e==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&e==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Wr.en)return s}return null}function sn(t,e){let r=[],i=null,n=null,a=null;for(let o of(0,an.stringify)(t).trimEnd().split(`
|
|
143
|
+
`)){let s=SS(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of jh(s,e).split(`
|
|
144
144
|
`))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
|
|
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.
|
|
145
|
+
`)}function ES(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||Ft.posix.isAbsolute(r)||Ft.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function ur(t){let e=ES(t,"native.artifact_root");return e.length===0?".":e.join("/")}function $h(t,e="docs"){let r=t??e;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function oo(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Ft.posix.isAbsolute(i)||Ft.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function vt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Oh(t,e,r){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function so(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>io)throw new Error(`${e} exceeds ${io} characters`);let r=0;for(let i=0;i<t.length;i+=1)t[i]==="?"?r+=1:t[i]==="*"&&(r+=1,t[i+1]==="*"&&(i+=1));if(r>no)throw new Error(`${e} contains more than ${no} wildcard tokens`);return t}function Ih(t,e,r){if(t===void 0)return[...r];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>so(i,e)))].sort((i,n)=>i.localeCompare(n,"en"))}function rn(t,e,r){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Th(t,e,r){let i=rn(t,e,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 xS(t){if(t===void 0)return{...ve,include:[...ve.include],exclude:[...ve.exclude]};let e=vt(t,"native.snapshot");return{include:Ih(e.include,"native.snapshot.include",ve.include),exclude:Ih(e.exclude,"native.snapshot.exclude",ve.exclude),max_files:rn(e.max_files,ve.max_files,"native.snapshot.max_files"),max_total_bytes:rn(e.max_total_bytes,ve.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:rn(e.max_duration_ms,ve.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:rn(e.max_selection_records,ve.max_selection_records,"native.snapshot.max_selection_records")}}function CS(t){if(t===void 0)return;let e=vt(t,"native.pending_root_move"),r=e.id,i=e.from_artifact_root,n=e.to_artifact_root,a=e.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(e.cleanup!==void 0){let s=vt(e.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(i),toArtifactRoot:ur(n),stage:a,...o?{cleanup:o}:{}}}function PS(t){if(t===void 0)return;let e=vt(t,"native.finish");if(e.pull_request===void 0)return{};let r=vt(e.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(Ft.posix.isAbsolute(i[0])||Ft.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??yS;if(!Number.isSafeInteger(n)||n<1||n>Ah)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ah}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function RS(t,e={}){let r=vt(t,"native"),i=r.artifact_root??(e.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??Rl;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=CS(r.pending_root_move),l=PS(r.finish);return{artifact_root:ur(i),language:Oh(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:xS(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function _S(t){let e=vt(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=e.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:$h(e.artifact_layout),language:Oh(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function AS(t){let r=vt(t,"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)=>oo(i,`hook.allow_paths[${n}]`)))]}}function IS(t){if(t===void 0)return{...nn};let e=vt(t,"memory"),r=e.learning??nn.learning,i=e.retrieval??nn.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 Al(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function TS(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ft.posix.isAbsolute(r)||Ft.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${e} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${e} must target a Markdown file ending in .md`);if(r.length>Rh)throw new Error(`${e} exceeds ${Rh} 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>_h)throw new Error(`${e} contains more than ${_h} wildcard tokens`);return r}function jS(t){let e=Al(t,"knowledge.local"),r=e.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>TS(n,`knowledge.local.include[${a}]`)))],max_file_mb:Th(e.max_file_mb,ao.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Th(e.max_total_mb,ao.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 $S(t){if(typeof t!="string"||t.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let e;try{e=new URL(t)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=e.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return e.toString()}function OS(t){let e=Al(t,"knowledge.remote"),r=$S(e.endpoint),i=e.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=e.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=e.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 HS(t){if(t===void 0)return{..._l};let e=Al(t,"knowledge"),r=e.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=e.local===void 0?void 0:jS(e.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=e.remote===void 0?void 0:OS(e.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 DS(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function LS(t,e,r,i,n,a,o,s){let c=t.schema!==void 0;if(!(c||t.default_workflow!==void 0||t.workflows!==void 0||!s.allowPartialProject&&t.native!==void 0)||s.allowPartialProject&&!c)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=t.workflows??[t.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(p=>p!=="native"&&p!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(t.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:t.default_workflow,workflows:d,ambient_resume:o,...e?{hook:e}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function zr(t,e={}){let r=(0,an.parseDocument)(t,{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=DS(n.ambient_resume),o=n.hook===void 0?void 0:AS(n.hook),s=IS(n.memory),c=HS(n.knowledge),l=n.native===void 0?void 0:RS(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=n.classic===void 0?void 0:_S(n.classic),d=LS(n,o,s,c,l,u,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Hh(t){return{id:t.id,from_artifact_root:t.fromArtifactRoot,to_artifact_root:t.toArtifactRoot,stage:t.stage,...t.cleanup?{cleanup:{kind:t.cleanup.kind,state:t.cleanup.state,manifest_hash:t.cleanup.manifestHash}}:{}}}function Dh(t){let e=t.knowledge??{..._l};return{schema:t.schema,default_workflow:t.default_workflow,workflows:t.workflows??[t.default_workflow],ambient_resume:t.ambient_resume,memory:t.memory??{...nn},knowledge:{provider:e.provider,...e.local?{local:{include:[...e.local.include],max_file_mb:e.local.max_file_mb??ao.max_file_mb,max_total_mb:e.local.max_total_mb??ao.max_total_mb}}:{},...e.remote?{remote:{endpoint:e.remote.endpoint,timeout_ms:e.remote.timeout_ms,...e.remote.token_env===void 0?{}:{token_env:e.remote.token_env},...e.remote.scope===void 0?{}:{scope:e.remote.scope}}}:{}},...t.hook?{hook:{allow_paths:[...t.hook.allow_paths]}}:{},...t.native?{native:{artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,...t.native.document_writes?{document_writes:t.native.document_writes}:{},...t.native.finish?.pull_request?{finish:{pull_request:{provider:t.native.finish.pull_request.provider,command:[...t.native.finish.pull_request.command],timeout_ms:t.native.finish.pull_request.timeout_ms}}}:{},...t.native.pending_root_move?{pending_root_move:Hh(t.native.pending_root_move)}:{}}}:{},...t.classic?{classic:{artifact_layout:t.classic.artifact_layout,language:t.classic.language,context_compression:t.classic.context_compression,review_mode:t.classic.review_mode,auto_transition:t.classic.auto_transition,...t.classic.document_evidence?{document_evidence:t.classic.document_evidence}:{}}}:{}}}function be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function cn(t,e){let r=Dh(e),i=zr((0,an.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...t,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...be(t.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=be(t.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=be(t.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...be(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={...be(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=be(t.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=be(a.finish);o.finish={...s,pull_request:{...be(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={...be(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=be(a.pending_root_move),c=Hh(i.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;n.native=o}return i.classic&&(n.classic={...be(t.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 co(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...nn},knowledge:{..._l},native:{artifact_root:ur(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Rl,snapshot:{...ve,include:[...ve.include],exclude:[...ve.exclude]}}}}var an,on,io,no,Rh,_h,Rl,nn,ao,_l,yS,Ah,bS,NS,kS,ve,Wr,Vt=S(()=>{"use strict";an=At(mt(),1),on=Number.MAX_SAFE_INTEGER,io=1024,no=64,Rh=1024,_h=64,Rl=5,nn={learning:!0,retrieval:!0},ao={include:[],max_file_mb:1,max_total_mb:32},_l={provider:"local"},yS=12e4,Ah=6e5,bS=[".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/**"],NS=["**/.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"],kS=[...bS,...NS].sort((t,e)=>t.localeCompare(e,"en")),ve={include:["**/*"],exclude:[...kS],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,142 @@ ${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(t){return t!==0&&t!==0n&&t!=="0"}function et(t,e){return qt(t.dev)&&qt(e.dev)&&qt(t.ino)&&qt(e.ino)}function H(t,e){let r=qt(t.dev)&&qt(e.dev);if(r&&t.dev!==e.dev)return!1;let i=qt(t.ino)&&qt(e.ino);return i&&t.ino!==e.ino?!1:r&&i?!0:t.birthtime===e.birthtime}var ln=S(()=>{"use strict"});import{constants as lo,promises as dr}from"fs";function Il(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Lh(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function un(t){return{dev:t.dev,ino:t.ino,birthtime:Il(t)}}function uo(t,e){let r=un(t),i=un(e);return et(r,i)?H(r,i):H(r,i)&&Il(t)===Il(e)&&Lh(t)===Lh(e)&&t.size===e.size}async function Gr(t,e,r={}){if(!Number.isSafeInteger(e)||e<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 dr.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new Be("too-large",`${i} exceeds ${e} bytes`);let o=await dr.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:un(a)});let s=process.platform==="win32"?lo.O_RDONLY:lo.O_RDONLY|lo.O_NOFOLLOW|lo.O_NONBLOCK,c;try{c=await dr.open(t,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),dr.lstat(t,{bigint:n}),dr.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!uo(a,l)||!uo(a,u))throw new Be("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:un(l)}),await r.hooks?.afterOpen?.();let p=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-f,{bytesRead:k}=await c.read(m,0,Math.min(m.length,y),null);if(k===0)break;if(f+=k,f>e)throw new Be("too-large",`${i} exceeds ${e} bytes`);p.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:n}),dr.lstat(t,{bigint:n}),dr.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!uo(a,h)||!uo(a,v))throw new Be("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:un(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:w}}finally{await c.close()}}var Be,dn=S(()=>{"use strict";ln();Be=class extends Error{reason;constructor(e,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as po}from"fs";import Wt from"path";function BS(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Tl(t,e){let r=Wt.relative(t,e);return r===""||!Wt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Wt.sep}`)}async function Bh(t,e){let r=Wt.resolve(t),i=await po.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return po.realpath(r)}async function Mh(t,e,r,i){let n=t;for(let a=0;a<r.length;a++){n=Wt.join(n,r[a]);let o;try{o=await po.lstat(n)}catch(u){if(BS(u))return{exists:!1,kind:"missing"};throw u}let s=Wt.relative(t,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 po.realpath(n);if(!Tl(e,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 gt(t,e,r){let i=oo(e,r.label),n=Wt.resolve(t),a=await Bh(n,r.label),o=i.split("/"),s=Wt.resolve(n,...o);if(!Tl(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Mh(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Z(t,e,r,i){let n=await gt(t,e,{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 Bh(n.projectRoot,i.label);return Gr(n.target,r,{...i,verify:async(o,s)=>{if(!Tl(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Mh(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var tt=S(()=>{"use strict";dn();Vt()});import{createHash as MS}from"crypto";function jl(t,e){return t.exists===e.exists&&t.sha256===e.sha256}function FS(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function fo(t,e={}){return(await fn(t,e)).document}async function Fh(t){try{return(await Z(t,pn,on,{label:pn})).bytes}catch(e){if(FS(e))return null;throw e}}function Vh(t){return t?{exists:!0,sha256:MS("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function ho(t){return Vh(await Fh(t))}async function fn(t,e={}){let r=await Fh(t);return{document:r?zr(r.toString("utf8"),e):null,identity:Vh(r)}}async function pr(t){return(await fo(t))?.config??null}var pn,fr=S(()=>{"use strict";Vt();tt();pn=".comet/config.yaml"});import{promises as Ol}from"node:fs";async function Hl(t,e){let r;for(let i=0;i<=$l.length;i+=1)try{return await t()}catch(n){r=n;let a=n.code;if(i===$l.length||!VS.has(a??""))throw n;await new Promise(o=>setTimeout(o,$l[i]))}throw r}async function mo(t,e){await Hl(()=>Ol.rename(t,e),`rename ${e}`)}async function Dl(t){await Hl(()=>Ol.unlink(t),`unlink ${t}`)}async function vo(t,e){await Hl(()=>Ol.link(t,e),`link ${e}`)}var VS,$l,Ll=S(()=>{"use strict";VS=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),$l=[50,100,200]});import{randomUUID as qS}from"crypto";import{constants as WS,promises as ce}from"fs";import Me from"path";async function Bl(t,e){try{return await vo(t,e),{linked:!0}}catch(r){let i=r.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw r}return await ce.copyFile(t,e,WS.COPYFILE_EXCL),{linked:!1}}function go(t,e){let r=Me.relative(t,e);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function wo(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function zS(t,e){return H(t,wo(e))}function yo(t,e){return H(wo(t),wo(e))}function GS(t,e){return yo(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function qh(t){let e=await ce.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await ce.realpath(t),...wo(e)}}async function Kr(t){for(let e of t){let r=await ce.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!zS(e,r)||await ce.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function KS(t,e,r){let[i,n]=await Promise.all([ce.lstat(t),ce.realpath(t),Kr(r)]);if(!i.isFile()||i.isSymbolicLink()||!yo(i,e)||!go(r[0].realPath,n))throw new Error("Contained atomic write temporary file changed after close");return i}async function JS(t,e){let r=Me.resolve(t),i=Me.resolve(e);if(!go(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let n=[await qh(r)],a=Me.relative(r,i).split(Me.sep).filter(Boolean),o=r;for(let s of a){await Kr(n),o=Me.join(o,s);try{await ce.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await qh(o);if(!go(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Kr(n),n}async function US(t){let e;try{e=await ce.open(t,"r"),await e.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await e?.close()}}async function YS(t,e,r){let i=Me.dirname(t),n=await JS(r.containedRoot,i),a=Me.join(i,`.${Me.basename(t)}.${qS()}.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(n),!l.isFile()||l.isSymbolicLink()||!yo(s,l)||!go(n[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!yo(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 KS(a,c,n),await r.beforeCommit?.(),await Kr(n);let d=await ce.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!GS(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await Bl(a,t),await ce.unlink(a)):await mo(a,t),await US(i)}catch(l){await o?.close();try{await Kr(n),await ce.rm(a,{force:!0})}catch{}throw l}}async function hr(t,e,r){await YS(t,e,r)}var Jr=S(()=>{"use strict";Ll();ln()});var u$,Ml=S(()=>{"use strict";Jr();fr();tt();u$=16*1024});async function Fl(t,e){if(!e)return;let r=await ho(t);if(!jl(r,e))throw new Error("Project config changed before commit; rerun the operation")}var Vl=S(()=>{"use strict";Jr();Vt();fr();tt();Ml()});var rt=S(()=>{"use strict";ln()});var Kh={};Ww(Kh,{atomicWriteBytes:()=>Gh,atomicWriteJson:()=>ae,atomicWriteText:()=>ee});import{randomUUID as ZS}from"crypto";import{promises as le}from"fs";import Fe from"path";function bo(t,e){let r=Fe.relative(t,e);return r===""||!Fe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Fe.sep}`)}function eE(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function No(t,e){return H({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function tE(t,e){return No(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Wh(t){let e=await le.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await le.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Ur(t){for(let e of t){let r=await le.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!eE(e,r)||await le.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function rE(t,e,r){let[i,n]=await Promise.all([le.lstat(t),le.realpath(t),r?Ur(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!No(i,e)||r&&!bo(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function iE(t,e){let r=Fe.resolve(t),i=Fe.resolve(e);if(!bo(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await Wh(r)],a=Fe.relative(r,i).split(Fe.sep).filter(Boolean),o=r;for(let s of a){await Ur(n),o=Fe.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wh(o);if(!bo(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ur(n),n}async function nE(t){let e;try{e=await le.open(t,"r"),await e.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await e?.close()}}async function zh(t,e,r={}){let i=Fe.dirname(t),n=r.containedRoot?await iE(r.containedRoot,i):null;n||await le.mkdir(i,{recursive:!0});let a=Fe.join(i,`.${Fe.basename(t)}.${ZS()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Ur(n),!l.isFile()||l.isSymbolicLink()||!No(s,l)||!bo(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!No(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 rE(a,c,n),await r.beforeCommit?.(),n){await Ur(n);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!tE(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await vo(a,t),await Dl(a)):await mo(a,t),await nE(i)}catch(l){if(await o?.close(),!n)await le.rm(a,{force:!0});else try{await Ur(n),await le.rm(a,{force:!0})}catch{}throw l}}async function ee(t,e,r={}){await zh(t,e,r)}async function Gh(t,e,r={}){await zh(t,e,r)}async function ae(t,e,r={}){await ee(t,JSON.stringify(e,null,2)+`
|
|
174
|
+
`,r)}var B=S(()=>{"use strict";Ll();rt()});import{existsSync as Jh,promises as wt}from"fs";import P from"path";import aE from"os";async function ql(t){try{return await wt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function sE(t){try{let e=await wt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Xr(t,e){let r=P.relative(t,e);return r===""||!P.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${P.sep}`)}async function Yr(t){let e=[],r=t;for(;!await ql(r);){let n=P.dirname(r);if(n===r)break;e.push(P.basename(r)),r=n}let i=await wt.realpath(r);return P.resolve(i,...e.reverse())}async function Wl(t){try{return(await wt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function zl(t){let e=P.resolve(t);try{(await wt.stat(e)).isDirectory()||(e=P.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let r=e,i=P.resolve(aE.homedir());for(;;){if(!(e===i&&r!==i)){let o=P.join(e,...ko.split("/")),s=e===r||await sE(o);if(await ql(o)&&s)return e}if(await ql(P.join(e,".git")))return e;let a=P.dirname(e);if(a===e)return r;e=a}}function Gl(t){return ur(t)}async function cE(t,e){let r=Gl(e),i=P.resolve(t,...r.split("/")),n=await wt.realpath(t),a=await Yr(i);if(!Xr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function yt(t,e){let r=Gl(e),i=await cE(t,r),n=P.join(i,"comet");if(await Wl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Yr(i),Yr(n)]);if(!Xr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=P.resolve(t),c=P.join(s,".comet","runtime","native");if(await Wl(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(t,...ko.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:P.join(n,"specs"),changesDir:P.join(n,"changes"),archiveDir:P.join(n,"archive"),runtimeDir:c,changesRuntimeDir:P.join(c,"changes"),locksDir:P.join(c,"locks"),transactionsDir:P.join(c,"transactions")}}async function Uh(t){await Promise.all([t.specsDir,t.changesDir,t.archiveDir].map(async e=>{await j(t.nativeRoot,e),await wt.mkdir(e,{recursive:!0})})),await Promise.all([t.changesRuntimeDir,t.locksDir,t.transactionsDir].map(async e=>{await j(t.projectRoot,e),await wt.mkdir(e,{recursive:!0})}))}function Kl(t){if(!oE.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Ve(t,e){Kl(e);let r=P.join(t.changesRuntimeDir,e);if(!te(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function lE(t,e){Kl(e);let r=P.join(t.changesDir,e,"runtime");if(!te(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ne(t,e){let r=Ve(t,e);if(Jh(r))return r;let i=lE(t,e);return Jh(i)?i:r}function Yh(t,e){Kl(e);let r=P.join(t.changesDir,e),i=Ne(t,e);return{artifactRoot:t.artifactRoot,nativeRoot:t.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:i,runtimeStatePath:P.join(i,"state.json")}}function qe(t,e){let r=P.resolve(e);if(te(t.runtimeDir,r))return t.runtimeDir;if(te(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function te(t,e){return Xr(P.resolve(t),P.resolve(e))}async function j(t,e){let r=P.resolve(t),i=P.resolve(e);if(!Xr(r,i))throw new Error(`Path is outside the Native root: ${e}`);if(await Wl(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([Yr(r),Yr(i)]);if(!Xr(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return i}var ko,oE,L=S(()=>{"use strict";Vt();ko=".comet/config.yaml",oE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import uE from"path";function Xh(t="docs",e="en"){return co(t,e)}async function oe(t){let e=(await fo(t))?.config??null;return e?.native?e:null}async function Eo(t){let e=await oe(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function hn(t,e,r={}){let i=await fn(t,{allowPartialProject:!0}),n=cn(i.document?.value??{},e),a=uE.join(t,...ko.split("/"));await ee(a,sn(n,e.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:t,beforeCommit:async()=>{await r.beforeCommit?.(),await Fl(t,i.identity)}})}var So,ke=S(()=>{"use strict";Vt();fr();Vl();B();L();So=so});function TE(t){return t.toLowerCase().startsWith(".env")}function mn(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>TE(i))?"environment-file":r.some(i=>IE.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>AE.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var AE,IE,vn=S(()=>{"use strict";AE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),IE=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as jE}from"node:crypto";import{promises as We}from"node:fs";import _e from"node:path";import{TextDecoder as $E}from"node:util";function Ql(t,e){let r=_e.relative(t,e);return r===""||!_e.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_e.sep}`)}function OE(t){let e=_e.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||_e.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let r=t.toLowerCase(),i=mn(t);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${t}`);return t}function HE(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function DE(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Io(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return et(r,i)?H(r,i):H(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function sm(t){let e=await We.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await We.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function LE(t,e){let r=_e.resolve(t),i=_e.resolve(e);if(!Ql(r,i))throw new Error("Native artifact path is outside its root");let n=[await sm(r)],a=r;for(let o of _e.relative(r,i).split(_e.sep).filter(Boolean)){a=_e.join(a,o);let s=await sm(a);if(!Ql(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function cm(t){for(let e of t){let r=await We.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!DE(e,r)||await We.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function ue(t){let e=OE(t.ref),r=t.maxBytes===null?null:HE(t.maxBytes??lm),i=_e.resolve(t.root,...e.split("/")),n=await LE(t.root,_e.dirname(i));await t.hooks?.afterParentChainCaptured?.();let a=await We.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);let o=await We.realpath(i);if(!Ql(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await We.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),We.lstat(i),We.realpath(i)]);if(await cm(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Io(a,c)||!Io(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],p=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?f.length:r+1-p,E=await s.read(f,0,Math.min(f.length,k),null);if(E.bytesRead===0)break;if(p+=E.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);d.push(Buffer.from(f.subarray(0,E.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),We.lstat(i),We.realpath(i)]);if(await cm(n),!h.isFile()||h.isSymbolicLink()||v!==o||!Io(c,m)||!Io(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,p),y;try{y=new $E("utf-8",{fatal:!0}).decode(w)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:p,hash:t.includeHash===!1?null:jE("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var lm,Ae=S(()=>{"use strict";vn();rt();lm=1024*1024});import{createHash as BE}from"node:crypto";function tu(t){return t.replaceAll(`\r
|
|
175
175
|
`,`
|
|
176
176
|
`).replaceAll("\r",`
|
|
177
|
-
`)}function
|
|
178
|
-
`),i=
|
|
177
|
+
`)}function hm(t){return BE("sha256").update(tu(t)).digest("hex")}function ru(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new D(`${e} must be an object`);return t}function mm(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new D(`${r} has unknown field(s): ${i.join(", ")}`)}function iu(t,e){if(typeof t!="string"||t.trim().length===0)throw new D(`${e} must be a non-empty string`);return t.trim()}function dm(t,e){if(t!==void 0){if(typeof t!="string")throw new D(`${e} must be text`);return tu(t).replace(/^\n+|\n+$/gu,"")}}function To(t,e){let r=iu(t,e).toLowerCase();if(!FE.test(r))throw new D(`${e} must be a SHA-256 hash`);return r}function pm(t,e,r){let i=ru(t,e),n=Object.entries(i);if(n.length>um)throw new D(`${e} must contain at most ${um} entries`);let a={};for(let[o,s]of n){if(eu(o,`${e} ID`)!==o)throw new D(`${e} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=To(s,`${e}.${o}`)}return a}function eu(t,e){let r=iu(t,e);if(!fm.test(r))throw new D(`${e} is not a valid stable requirement ID`);return r}function VE(t,e){let r=iu(t,e);if(!ME.test(r))throw new D(`${e} is not a valid capability ID`);return r}function qE(t,e){let r=`Native delta operations[${e}]`,i=ru(t,r);mm(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=eu(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new D(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:eu(i.to_id,`${r}.to_id`),c=dm(i.title,`${r}.title`),l=dm(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:To(i.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===n||!u||l==="")throw new D(`${r} rename requires a different to_id and expected_hash`);return{id:n,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 WE(t){let e=ru(t,"Native delta");if(mm(e,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),e.schema!==Zl)throw new D(`Native delta schema must be ${Zl}`);let r=VE(e.capability,"Native delta capability"),i=To(e.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(e.base_version)||Number(e.base_version)<1)throw new D("Native delta base_version must be a positive integer");let n=e.legacy_hash===void 0?void 0:To(e.legacy_hash,"Native delta legacy_hash"),a;e.base_requirements!==void 0&&(a=pm(e.base_requirements,"Native delta base_requirements",!1));let o=e.independent_requirements===void 0?void 0:pm(e.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(e.operations))throw new D("Native delta operations must be an array");let s=e.operations.map(qE),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let p of d){if(c.has(p))throw new D(`Native delta operations contain duplicate or overlapping requirement ID ${p} at ${l}`);c.add(p)}}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:Zl,capability:r,base_hash:i,base_version:Number(e.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function zE(t){let e=(0,jo.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new D(`Native delta is invalid YAML: ${e.errors[0].message}`);return e.toJS({mapAsMap:!1})}function $o(t){return WE(typeof t=="string"?zE(t):t)}function nu(t){let e=$o(t);return(0,jo.stringify)({schema:e.schema,capability:e.capability,base_hash:e.base_hash,base_version:e.base_version,...e.legacy_hash===void 0?{}:{legacy_hash:e.legacy_hash},...e.base_requirements===void 0?{}:{base_requirements:Object.fromEntries(Object.entries(e.base_requirements).sort(([r],[i])=>r.localeCompare(i,"en")))},...e.independent_requirements===void 0?{}:{independent_requirements:Object.fromEntries(Object.entries(e.independent_requirements).sort(([r],[i])=>r.localeCompare(i,"en")))},operations:e.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 GE(t){let e=/^\s{0,3}(#{1,6})\s+/u.exec(t);return e?e[1].length:null}function KE(t){let e=[],r=null;for(let[i,n]of t.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.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(n);if(!o)continue;let s=o[3];if(!fm.test(s))throw new D(`Native total Spec requirement ID is invalid: ${s}`);e.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return e}function vm(t){let e=tu(t),r=e.split(`
|
|
178
|
+
`),i=KE(r),n=[],a=new Set;for(let l of i){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(i.some(f=>f.line===d)){u=d;break}let p=GE(r[d]);if(p!==null&&p<=l.level){u=d;break}}n.push({start:l.line,end:u,marker:l})}let o=new Map;for(let l of n){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
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 n)s.push(r.slice(c,l.start).join(`
|
|
182
182
|
`)),c=l.end;return s.push(r.slice(c).join(`
|
|
183
|
-
`)),{text:
|
|
184
|
-
`)}}function
|
|
183
|
+
`)),{text:e,lines:r,requirements:o,legacyText:s.join(`
|
|
184
|
+
`)}}function zt(t){return hm(t)}function Oo(t){let e=vm(t).legacyText;return hm(e.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)}
|
|
186
|
+
`).trim())}function au(t){let e=vm(t);return{legacy_hash:Oo(t),requirements:[...e.requirements.values()].map(r=>({...r}))}}var jo,Zl,ME,fm,FE,um,D,Ho=S(()=>{"use strict";jo=At(mt(),1),Zl="comet.native.delta.v1",ME=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,fm=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,FE=/^[a-f0-9]{64}$/iu,um=512,D=class extends Error{code="native-delta-invalid";constructor(e){super(e),this.name="NativeDeltaValidationError"}}});import{AsyncLocalStorage as JE}from"node:async_hooks";import{performance as Do}from"node:perf_hooks";function ou(t=0){UE+=1,YE+=t;let e=XE.getStore();e&&(e.gitCommands+=1,e.gitDurationMs+=t)}function gn(t){let e=Do.now();try{return t()}finally{ou(Do.now()-e)}}async function su(t){let e=Do.now();try{return await t()}finally{ou(Do.now()-e)}}var UE,YE,XE,Qr=S(()=>{"use strict";UE=0,YE=0,XE=new JE});import{execFileSync as QE}from"node:child_process";function tx(t,e){try{return gn(()=>QE("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:ZE,maxBuffer:ex,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new cu(t,e,i)}}function re(t,e){return tx(t,e).trim()}function lu(t){return re(t,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function uu(t,e){re(t,["check-ref-format","--branch",e])}var ZE,ex,cu,ze=S(()=>{"use strict";Qr();ZE=3e4,ex=8*1024*1024,cu=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function bu(){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 ri,kn,zm,Sn=S(()=>{"use strict";ri="comet.native.v4",kn="comet.native.local-execution.v4",zm=["multi-session","single-session"]});import{createHash as Yx}from"crypto";function Ge(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Xx(t,e){e.has(t)&&Ge("cyclic structures are not supported"),e.add(t);try{let r=Object.keys(t);for(let i=0;i<t.length;i+=1)Object.prototype.hasOwnProperty.call(t,i)||Ge("sparse arrays are not supported");return(r.length!==t.length||r.some((i,n)=>i!==String(n)))&&Ge("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Ge("symbol properties are not supported"),`[${t.map(i=>Nu(i,e)).join(",")}]`}finally{e.delete(t)}}function Qx(t,e){let r=Object.getPrototypeOf(t);r!==Object.prototype&&r!==null&&Ge("only plain objects are supported"),e.has(t)&&Ge("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Ge("symbol properties are not supported"),e.add(t);try{let i=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Ge("accessor properties are not supported"),`${JSON.stringify(o)}:${Nu(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Nu(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Ge("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Xx(t,e):Qx(t,e);case"bigint":case"function":case"symbol":case"undefined":return Ge(`${typeof t} values are not supported`)}return Ge("unsupported value type")}function ku(t){return Nu(t,new Set)}function K(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return Yx("sha256").update(`${t}
|
|
187
|
+
${ku(e)}`).digest("hex")}var J=S(()=>{"use strict"});function Su(t,e,r,i=""){let n=Object.keys(t),a=e.filter(s=>!Object.hasOwn(t,s)),o=n.filter(s=>!e.includes(s));if(a.length||o.length)throw new En({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...e]})}var En,Fo=S(()=>{"use strict";En=class extends Error{issues;constructor(e){let r=[e.missingFields.length?`missing: ${e.missingFields.join(", ")}`:"",e.unknownFields.length?`unknown: ${e.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${e.context} fields are invalid at ${e.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[e]}}});var xn=S(()=>{"use strict"});var Vo=S(()=>{"use strict";Fo();xn()});var qo,mr=S(()=>{"use strict";J();Vo();qo=3});import{existsSync as cC}from"node:fs";import Cn from"node:path";function Xm(t,e){let r=e.toLowerCase();return Object.entries(t).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function uC(t){let e=(Xm(t,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function dC(t,e,r){let n=Cn.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(Xm(e,"PATH")??"").split(Cn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Cn.win32.extname(t)?[t]:uC(e).map(s=>`${t}${s}`);return n.flatMap(s=>o.map(c=>s?Cn.join(s,c):Cn.resolve(r,c)))}function zo(t,e,r){return dC(t,e,r).find(i=>cC(i))??t}function Eu(t){if(t.some(e=>lC.test(e)))throw new Error("Windows batch check arguments must not contain shell syntax")}var lC,z0,Pn=S(()=>{"use strict";lC=/[&|<>()^%"!\r\n]/u,z0=["$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 pC,execFileSync as J0}from"node:child_process";import Qm from"node:path";async function Kt(t,e,r={}){let i=r.timeoutMs??fC,n=r.maxBufferBytes??hC;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Qm.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?zo(t,o,a):t,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&Eu(e);let l=()=>new Promise((u,d)=>{let p=!1,f=pC(s,[...e],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(w,y,k)=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),w?d(new Rn(t,e,k.trim(),{cause:w,timedOut:mC(w)})):u(y))}),m=w=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),f.kill("SIGKILL"),f.stdin?.destroy(),f.stdout?.destroy(),f.stderr?.destroy(),f.unref(),d(new Rn(t,e,"",{timedOut:w})))},h=()=>m(!1),v=setTimeout(()=>m(!0),i);r.signal?.addEventListener("abort",h,{once:!0}),r.signal?.aborted&&h(),f.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Qm.win32.basename(t))?su(l):l()}function mC(t){return t instanceof Error&&(t.code==="ETIMEDOUT"||t.killed===!0&&t.signal==="SIGTERM")}var fC,hC,Rn,Go=S(()=>{"use strict";Qr();Pn();fC=6e4,hC=8*1024*1024;Rn=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});function Pu(t,e){if(typeof t!="string"||!t.trim()||t.length>4e3||/^<[^>]+>$/u.test(t.trim()))throw new Error(`${e} must contain a concrete statement of at most 4000 characters`);return t.trim()}function Ru(t){if(!Array.isArray(t))throw new Error("Native Builder acceptance_review must be an array");return t.map((e,r)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Builder acceptance review entry must be an object");let i=e,n=`Native Builder acceptance_review[${r}]`;Su(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:Pu(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>Pu(o,`${n}.evidence`)),note:Pu(i.note,`${n}.note`)}})}function _u(t,e){if(!e)throw new si(t.map(({id:c})=>c),[]);let r=new Set(t.map(({id:c})=>c)),i=e.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=t.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=e.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new si(o,s)}var si,Jo=S(()=>{"use strict";Fo();si=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});import{promises as CC}from"node:fs";function pe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function fe(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Y(t,e,r){if(typeof t!="string"||!r?.empty&&t.length===0)throw new Error(`${e} must be ${r?.empty?"a string":"a non-empty string"}`);return t}function Au(t,e){return t===null?null:Y(t,e)}function Iu(t,e){let r=Y(t,e);if(!AC.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function ci(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function F(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function TC(t,e){return t===null?null:F(t,e,Number.MIN_SAFE_INTEGER)}function q(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function at(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((i,n)=>r(i,n))}function Xo(t,e){return at(t,e,(r,i)=>Y(r,`${e}[${i}]`))}function Sr(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function li(t,e){let r=Y(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function Uo(t,e,r=!1){let i=Y(t,e);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return i}function Ie(t,e){let r=pe(t,e);return fe(r,new Set(["text","truncated"]),e),{text:Y(r.text,`${e}.text`,{empty:!0}),truncated:ci(r.truncated,`${e}.truncated`)}}function jC(t,e){let r=`Native spec_changes[${e}]`,i=pe(t,r);fe(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=Y(i.capability,`${r}.capability`);if(!RC.test(n))throw new Error(`${r}.capability is invalid`);let a=q(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Uo(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Uo(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:Iu(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 $C(t){let e="Native workspace",r=pe(t,e);fe(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let i=q(r.isolation,["current","branch","worktree"],`${e}.isolation`),n=Au(r.change_branch,`${e}.change_branch`),a=Au(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:q(r.finish,["merge","push","pull-request","keep"],`${e}.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 OC(t){let e="Native loop",r=pe(t,e);fe(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"]),e);let i=Xo(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);Sr(i,`${e}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:q(r.stop_reason,["budget","stalled"],`${e}.stop_reason`);return{stage:q(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:F(r.goal_cycle,`${e}.goal_cycle`,1),iteration:F(r.iteration,`${e}.iteration`),attempt:F(r.attempt,`${e}.attempt`),retry_epoch:F(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:F(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:F(r.no_progress_count,`${e}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:F(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:i,next_action:Au(r.next_action,`${e}.next_action`)}}function HC(t,e){let r=`Native acceptance[${e}]`,i=pe(t,r);fe(i,new Set(["id","source","text","result","reason"]),r);let n=Y(i.id,`${r}.id`);if(!_C.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Uo(i.source,`${r}.source`),text:Y(i.text,`${r}.text`),result:q(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ie(i.reason,`${r}.reason`)}}function DC(t,e){let r=`Native builder_handoff.checks[${e}]`,i=pe(t,r);return fe(i,new Set(["name","result","note"]),r),{name:Ie(i.name,`${r}.name`),result:q(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ie(i.note,`${r}.note`)}}function LC(t){let e="Native builder_handoff",r=pe(t,e);fe(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"]),e);let i=Xo(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);Sr(i,`${e}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:pe(r.review,`${e}.review`);return n&&fe(n,new Set(["status","summary","reviewer_execution_ref"]),`${e}.review`),{candidate_id:Y(r.candidate_id,`${e}.candidate_id`),identity_provider:Y(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:Y(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:F(r.iteration,`${e}.iteration`,1),summary:Ie(r.summary,`${e}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:Ru(r.acceptance_review)},checks:at(r.checks,`${e}.checks`,DC),checks_truncated:ci(r.checks_truncated,`${e}.checks_truncated`),known_limits:at(r.known_limits,`${e}.known_limits`,(a,o)=>Ie(a,`${e}.known_limits[${o}]`)),known_limits_truncated:ci(r.known_limits_truncated,`${e}.known_limits_truncated`),review:n?{status:q(n.status,["passed"],`${e}.review.status`),summary:Ie(n.summary,`${e}.review.summary`),reviewer_execution_ref:Y(n.reviewer_execution_ref,`${e}.review.reviewer_execution_ref`)}:null,submitted_at:li(r.submitted_at,`${e}.submitted_at`)}}function BC(t,e){let r=`Native blockers[${e}]`,i=pe(t,r);fe(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Xo(i.acceptance_ids,`${r}.acceptance_ids`);return Sr(n,`${r}.acceptance_ids`),{owner:q(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ie(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:q(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function MC(t,e){let r=`Native verification.checks[${e}]`,i=pe(t,r);return fe(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:Y(i.id,`${r}.id`),name:Ie(i.name,`${r}.name`),argv_display:at(i.argv_display,`${r}.argv_display`,(n,a)=>Ie(n,`${r}.argv_display[${a}]`)),argv_truncated:ci(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Uo(i.cwd_ref,`${r}.cwd_ref`,!0),status:q(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:TC(i.exit_code,`${r}.exit_code`),duration_ms:F(i.duration_ms,`${r}.duration_ms`)}}function FC(t){let e="Native verification",r=pe(t,e);fe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let i=at(r.checks,`${e}.checks`,MC);Sr(i.map(a=>a.id),`${e}.checks IDs`);let n=Y(r.identity_provider,`${e}.identity_provider`);return{candidate_id:Y(r.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:Y(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:F(r.iteration,`${e}.iteration`,1),attempt:F(r.attempt,`${e}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":q(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:q(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:i,summary:Ie(r.summary,`${e}.summary`),risks:at(r.risks,`${e}.risks`,(a,o)=>Ie(a,`${e}.risks[${o}]`)),risks_truncated:ci(r.risks_truncated,`${e}.risks_truncated`),completed_at:li(r.completed_at,`${e}.completed_at`)}}function VC(t,e){let r=`Native history[${e}]`,i=pe(t,r);fe(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Xo(i.unresolved_ids,`${r}.unresolved_ids`);return Sr(n,`${r}.unresolved_ids`),{goal_cycle:F(i.goal_cycle,`${r}.goal_cycle`,1),iteration:F(i.iteration,`${r}.iteration`),attempt:F(i.attempt,`${r}.attempt`),outcome:q(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ie(i.summary,`${r}.summary`),completed_at:li(i.completed_at,`${r}.completed_at`)}}function qC(t){let e="Native history_overflow.outcome_counts",r=pe(t,e),i=["pass","fail","blocked","execution-error","recovery"];return fe(r,new Set(i),e),{pass:F(r.pass,`${e}.pass`),fail:F(r.fail,`${e}.fail`),blocked:F(r.blocked,`${e}.blocked`),"execution-error":F(r["execution-error"],`${e}.execution-error`),recovery:F(r.recovery,`${e}.recovery`)}}function WC(t){let e="Native history_overflow",r=pe(t,e);fe(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let i=F(r.dropped_entries,`${e}.dropped_entries`),n=r.first_dropped_at===null?null:li(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:li(r.last_dropped_at,`${e}.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=qC(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 zC(t){let e=new Set(t.acceptance.map(r=>r.id));for(let r of t.loop.previous_unresolved_ids)if(!e.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);t.builder_handoff?.acceptance_review&&_u(t.acceptance,t.builder_handoff.acceptance_review);for(let r of t.blockers)for(let i of r.acceptance_ids)if(!e.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(t.builder_handoff){if(!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.builder_handoff.review?.reviewer_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function GC(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let r=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(r!==null&&t.loop.stage!==r)throw new Error(`Native status ${t.status} requires loop stage ${r}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function ui(t){let e=pe(t,"Native portable state");if(fe(e,IC,"Native portable state"),e.schema!==ri)throw new Error(`Native portable state schema must be ${ri}`);let r=Y(e.name,"Native state name");if(!PC.test(r))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=at(e.spec_changes,"Native spec_changes",jC);Sr(i.map(s=>s.capability),"Native spec change capabilities");let n=at(e.acceptance,"Native acceptance",HC);Sr(n.map(s=>s.id),"Native acceptance IDs");let a=at(e.history,"Native history",VC);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ri,name:r,language:q(e.language,["en","zh-CN"],"Native state language"),phase:q(e.phase,["shape","build","verify","archive"],"Native state phase"),status:q(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:F(e.state_version,"Native state_version",1),brief:"brief.md",...e.document_constraints_version===void 0?{}:e.document_constraints_version===1||e.document_constraints_version===2?{document_constraints_version:e.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1 or 2")})(),...e.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Iu(e.shape_confirmation_hash,"Native Shape confirmation hash")},...e.children_contract_hash===void 0?{}:{children_contract_hash:Iu(e.children_contract_hash,"Native children contract hash")},...e.coordination_mode===void 0?{}:{coordination_mode:q(e.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:$C(e.workspace),loop:OC(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:LC(e.builder_handoff),blockers:at(e.blockers,"Native blockers",BC),verification:e.verification===null?null:FC(e.verification),history:a,history_overflow:WC(e.history_overflow),verification_result:q(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:q(e.verification_report,["verification.md"],"Native verification_report"),archived:ci(e.archived,"Native archived"),created_at:li(e.created_at,"Native created_at")};return zC(o),GC(o),o}function sv(t){let e=t.createdAt instanceof Date?t.createdAt.toISOString():t.createdAt??new Date().toISOString();return ui({schema:ri,name:t.name,language:t.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:t.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:t.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:bu(),verification_result:"pending",verification_report:null,archived:!1,created_at:e})}function KC(t,e){let r=(0,Yo.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Tu(t){let e=await CC.readFile(t,"utf8");return ui(KC(e,"Native portable state"))}async function cv(t,e,r={}){let i=ui(e);await ee(t,(0,Yo.stringify)(i),r)}var Yo,PC,RC,_C,AC,IC,Yt=S(()=>{"use strict";Jo();Yo=At(mt(),1);B();Sn();PC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,RC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_C=/^A[1-9][0-9]*$/u,AC=/^[a-f0-9]{64}$/u,IC=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 UP(t,e){return Ku[t][e]}function Dn(t,e={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return e.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${UP(t,i)}
|
|
188
188
|
`).join(`
|
|
189
|
-
`)}var
|
|
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
|
-
|
|
189
|
+
`)}var Ku,GP,KP,JP,Iv,Rr=S(()=>{"use strict";Ku={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:"验证预期"}},GP={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:"结论"}},KP={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:"结论"}},JP=new Map,Iv=new Map;for(let t of Object.keys(Ku)){for(let[e,r]of Object.entries(Ku[t]))JP.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(GP[t]))Iv.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(KP[t]))Iv.set(r.toLocaleLowerCase("en-US"),e)}});import{createHash as Uu,randomUUID as YP}from"node:crypto";import{promises as xe}from"node:fs";import XP from"node:os";import we from"node:path";async function Ju(t,e){let r=await xe.lstat(t,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(e))throw new Error("Invalid process probe cache");let i=await xe.readFile(t),n=await xe.lstat(t,{bigint:!0});if(r.ino!==n.ino||r.ctimeNs!==n.ctimeNs||r.size!==n.size)throw new Error("Process probe cache changed");return i}async function $v(t){try{let e=JSON.parse((await Ju(we.join(t,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(e.file??""))return null;let r=we.join(t,e.file),i=await Ju(r,65536);return Uu("sha256").update(i).digest("hex")===e.hash?r:null}catch{return null}}async function eR(t,e){let r,i=YP(),n=we.join(t,`probe-${i}.cs`),a=we.join(t,`probe-${i}.exe`),o=we.join(t,`probe-${i}.json`);try{if(await xe.mkdir(t,{recursive:!0,mode:448}),(await xe.lstat(t)).isSymbolicLink())return null;r=await xe.open(we.join(t,"prepare.lock"),"wx",384);let s=await $v(t);if(s)return s;await xe.writeFile(n,jv,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=we.join(e,"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}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=Uu("sha256").update(await Ju(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(t,"probe.json")),a}catch{return null}finally{await xe.unlink(n).catch(()=>{}),await xe.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await xe.unlink(we.join(t,"prepare.lock")).catch(()=>{}))}}async function Tv(t,e,r){try{let i=await Kt(we.join(e,"System32","wbem","WMIC.exe"),["process","where",`processid=${t}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),n=/^CreationDate=(\S+)/mu.exec(i);if(n)return`win32-wmic:${n[1]}`}catch{}if(r.aborted)return null;try{let n=(await Kt(we.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${t} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function tR(t,e){let r=is.get(t);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:eR(t,e),retryAfter:1/0};return is.set(t,i),i.promise.then(n=>{is.get(t)===i&&(n?is.delete(t):i.retryAfter=performance.now()+ZP)}),i.promise}async function Ov(t,e={}){if(!Number.isSafeInteger(t)||t<=0)return null;let r=e.systemRoot??process.env.SystemRoot??"C:\\Windows",i=we.join(e.cacheRoot??we.join(XP.tmpdir(),"comet-process-identity"),QP),n=async l=>{if(!l)return null;try{let d=(await Kt(l,[String(t)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await $v(i);if(a){let l=await n(a);return l||Tv(t,r,new AbortController().signal)}let o=tR(i,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(n).then(c),Tv(t,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var jv,QP,ZP,is,Hv=S(()=>{"use strict";Go();jv=`using System;
|
|
190
|
+
using System.Runtime.InteropServices;
|
|
191
|
+
class CometProcessIdentity {
|
|
192
|
+
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
|
193
|
+
[DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
|
|
194
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
|
195
|
+
static int Main(string[] args) {
|
|
196
|
+
int pid; if(args.Length != 1 || !int.TryParse(args[0], out pid) || pid <= 0) return 1;
|
|
197
|
+
IntPtr handle=OpenProcess(0x1000, false, pid); if(handle == IntPtr.Zero) return 1;
|
|
198
|
+
try { long creation, exit, kernel, user; if(!GetProcessTimes(handle,out creation,out exit,out kernel,out user)) return 1;
|
|
199
|
+
Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
|
|
200
|
+
} finally { CloseHandle(handle); }
|
|
201
|
+
}
|
|
202
|
+
}`,QP=Uu("sha256").update(jv).digest("hex"),ZP=1e4,is=new Map});import{promises as Dv}from"node:fs";function iR(t){let e=Xu.get(t);if(e){if(Date.now()-e.at>rR){Xu.delete(t);return}return e.value}}async function Ln(t){if(t===process.pid&&Yu!==null)return Yu;let e=iR(t);if(e!==void 0)return e;let r=ns.get(t);r||(r=nR(t),ns.set(t,r));let i=await r;return ns.get(t)===r&&ns.delete(t),t===process.pid&&i!==null&&(Yu=i),i===null&&Xu.set(t,{value:null,at:Date.now()}),i}async function nR(t){if(!Number.isSafeInteger(t)||t<=0)return null;try{if(process.platform==="linux"){let[e,r]=await Promise.all([Dv.readFile(`/proc/${t}/stat`,"utf8"),Dv.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=e.slice(e.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await Ov(t);if(process.platform==="darwin"){let e=(await Kt("/bin/ps",["-p",String(t),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return e?`darwin:${e}`:null}}catch{}return null}function as(t){let e=t.indexOf(":");return e===-1?"":t.slice(0,e)}async function Qu(t,e){if(!Number.isSafeInteger(t)||t<=0)return"alive";try{process.kill(t,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!e)return"unknown";let r=await Ln(t);return r===e?"alive":r===null||as(r)!==as(e)&&Lv.has(as(r))&&Lv.has(as(e))?"unknown":"dead"}var Yu,rR,Xu,ns,Lv,os=S(()=>{"use strict";Go();Hv();Yu=null,rR=1e4,Xu=new Map,ns=new Map;Lv=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as aR}from"async_hooks";import{randomUUID as Fv}from"crypto";import{promises as je}from"fs";import Vv from"os";import M from"path";function cR(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function lR(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let r=t;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: ${e}`);return r}function qv(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function cs(t,e){let r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return et(r,i)?H(r,i):H(r,i)&&t.size===e.size}function Bn(t,e){return cs(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}function uR(t,e){return t.status!==e.status?!1:!t.owner||!t.identity||!e.owner||!e.identity?t.owner===e.owner&&t.identity===e.identity:t.owner.id===e.owner.id&&Bn(t.identity,e.identity)}async function $e(t){let e,r;try{let i=await Gr(t,Bv,{bigint:!0,label:"Native lock"});e=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Be?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Bv} bytes: ${t}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:i}):new Error(`Native lock changed while reading: ${t}`,{cause:i}):i}return{file:t,owner:lR(JSON.parse(e.toString("utf8")),t),identity:qv(r)}}async function dR(t){return(await $e(t))?.owner??null}async function ed(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Vv.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=await Qu(t.owner.pid,t.owner.processIdentity);return{status:e==="alive"?"active":e==="dead"?"stale":"unknown",owner:t.owner,identity:t.identity}}async function pR(t,e){try{await je.lstat(e);return}catch(r){if(r.code!=="ENOENT")throw r}try{await je.rename(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function ls(t,e){let r=await $e(t.file);if(!r)return"missing";if(r.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Bn(r.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await je.mkdir(e,{recursive:!0});let i=M.join(e,`${M.basename(t.file)}.${t.owner.id}.${Fv()}.removed`);try{await je.rename(t.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await $e(i);if(!n||n.owner.id!==t.owner.id||!cs(n.identity,t.identity))throw await pR(i,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await je.rm(i,{force:!0}),"removed"}async function Wv(t){let e=await Ln(process.pid);return{id:Fv(),pid:process.pid,hostname:Vv.hostname(),createdAt:new Date().toISOString(),operation:t,...e===null?{}:{processIdentity:e}}}async function zv(t,e){let r;try{r=await je.open(t,"wx")}catch(a){if(a.code==="EEXIST"){let o=await dR(t);throw new Error(`Native lock is already held: ${t}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(e,null,2)+`
|
|
203
|
+
`,"utf8"),await r.sync(),i=qv(await r.stat({bigint:!0}))}finally{await r.close()}let n=await $e(t);if(!i||!n||n.owner.id!==e.id||!cs(n.identity,i))throw new Error(`Native lock changed after write: ${t}`);return n.identity}async function fR(t,e){let r=await j(t.runtimeDir,t.locksDir);await je.mkdir(r,{recursive:!0});let i=await j(t.runtimeDir,M.join(r,Zu));await je.mkdir(i,{recursive:!0});let n=await Wv(e),a=M.join(i,`.${n.id}.tmp`),o=M.join(i,`${n.id}.claim`);try{let s=await zv(a,n);await je.rename(a,o);let c=await $e(o);if(!c||!cs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await je.rm(a,{force:!0})}}async function hR(t){let e=M.dirname(t.file),r=!1,i=M.basename(t.file);for(let n of await je.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=M.join(e,n.name);if(M.resolve(a)!==M.resolve(t.file))try{let o=await $e(a),s=await ed(o);if(s.status==="missing")continue;let c=await $e(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Bn(c.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await ls(o,e);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Gv(t){let e=await $e(t.file);if(e){if(e.owner.id!==t.owner.id||!Bn(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await ls(e,M.dirname(t.file))}}async function mR(t,e){let r=Date.now()+oR;for(;;){let i=await fR(t,e);if(!await hR(i))return i;if(await Gv(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function vR(t){let e=ss.get(t)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=e.then(()=>i);return ss.set(t,n),await e,()=>{r(),ss.get(t)===n&&ss.delete(t)}}async function us(t,e,r){let i=M.resolve(t.locksDir),n=Mv.getStore();if(n?.has(i))return r();let a=await vR(i);try{let o=await mR(t,e),s=new Map(n??[]);return s.set(i,o),await Mv.run(s,async()=>{try{return await r()}finally{await Gv(o)}})}finally{a()}}async function Kv(t,e,r){let i=[...new Map(t.map(a=>[M.resolve(a.locksDir),a])).values()].sort((a,o)=>M.resolve(a.locksDir).localeCompare(M.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?us(o,e,()=>n(a+1)):r()};return n(0)}async function ds(t,e,r){return us(t,`acquire ${e}`,async()=>{let i=await j(t.runtimeDir,t.locksDir);await je.mkdir(i,{recursive:!0});let n=await j(t.runtimeDir,M.join(i,cR(e))),a=await Wv(r),o=await zv(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:i,owner:a,identity:o}})}async function ps(t){await $e(t.file)&&await us({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${M.basename(t.file)}`,async()=>{let e=await $e(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Bn(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=M.join(t.locksDir,Zu);await ls(e,r)})}function gR(t,e=Date.now()){if(!t)return 0;let r=Date.parse(t.createdAt);return Number.isFinite(r)?Math.max(0,e-r):Number.POSITIVE_INFINITY}async function Jv(t){return ed(await $e(t))}async function Uv(t,e,r,i={}){return us(t,`take over ${M.basename(e)}`,async()=>{let n=await j(t.runtimeDir,t.locksDir),a=await j(t.runtimeDir,e);if(M.resolve(M.dirname(a))!==M.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${e}`);let o=await $e(a),s=await ed(o);if(s.status==="missing")return{status:"missing"};if(r&&!uR(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&gR(o?.owner??null)>=sR;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=M.join(n,Zu);return await ls(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Bv,Zu,oR,sR,Mv,ss,Mn=S(()=>{"use strict";dn();os();L();rt();Bv=16*1024,Zu=".coordinator",oR=5e3,sR=900*1e3,Mv=new aR,ss=new Map});var ct,St,Et,Fn=S(()=>{"use strict";ct="comet.native.v3",St="comet.native.v2",Et="comet.native.v1"});import wR from"node:path";function qn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Zv(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function hi(t){if(!Qv.test(t))throw new Error(`Invalid Native change name: ${t}`)}function eg(t){if(!Qv.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function tg(t,e){if(t.length===0||wR.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function CR(t,e){let r=qn(t,`spec_changes[${e}]`);if(Zv(r,NR,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(eg(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"&&tg(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"||!rd.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"||!rd.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 PR(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function id(t,e){if(Zv(t,e,Je),typeof t.name!="string")throw new Error("Native change name is required");if(hi(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!kR.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!SR.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let r=t.spec_changes.map(CR),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 t.verification_result!="string"||!ER.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&tg(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!PR(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:r,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Wn(t){let e=qn(t,Je);if(e.schema!==Et)throw new Error(`Expected ${Et}`);return{schema:Et,...id(e,yR)}}function Vn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function td(t,e,r){if(t===null)return null;let i=typeof t=="string"?xR.exec(t):null;if(!i||i[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function RR(t){if(t==null)return null;if(typeof t!="string"||!rd.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function _R(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function zn(t){let e=qn(t,Je);if(e.schema!==St)throw new Error(`Expected ${St}`);if(Vn(e.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:Vn(e.revision,"Native v2 revision"),...id(e,Xv)}}function mi(t){let e=qn(t,Je);if(e.schema!==ct){if(e.schema===Et||e.schema===St){let o=e.schema===Et?Wn(e):zn(e);throw new fi(o.name,o.schema)}throw new Ct(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=Vn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Ct(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let i=Vn(e.revision,"Native revision"),n=id(e,bR),a=RR(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ct,minimum_runtime_version:3,revision:i,verification_protocol:_R(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:td(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:td(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:td(e.partial_allowance,"Native partial_allowance","allowances")}}function fs(t){let e=qn(t,Je);if(e.schema===Et){let n=Wn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ct}`}}if(e.schema===St){let n=zn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ct}`}}if(e.schema!==ct){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Ct(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let r=Vn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new Ct(e.schema,r).message};let i=mi(e);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Yv,yR,Xv,bR,NR,kR,SR,ER,Je,rd,Qv,xR,fi,Ct,hs=S(()=>{"use strict";Fn();Yv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],yR=new Set(Yv),Xv=new Set([...Yv,"minimum_runtime_version","revision"]),bR=new Set([...Xv,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),NR=new Set(["capability","operation","source","base_hash"]),kR=new Set(["shape","build","verify","archive"]),SR=new Set(["implicit","confirmed"]),ER=new Set(["pending","pass","fail"]),Je="comet-state.yaml",rd=/^[a-f0-9]{64}$/u,Qv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,fi=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"},Ct=class extends Error{constructor(r,i){super(r!==ct||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 gH,rg,ms=S(()=>{"use strict";Rr();J();gH=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),rg=Object.freeze({maxCriteria:1024})});var nd=S(()=>{"use strict";ms()});var _r=S(()=>{"use strict"});function LR(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function BR(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let r=new Date(t);if(Number.isNaN(r.valueOf())||r.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function ng(t){let e=LR(t,"Native portable migration transaction"),r=Object.keys(e).filter(i=>!jR.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==ig)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!OR.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!$R.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!DR.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!HR.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:ig,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:BR(e.createdAt,"Native portable migration transaction createdAt")}}var ig,jR,$R,OR,HR,DR,ag=S(()=>{"use strict";hs();nd();Yt();_r();Sn();Fn();ig="comet.native.portable-migration.v1",jR=new Set(["schema","id","change","fromSchema","status","createdAt"]),$R=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OR=/^[a-z0-9][a-z0-9-]{7,127}$/u,HR=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),DR=new Set([Et,St,ct])});import MR from"node:path";function ug(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function dg(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ad(t,e){if(t!==void 0){if(t===null)return null;if(typeof t!="string"||!/^[a-f0-9]{64}$/iu.test(t))throw new Error(`${e} must be a SHA-256 hash or null`);return t.toLowerCase()}}function sg(t,e){if(t!==void 0){if(t!==null&&typeof t!="string")throw new Error(`${e} must be text or null`);return t}}function JR(t,e){let r=`Native portable Archive spec_changes[${e}]`,i=ug(t,r);if(dg(i,KR,r),typeof i.capability!="string"||!lg.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(p=>p==="."||p==="..")))throw new Error(`${r}.delta_source is invalid`);let o=ad(i.base_hash,`${r}.base_hash`),s=sg(i.delta_content,`${r}.delta_content`),c=sg(i.source_content,`${r}.source_content`),l=ad(i.expected_target_hash,`${r}.expected_target_hash`),u=ad(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 p=$o(s);if(p.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(p.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(zt(i.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(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(p=>p==="."||p===".."))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||zt(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 UR(t){let e=ug(t,"Native portable Archive transaction");if(dg(e,GR,"Native portable Archive transaction"),e.schema!==og)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!qR.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!lg.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!WR.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!zR.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=e.spec_changes.map(JR);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(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(e.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:og,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:r,created_at:e.created_at}}function od(t){let e=FR.exec(t);if(e)return{kind:"archive",change:e[1]};let r=VR.exec(t);return r?{kind:"migration",change:r[1]}:null}async function pg(t,e){let r=od(e);if(!r)return null;let i=await ue({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=MR.join(t.transactionsDir,e);if(r.kind==="archive"){let s=UR(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=ng(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 fg(t){return t.kind==="archive"||t.journal.status!=="committed"}var og,cg,FR,VR,qR,WR,zR,GR,KR,lg,sd=S(()=>{"use strict";Ae();Ho();ag();og="comet.native.archive-transaction.v4",cg="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",FR=new RegExp(`^portable-archive-(${cg})\\.json$`,"u"),VR=new RegExp(`^portable-migration-(${cg})\\.json$`,"u"),qR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,WR=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zR=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),GR=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),KR=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),lg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as YR}from"node:crypto";import{constants as vs,promises as Ce}from"node:fs";import Ue from"node:path";import{TextDecoder as XR}from"node:util";function ws(t,e){let r=Ue.relative(t,e);return r===""||!Ue.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ue.sep}`)}function hg(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function QR(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function ZR(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function gs(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function cd(t,e){let r=await Ce.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await Ce.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function mg(t,e,r){let i=Ue.resolve(t),n=Ue.resolve(e);if(!ws(i,n))throw new Error(`${r} is outside its managed root`);let a=[await cd(i,r)],o=i;for(let s of Ue.relative(i,n).split(Ue.sep).filter(Boolean)){await Pt(a,r),o=Ue.join(o,s);let c=await cd(o,r);if(!ws(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(t,e){for(let r of t){let i=await Ce.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!QR(r,i)||await Ce.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function e_(t,e,r){let i=[],n=0,a=Buffer.allocUnsafe(e===null?64*1024:Math.min(64*1024,e+1));for(;;){let o=e===null?a.length:e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,e!==null&&n>e)throw new Error(`${r} exceeds ${e} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function vi(t){let e=t.maxBytes===null?null:hg(t.maxBytes),r=Ue.resolve(t.file),i=await mg(t.root,Ue.dirname(r),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(u=>cd(Ue.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Pt(i,t.label);let a=await Ce.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(e!==null&&a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=ZR(a),s=await Ce.realpath(r);if(!ws(i[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(u=>ws(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?vs.O_RDONLY:vs.O_RDONLY|vs.O_NOFOLLOW|vs.O_NONBLOCK,l=await Ce.open(r,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[d,p]=await Promise.all([Ce.lstat(r),Ce.realpath(r)]);if(await Pt(i,t.label),await Pt(n,t.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!gs(o,u)||!gs(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let f=await e_(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),Ce.lstat(r),Ce.realpath(r)]);if(await Pt(i,t.label),await Pt(n,t.label),!h.isFile()||h.isSymbolicLink()||v!==s||!gs(o,m)||!gs(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:f,hash:YR("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function vg(t){let e=await vi(t),r;try{r=new XR("utf-8",{fatal:!0}).decode(e.bytes)}catch(i){throw new Error(`${t.label} is not valid UTF-8`,{cause:i})}return{...e,text:r}}async function Kn(t){let e=await mg(t.root,t.directory,t.label),r;if(t.maxEntries===void 0)r=await Ce.readdir(t.directory,{withFileTypes:!0});else{let i=hg(t.maxEntries);r=[];let n=await Ce.opendir(t.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${t.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Pt(e,t.label),{entries:r,verify:()=>Pt(e,t.label)}}var lt=S(()=>{"use strict";B();rt()});import Rt from"path";import{TextDecoder as r_}from"util";function bs(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ns(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function bg(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function ld(t,e){if(typeof t!="string"||t.length===0||Rt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function ys(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function gg(t,e){if(ld(t,e),t.includes("\\")||t!==Rt.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function c_(t,e){let r=bs(t,`transaction operations[${e}]`);if(Ns(r,n_,`transaction operations[${e}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${e}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);ld(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ld(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 Ng(t){let e=bs(t,"Native Archive transaction journal");if(Ns(e,a_,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!yg.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!bg(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ys(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=e.operations.map((s,c)=>{let l=bs(s,`Archive transaction operations[${c}]`);if(Ns(l,o_,`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`);gg(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&gg(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&ys(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(ys(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`);ys(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/${e.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||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:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:r}}function l_(t){let e=bs(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Ng(e);if(Ns(e,i_,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!yg.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Rt.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Rt.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!bg(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let r=e.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:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:r}}function u_(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Rt.join(t.transactionsDir,e)}function kg(t,e){let r=u_(t,e);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 ud(t,e){let r=kg(t,e);return await Promise.all(Object.values(r).map(i=>j(t.runtimeDir,i))),r}async function dd(t,e,r={}){let i=await ud(t,e),n=await vi({root:t.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(s_.decode(n.bytes)),o=l_(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}var i_,n_,a_,o_,yg,s_,ks=S(()=>{"use strict";B();L();lt();i_=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),n_=new Set(["id","type","source","target","staged","backup"]),a_=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),o_=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),yg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),s_=new r_("utf-8",{fatal:!0})});import{promises as d_}from"fs";import p_ from"path";async function f_(t,e,r){let i;try{i=await d_.readdir(t.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 dd(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(od(n.name))try{let a=await pg(t,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(fg(a))return!0}catch{return!0}return!1}async function h_(t,e){let r=Date.now()+5e3,i=p_.join(t.locksDir,"root-move.lock");for(;;)try{return await ds(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Jv(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Uv(t,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 X(t,e,r,i){let n=await h_(t,e);try{if(await Eo(t.projectRoot),await f_(t,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await ps(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
|
|
204
|
+
`)}}}var ie=S(()=>{"use strict";ke();Mn();sd();ks()});import{createHash as m_}from"crypto";function Pe(t){return m_("sha256").update(t).digest("hex")}var ut=S(()=>{"use strict"});import fd from"path";function Ss(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function O_(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function H_(t,e){return Pe(`comet.native.snapshot-policy.v1
|
|
205
|
+
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function pd(t,e,r){let i=new Set(e),n=[...e];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=t[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 D_(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Sg(t){let e=So(t,"Native snapshot pattern"),r=[];for(let i=0;i<e.length;i+=1){let n=e[i];n==="*"&&e[i+1]==="*"?(i+=1,e[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?D_(n):void 0;if(a&&!a())return!1;let o=pd(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=pd(r,c,a),o===null||o.size===0)return!1}return pd(r,o,a)?.has(r.length)??!1}}function L_(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>So(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(t.exclude.map(n=>So(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let i=H_(e,r);if("hash"in t&&t.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:i},includeMatchers:e.map(Sg),excludeMatchers:r.map(Sg),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 Oe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function He(t,e,r){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function wi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function dt(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Cg(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let r=fd.posix.normalize(t);if(r!==t||fd.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function B_(t,e){let r=Oe(t,`Native snapshot entry ${e}`);He(r,R_,`Native snapshot entry ${e}`);let i=Cg(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!Es.test(r.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:i,hash:r.hash,size:dt(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!$_.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function M_(t,e){let r=Oe(t,`Native snapshot omission ${e}`);if(He(r,__,`Native snapshot omission ${e}`),!T_.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!j_.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Cg(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:dt(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function F_(t){let e=Oe(t,"Native snapshot omission overflow");if(He(e,A_,"Native snapshot omission overflow"),typeof e.hash!="string"||!Es.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:e.hash,count:wi(e.count,"Native snapshot omission overflow count")}}function gi(t,e){let r=Oe(t,e);if(He(r,x_,e),typeof r.hash!="string"||!Es.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let i=dt(r.recordCount,`${e} recordCount`),n=dt(r.storedRecordCount,`${e} storedRecordCount`),a=dt(r.stdoutBytes,`${e} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Eg(t){let e=Oe(t,"Native Git selection evidence");if(He(e,E_,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=gi(e.stageBefore,"Native Git selection stageBefore"),i=gi(e.combined,"Native Git selection combined"),n=gi(e.stageAfter,"Native Git selection stageAfter"),a=gi(e.finalStageBefore,"Native Git selection finalStageBefore"),o=gi(e.finalCombined,"Native Git selection finalCombined"),s=gi(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Ss(r,n)||!Ss(n,a)||!Ss(i,o)||!Ss(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(e.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 xg(t,e){let r=Oe(t,e);if(He(r,P_,e),typeof r.hash!="string"||!Es.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${e} flags are invalid`);let i=dt(r.visitedNodeCount,`${e} visitedNodeCount`),n=dt(r.recordCount,`${e} recordCount`),a=dt(r.storedRecordCount,`${e} storedRecordCount`),o=dt(r.encodedBytes,`${e} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function V_(t){let e=Oe(t,"Native physical selection evidence");if(He(e,C_,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=xg(e.before,"Native physical selection before"),i=xg(e.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!O_(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(e.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 Pg(t){let e=Oe(t,"Native content snapshot manifest");if(He(e,y_,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!I_.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let g=Oe(e.capture,"Native content snapshot capture");if(He(g,k_,"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:Eg(g.gitSelection),b=g.physicalSelection===void 0?void 0:V_(g.physicalSelection),T=null;if(g.projection!==void 0){let ne=Oe(g.projection,"Native content snapshot projection");if(He(ne,S_,"Native content snapshot projection"),ne.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");T={provider:"git",...ne.selection===void 0?{}:{selection:Eg(ne.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 e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=Oe(e.limits,"Native content snapshot limits");He(i,b_,"Native content snapshot limits");let n={maxFiles:wi(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:wi(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:wi(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:wi(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:wi(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=Oe(e.policy,"Native snapshot policy");if(He(g,N_,"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=L_({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(B_),s=e.omitted.map(M_),c=dt(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:F_(e.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,_)=>g+_.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>g_||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(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(g=>g.reason==="git-enumeration-limit"),p=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...p])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||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=f?.status==="overflow"||f?.status==="overflow-and-changed",h=f?.status==="changed"||f?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(p.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:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}function q_(t,e){if(!w_.test(e))throw new Error(`Invalid Native change name: ${e}`);return fd.join(Ne(t,e),"baseline-manifest.json")}async function Rg(t,e){let r=q_(t,e),i=qe(t,r);await j(i,r);try{let n=await vg({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return Pg(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var vD,g_,w_,y_,b_,N_,k_,S_,E_,x_,C_,P_,R_,__,A_,I_,T_,j_,Es,$_,gD,wD,yD,bD,ND,Jn=S(()=>{"use strict";Qr();B();ke();ut();rt();L();lt();vn();vD={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},g_=1e3,w_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,y_=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),b_=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),N_=new Set(["schema","include","exclude","hash"]),k_=new Set(["provider","gitSelection","physicalSelection","projection"]),S_=new Set(["provider","selection"]),E_=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),x_=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),C_=new Set(["schema","status","before","after"]),P_=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),R_=new Set(["path","hash","size","type","gitObjectId"]),__=new Set(["path","size","type","reason"]),A_=new Set(["ref","hash","count"]),I_=new Set(["change-created","legacy-migration","explicit"]),T_=new Set(["file","directory","other"]),j_=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"]),Es=/^[a-f0-9]{64}$/u,$_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,gD=64*1024,wD=64*1024,yD={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},bD={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};ND=(1n<<256n)-1n});var _A,$s=S(()=>{"use strict";_A=At(mt(),1);Ae()});var rr=S(()=>{"use strict";B();J();$s();L();mr()});var xd=S(()=>{"use strict"});var Ar=S(()=>{"use strict"});var Os=S(()=>{"use strict";Pn();xd();Ar()});var Kg=S(()=>{"use strict";ze();Os();J()});import{createHash as HA}from"node:crypto";import{lstatSync as kB,readFileSync as SB,promises as Jg}from"node:fs";import Cd from"node:path";async function Hs(t){let e=Cd.join(t,DA),r;try{r=await Jg.readFile(e)}catch(n){if(n.code==="ENOENT")return;throw n}let i=LA(t);await Jg.mkdir(Cd.dirname(i),{recursive:!0}),await ae(i,{hash:BA(r)},{containedRoot:t})}var DA,LA,BA,Ds=S(()=>{"use strict";ze();B();DA=".comet/config.yaml",LA=t=>Cd.join(t,".comet","runtime","native","workspace-config.json"),BA=t=>HA("sha256").update(t).digest("hex")});var rw,Ei=S(()=>{"use strict";J();Jn();rw=1024*1024});var Bs=S(()=>{"use strict";J();Ar();vn();Ei()});var nw,sI,cI,lI,EF,uI,xF,_d=S(()=>{"use strict";J();nw="scoped-text-safety",sI=1,cI=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),lI="comet.native.checker-policy.v1",EF=K(lI,{policy:nw,version:sI,limits:cI,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),uI=["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"],xF=new Set(uI)});var Ms=S(()=>{"use strict";J();_d();Ar()});var fI,VF,xi=S(()=>{"use strict";B();L();rt();Ei();Bs();Ms();fI=rw,VF=3*fI});ke();B();import{promises as mT}from"node:fs";import Gs from"node:path";var Xl=At(mt(),1);tt();import{createHash as hE}from"node:crypto";import mE from"node:path";var Jl={strong:8,phrase:8,weak:12},Qh=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(" ")),Po=new Set(["请","帮我","一下","这个","进行","实现","需要","如何"]);function Ro(t,e=2e3){return[...t].map(r=>{let i=r.codePointAt(0)??0;return i<32||i===127?" ":r}).join("").replace(/\s+/gu," ").trim().slice(0,e)}function dE(t){if(!t)return;let e=Ro(t,512).replaceAll("\\","/");if(!(!e||e.startsWith("/")||/^[A-Za-z]:\//u.test(e)||e.split("/").includes("..")))return e}function Ul(t){return t.replace(/(^|[\s([{"'])(?:[A-Za-z]:[\\/]|\\\\)[^\s)\]}>,;"']+/gu,"$1").replace(/(^|[\s([{"',;:])\/(?!\/)[^\s)\]}>,;"']+/gu,"$1").replace(/\s+/gu," ").trim()}function Se(t,e){let r=e.trim();r.length<2||t.includes(r)||t.push(r)}function xo(t,e,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(Po.has(s))continue;Se(t,s);let c="";for(let{segment:l,isWordLike:u}of a.segment(s))u&&!Po.has(l)&&Se(e,l),u&&l.length===1&&!"的和与给为在对及".includes(l)?(c&&Se(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);!Po.has(d)&&d!==s&&Se(i,d)}}for(let o of n)Se(e,o);for(let o of i)Se(e,o)}function Co(t,e,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(!Qh.has(a)&&(Se(pE(n)?t:e,n),n.includes("/")))for(let o of n.split(/[/:.]/u))Se(e,o)}for(let i of r.matchAll(/\b\d+(?:\.\d+)?\b/gu))Se(t,i[0])}function pE(t){return t.includes("/")||t.includes("\\")||t.includes("_")||/[a-z][A-Z]/u.test(t)||/[A-Z]{2,}/u.test(t)||/[A-Za-z][A-Za-z0-9]*\d[A-Za-z0-9]*/u.test(t)||/\d{2,}/u.test(t)||/(?:^|[^A-Za-z0-9])[A-Za-z0-9]+\.[A-Za-z0-9]+(?:$|[^A-Za-z0-9])/u.test(t)}function fE(t){return t.length>256||!/\s/u.test(t)?void 0:t.split(/\s+/u).filter(r=>{let i=r.toLowerCase();return r.length>=2&&!Qh.has(i)&&!Po.has(r)}).length>=2?t:void 0}function Zh(t){let e=Ro(t.task);if(!e)throw new Error("Project knowledge task must not be empty");let r=dE(t.path),i=t.phase?Ro(t.phase,128):void 0,n=t.operation?Ro(t.operation,128):void 0,a=[],o=[],s=[],c=[],l=[];Co(a,c,e),xo(o,l,e);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),Co(a,s,r),xo(o,s,r)),i&&(Co(a,s,i),xo(o,s,i)),n&&(Co(a,s,n),xo(o,s,n));let u=fE(e);u&&Se(o,u);let d=a.slice(0,Jl.strong),p=o.slice(0,Jl.phrase),f=s.filter(v=>!d.includes(v)&&!p.includes(v)).slice(0,Jl.weak),m=[...d,...p,...f],h=[Ul(e),...r?[`Target path: ${r}`]:[],...i?[`Phase: ${Ul(i)}`]:[],...n?[`Operation: ${Ul(n)}`]:[]].join(`
|
|
206
|
+
`);return{task:e,...r?{path:r}:{},...i?{phase:i}:{},...n?{operation:n}:{},terms:m,strongTerms:d,phraseTerms:p,weakTerms:f,remoteQuery:h}}function em(t,e){return t.toLocaleLowerCase().includes(e.toLocaleLowerCase())}var tm=5,_o=40,vE=5,gE=600,wE=256*1024,yE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;function Yl(t,e){let r=t.replaceAll("\\","/").replace(/^\.\//u,"").replace(/\/+$/u,"");if(!r||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${e} must be a project-relative path`);return r}function Ao(t,e){let r=t.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=e==="native"?yE:bE;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${e} capability: ${t}`);return i.join("/")}function NE(t,e){let r=e.replaceAll("\\","/").replace(/^\.\//u,""),i=`${Yl(t.currentSpecRoot,"current Spec root")}/`;if(r.startsWith(i)&&r.endsWith("/spec.md")){let s=r.slice(i.length,-8);try{return{kind:"current",capability:Ao(s,t.workflow),source:r}}catch{return null}}let n=`${Yl(t.archiveRoot,"archive root")}/`;if(!r.startsWith(n))return null;let a=r.slice(n.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:Ao(o,t.workflow),source:r}}catch{return null}}function kE(t,e){return`${Yl(t.currentSpecRoot,"current Spec root")}/${Ao(e,t.workflow)}/spec.md`}function SE(t){return hE("sha256").update(t.toString("utf8").replaceAll(`\r
|
|
194
207
|
`,`
|
|
195
208
|
`).replaceAll("\r",`
|
|
196
|
-
`)).digest("hex")}function
|
|
197
|
-
`),resultScore:
|
|
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
|
|
209
|
+
`)).digest("hex")}function EE(t){let e=typeof t.score=="number"&&Number.isFinite(t.score)?t.score:0,r={source:t.source,kind:t.document?.kind??"project-knowledge",...t.title?{title:t.title}:{},snippet:t.content.slice(0,gE),searchableText:[t.source,t.title??"",t.content,t.record?.summary??""].join(`
|
|
210
|
+
`),resultScore:e,resultRank:0},i=t.record?[...t.record.conclusions,...t.record.relations].flatMap(n=>n.sources):[];return[r,...i.map((n,a)=>({source:n.source,kind:"record-reference",searchableText:[n.source,t.title??"",t.content,t.record?.summary??""].join(`
|
|
211
|
+
`),resultScore:e,resultRank:a+1}))]}function xE(t,e,r){let i=`${e.workflow}\0${r}`,n=t.get(i);if(n)return n;let a={workflow:e.workflow,capability:r,historicalSources:new Set,matchedTerms:new Set,evidence:new Map,currentHits:0,historicalHits:0,bestScore:0,bestRank:Number.MAX_SAFE_INTEGER};return t.set(i,a),a}function CE(t,e){let r=e.terms.some(i=>i.toLocaleLowerCase()===t.capability.toLocaleLowerCase());return t.currentHits>0&&(t.matchedTerms.size>=2||r)?"high":t.currentHits>0?"medium":"low"}function PE(t,e){let r=t.currentHits>0?"当前总 Spec 已命中":"检索命中历史 change",i=t.historicalSources.size?`,并找到 ${t.historicalSources.size} 个历史来源`:"";return`${r}${i};已核对当前能力文件,匹配 ${t.matchedTerms.size} 个查询词(${e})`}function RE(t,e){let r=t.matchedTerms.size/Math.max(1,e.terms.length);return Math.min(1,(t.currentHits>0?.5:.15)+Math.min(.3,r*.3)+Math.min(.15,Math.max(0,t.bestScore)*.15)+Math.min(.05,t.historicalSources.size*.02))}function _E(t){return[...t.values()].sort((e,r)=>{let i=e.kind.endsWith("-spec")?0:1,n=r.kind.endsWith("-spec")?0:1;return i-n||e.source.localeCompare(r.source)}).slice(0,vE)}function rm(t,e,r){return{schema:"comet.capability-association.v1",status:r,workflow:t.workflow,capability:t.capability,current_spec:t.currentSpec.source,current_hash:t.currentSpec.hash,confidence:t.confidence,...e?{query:e.task}:{},reason:t.reason,historical_sources:[...t.historicalSources],evidence:t.evidence}}async function im(t,e,r){let i=kE(e,r),n=await Z(t,i,wE,{label:`${e.workflow} current capability Spec`});return{source:i,hash:SE(n.bytes)}}function nm(t,e,r,i){return{workflow:t.workflow,query:e,candidates:[],associationDraft:null,diagnostics:r,searched:i,providerLimit:_o}}async function am(t){let e=mE.resolve(t.projectRoot),r=[],i=t.capability?.trim();if(!i&&!t.task?.trim())throw new Error("Capability discovery requires task or capability");let n=t.task?.trim()?Zh({task:t.task.trim(),operation:"associate capability"}):null;if(i){let d=Ao(i,t.scope.workflow),p=await im(e,t.scope,d),f={workflow:t.scope.workflow,capability:d,currentSpec:p,historicalSources:[],matchedTerms:[d],confidence:"high",score:1,reason:"用户显式指定能力,已直接核对当前总 Spec 路径。",evidence:[{source:p.source,kind:`${t.scope.workflow}-spec`}]};return{workflow:t.scope.workflow,query:n,candidates:[f],associationDraft:rm(f,n,"explicit"),diagnostics:r,searched:!1,providerLimit:_o}}if(!t.provider)throw new Error("Capability discovery requires a Project Knowledge provider for task search");let a;try{a=await t.provider.query({kind:"search",query:n,limit:_o})}catch(d){return r.push({code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${d instanceof Error?d.message:String(d)}`}),nm(t.scope,n,r,!0)}if(a.kind!=="search")return nm(t.scope,n,a.diagnostics,!0);r.push(...a.diagnostics);let o=new Map;for(let[d,p]of a.results.entries())for(let f of EE(p)){let m=NE(t.scope,f.source);if(!m)continue;let h=xE(o,t.scope,m.capability),v=n.terms.filter(w=>em(f.searchableText,w));for(let w of v)h.matchedTerms.add(w);h.bestScore=Math.max(h.bestScore,f.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"?`${t.scope.workflow}-spec`:`${t.scope.workflow}-archive`,...f.title?{title:f.title}:{},...f.snippet?{snippet:f.snippet}:{}})}let s=Math.max(1,Math.min(tm,t.limit??tm)),c=[],l=[...o.values()].sort((d,p)=>p.currentHits-d.currentHits||p.matchedTerms.size-d.matchedTerms.size||p.bestScore-d.bestScore||d.bestRank-p.bestRank||d.capability.localeCompare(p.capability));for(let d of l.slice(0,s)){let p;try{p=await im(e,t.scope,d.capability)}catch(h){r.push({code:"capability-stale",message:`候选 ${d.capability} 没有可核对的当前总 Spec,已排除:${h instanceof Error?h.message:String(h)}`});continue}let f=CE(d,n),m={workflow:t.scope.workflow,capability:d.capability,currentSpec:p,historicalSources:[...d.historicalSources].sort(),matchedTerms:[...d.matchedTerms],confidence:f,score:RE(d,n),reason:PE(d,f),evidence:_E(d.evidence)};c.push(m)}c.sort((d,p)=>p.score-d.score||d.capability.localeCompare(p.capability));let u=c.length===1&&c[0].confidence==="high"?rm(c[0],n,"suggested"):null;return{workflow:t.scope.workflow,query:n,candidates:c,associationDraft:u,diagnostics:r,searched:!0,providerLimit:_o}}function om(t){return(0,Xl.stringify)({schema:t.schema,status:t.status,workflow:t.workflow,capability:t.capability,current_spec:t.current_spec,current_hash:t.current_hash,confidence:t.confidence,...t.query===void 0?{}:{query:t.query},reason:t.reason,historical_sources:[...t.historical_sources],evidence:t.evidence.map(e=>({source:e.source,kind:e.kind,...e.title===void 0?{}:{title:e.title},...e.snippet===void 0?{}:{snippet:e.snippet}}))})}Ae();Ho();tt();fr();import{createHash as jm}from"node:crypto";import{promises as ti}from"node:fs";import G from"node:path";ze();import{createHash as rx}from"node:crypto";import{AsyncLocalStorage as ix}from"node:async_hooks";import Lo from"node:path";function Bo(...t){if(t.length===0)return Lo.resolve();if(Lo.win32.isAbsolute(t[0])){let e=Lo.win32.resolve(...t);return process.platform==="win32"?e:e.replace(/\\/gu,"/")}return Lo.resolve(...t)}var nx=new ix;function ax(t,e){let r=Bo(t),i=e.runGit??re,n=nx.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=Bo(r,l))}catch{}}let c={identity:wm(s),name:cx(s)};if(a){let l=a.get(r)??new Map;l.set(i,c),a.set(r,l)}return c}function ox(t,e={}){return ax(t,e).identity}function sx(t){let e=wm(t),i=(e.split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project",n=rx("sha256").update(e,"utf8").digest("hex").slice(0,8);return`${i.slice(0,40)}-${n}`}function gm(t,e={}){return sx(ox(t,e))}function cx(t){return(t.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 wm(t){let e=t.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").toLocaleLowerCase();return e||"project"}var bt=class extends Error{code;constructor(e,r,i){super(r,i),this.name="BoundedHttpRequestError",this.code=e}};async function lx(t,e){if(!t.body){let s=new Uint8Array(await t.arrayBuffer());if(s.byteLength>e)throw new bt("response-too-large","HTTP response exceeds byte limit");return s}let r=t.body.getReader(),i=[],n=0;try{for(;;){let s=await r.read();if(s.done)break;if(n+=s.value.byteLength,n>e)throw await r.cancel(),new bt("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 ym(t){let e=new AbortController,r=setTimeout(()=>e.abort(),t.timeoutMs);try{let i=await(t.fetch??globalThis.fetch)(t.url,{...t.init,signal:e.signal}),n=i.ok?await lx(i,t.maxResponseBytes):new Uint8Array;return{response:i,bytes:n}}catch(i){throw i instanceof bt?i:e.signal.aborted?new bt("timeout","HTTP request timed out",{cause:i}):new bt("request-failed","HTTP request failed",{cause:i})}finally{clearTimeout(r)}}import bm from"node:path";var ux=/^[a-z0-9][a-z0-9._-]{1,127}$/u,Em=2e3,dx=1024,px=32,fx=32,hx=32,mx=16,vx=16,xm=32,gx=128,wx=32,yx=new Set(["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"]),bx=new Set(["trial","proven","enforced","superseded"]),Nx=new Set(["automatic","user","repository"]),kx=new Set(["contains","depends-on","consumes","registers","propagates-to","generated-by","validated-by","supersedes"]);function ei(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ee(t,e,r=Em){if(typeof t!="string"||t.trim().length===0||t.length>r)throw new Error(`${e} must be a non-empty string of at most ${r} characters`);return t.trim()}function du(t,e){let r=Ee(t,e,128);if(!ux.test(r))throw new Error(`${e} must use a stable record id`);return r}function Zr(t,e,r,i){if(t===void 0)return[];if(!Array.isArray(t)||t.length>r)throw new Error(`${e} must be a bounded list`);return t.map((n,a)=>i(n,a))}function Cm(t,e,r,i){if(!Array.isArray(t)||t.length===0||t.length>r)throw new Error(`${e} must be a non-empty bounded list`);return t.map((n,a)=>i(n,a))}function fu(t,e){let r=Ee(t,e,dx).replaceAll("\\","/");if(bm.posix.isAbsolute(r)||bm.win32.isAbsolute(r)||r.includes("\0")||r.split("/").some(i=>i===".."))throw new Error(`${e} must be a project-relative path`);return r}function Sx(t,e,r=px){return Zr(t,e,r,(i,n)=>fu(i,`${e}[${n}]`))}function Nm(t,e,r=fx){return Zr(t,e,r,(i,n)=>Ee(i,`${e}[${n}]`,512))}function pu(t,e,r=Em){if(t!==void 0)return Ee(t,e,r)}function km(t,e){if(!Number.isSafeInteger(t)||Number(t)<1)throw new Error(`${e} must be a positive integer`);return Number(t)}function wn(t,e){if(!Number.isSafeInteger(t)||Number(t)<0)throw new Error(`${e} must be a non-negative integer`);return Number(t)}function Pm(t,e){let r=ei(t,e),i=r.lineStart,n=r.lineEnd,a=i===void 0?void 0:km(i,`${e}.lineStart`),o=n===void 0?void 0:km(n,`${e}.lineEnd`);if(a!==void 0&&o!==void 0&&o<a)throw new Error(`${e}.lineEnd must be greater than or equal to lineStart`);let s=pu(r.anchor,`${e}.anchor`,256),c=pu(r.evidence,`${e}.evidence`,1024);return{source:fu(r.source,`${e}.source`),...s===void 0?{}:{anchor:s},...a===void 0?{}:{lineStart:a},...o===void 0?{}:{lineEnd:o},...c===void 0?{}:{evidence:c}}}function Ex(t,e){let r=ei(t,`conclusions[${e}]`);return{text:Ee(r.text,`conclusions[${e}].text`),sources:Cm(r.sources,`conclusions[${e}].sources`,xm,(i,n)=>Pm(i,`conclusions[${e}].sources[${n}]`))}}function xx(t,e){let r=ei(t,`relations[${e}]`),i=Ee(r.type,`relations[${e}].type`,64);if(!kx.has(i))throw new Error(`relations[${e}].type is unsupported`);return{type:i,targetId:du(r.targetId,`relations[${e}].targetId`),sources:Cm(r.sources,`relations[${e}].sources`,xm,(n,a)=>Pm(n,`relations[${e}].sources[${a}]`))}}function Cx(t,e){let r=ei(t,`verification[${e}]`),i=pu(r.expected,`verification[${e}].expected`);return{command:Ee(r.command,`verification[${e}].command`),...i===void 0?{}:{expected:i}}}function Px(t,e){let r=ei(t,`sourceVersions[${e}]`),i=r.digest;if(i!==void 0&&(typeof i!="string"||!/^[a-f0-9]{64}$/u.test(i)))throw new Error(`sourceVersions[${e}].digest must be a SHA-256 hash`);return{source:fu(r.source,`sourceVersions[${e}].source`),size:wn(r.size,`sourceVersions[${e}].size`),modifiedAt:wn(r.modifiedAt,`sourceVersions[${e}].modifiedAt`),...i===void 0?{}:{digest:i}}}function Rx(t,e){return t.reduce((r,i)=>r+i.sources.length,0)+e.reduce((r,i)=>r+i.sources.length,0)}function Sm(t){let e=Ee(t,"updatedAt",64);if(Number.isNaN(Date.parse(e)))throw new Error("updatedAt must be an ISO-8601 timestamp");return e}function _x(t){let e=ei(t,"record"),r=Ee(e.type,"type",64);if(!yx.has(r))throw new Error("type is unsupported");let i=Ee(e.state,"state",32);if(!bx.has(i))throw new Error("state is unsupported");let n=Ee(e.authority,"authority",32);if(!Nx.has(n))throw new Error("authority is unsupported");let a=Zr(e.conclusions,"conclusions",hx,Ex),o=Zr(e.relations,"relations",mx,xx);if(Rx(a,o)>gx)throw new Error("conclusions/relations sources exceed the bounded total reference count");let s=Zr(e.sourceVersions,"sourceVersions",wx,Px);if(new Set(s.map(c=>c.source)).size!==s.length)throw new Error("sourceVersions must not contain duplicate sources");return{id:du(e.id,"id"),projectId:du(e.projectId,"projectId"),type:r,state:i,authority:n,title:Ee(e.title,"title"),summary:Ee(e.summary,"summary"),applicablePaths:Sx(e.applicablePaths,"applicablePaths"),operations:Nm(e.operations,"operations"),phases:Nm(e.phases,"phases"),conclusions:a,relations:o,verification:Zr(e.verification,"verification",vx,Cx),sourceVersions:s,applicationCount:wn(e.applicationCount,"applicationCount"),successCount:wn(e.successCount,"successCount"),failureCount:wn(e.failureCount,"failureCount"),...e.lastAppliedAt===void 0?{}:{lastAppliedAt:Sm(e.lastAppliedAt)},updatedAt:Sm(e.updatedAt)}}function Gt(t){return _x(t)}var Ax=1024*1024,Ix=512,Im=200,Tm=1600,Tx=5e3,jx=8,$x=512*1024,Ox=32;function I(t,e,r=!1){if(typeof t!="string")return null;let i=[...t].map(n=>{let a=n.codePointAt(0)??0;return a<32||a===127?" ":n}).join("").trim().slice(0,e);return r&&!i?null:i}function mu(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let r=I(e.code,64,!0),i=I(e.message,240,!0);return r&&i?{code:r,message:i}:null}).filter(e=>e!==null).slice(0,jx):[]}function yn(){return[]}function Rm(t){let e={...t};return delete e.evidence,e}function _m(t){return{...t,conclusions:t.conclusions.map(e=>({...e,sources:e.sources.map(Rm)})),relations:t.relations.map(e=>({...e,sources:e.sources.map(Rm)}))}}function Hx(t){if(t.kind==="upsert")return{kind:"upsert",record:_m(t.record)};if(t.kind!=="experience-delta")return t;let e=t.delta,r=e.payload;r?.kind==="record"?r={kind:"record",record:_m(Gt(r.record))}:r?.kind==="verify"?r={kind:"verify",projectId:I(r.projectId,128)??"",commands:bn(r.commands,16,2e3),...typeof r.updatedAt=="string"?{updatedAt:r.updatedAt.slice(0,64)}:{}}:r!==void 0&&(r=void 0);let{payload:i,...n}=e,a={...n,statement:I(e.statement,4e3)??"",...e.title===void 0?{}:{title:I(e.title,512)??""},applicability:{...e.applicability.projectId===void 0?{}:{projectId:I(e.applicability.projectId,128)??""},...e.applicability.paths===void 0?{}:{paths:bn(e.applicability.paths,32,512)},...e.applicability.operations===void 0?{}:{operations:bn(e.applicability.operations,16,128)},...e.applicability.phases===void 0?{}:{phases:bn(e.applicability.phases,16,128)},...e.applicability.tasks===void 0?{}:{tasks:bn(e.applicability.tasks,16,512)}},evidence:e.evidence.slice(0,Ox).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{...t,idempotencyKey:I(t.idempotencyKey,256,!0)??"invalid",delta:a}}function bn(t,e,r){return Array.isArray(t)?t.map(i=>I(i,r)).filter(i=>!!i).slice(0,e):[]}function Dx(t){if(t.kind==="search"){let e=t.query;return{kind:"search",task:I(e.task,2e3)??"",...e.path?{path:I(e.path,512)}:{},...e.phase?{phase:I(e.phase,128)}:{},...e.operation?{operation:I(e.operation,128)}:{},terms:e.terms.slice(0,28).map(r=>I(r,128)).filter(Boolean),limit:Math.max(1,Math.min(8,t.limit??8))}}return t.kind==="list"?{kind:"list",...t.projectId?{projectId:I(t.projectId,128)}:{},...t.type?{type:t.type}:{},...t.state?{state:t.state}:{},...t.authority?{authority:t.authority}:{},limit:Math.max(1,Math.min(500,t.limit??100))}:t.kind==="manifest"?{kind:"manifest",...t.projectId?{projectId:I(t.projectId,128)}:{},...t.state?{state:t.state}:{},limit:Math.max(1,Math.min(500,t.limit??100))}:t.kind==="expand"?{kind:"expand",id:I(t.id,128)??"",...t.projectId?{projectId:I(t.projectId,128)}:{}}:{kind:"get",id:I(t.id,128)??"",...t.projectId?{projectId:I(t.projectId,128)}:{}}}function hu(t,e,r){if(!Array.isArray(t))return[];let i=[];for(let n of t.slice(0,500))try{let a=Gt(n);if(a.projectId!==r)throw new Error("Project mismatch");i.push(a)}catch{e()}return i}function Lx(t,e,r){if(!t||typeof t!="object"||Array.isArray(t))return e(),null;let i=I(t.content,Tm,!0),n=I(t.source,Ix,!0);if(!i||!n)return e(),null;let a=t.title,o=a===void 0?void 0:I(a,Im);if(a!==void 0&&o===null)return e(),null;let s=t.score;if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)))return e(),null;let c,l=t.record;if(l!==void 0)try{if(c=Gt(l),c.projectId!==r)throw new Error("Project mismatch")}catch{return e(),null}return{content:i,source:n,...o?{title:o}:{},...s===void 0?{}:{score:s},...c?{record:c}:{}}}function Bx(t,e){let r=t&&typeof t=="object"&&!Array.isArray(t)&&"status"in t?t.status:t;if(!r||typeof r!="object"||Array.isArray(r))return e(),null;let i=r.provider,n=r.healthy,a=r.writable;if(i!=="remote"||typeof n!="boolean"||typeof a!="boolean")return e(),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:mu(r.diagnostics)}}function Mx(t,e,r,i){let n=t&&typeof t=="object"&&!Array.isArray(t)&&"result"in t?t.result:t;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.kind??e.kind,o=mu(n.diagnostics);if(a==="list")return{kind:"list",records:hu(n.records,r,i),truncated:n.truncated===!0,diagnostics:o};if(a==="get"){let p=n.record,f=null;if(p!=null)try{if(f=Gt(p),f.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"get",record:f,diagnostics:o}}if(a==="expand"){let p=n.record,f=null;if(p!=null)try{if(f=Gt(p),f.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"expand",record:f,diagnostics:o}}if(a==="manifest")return{kind:"manifest",items:Array.isArray(n.items)?n.items.slice(0,500).flatMap(f=>{if(!f||typeof f!="object"||Array.isArray(f))return r(),[];let m=f,h=I(m.id,128,!0),v=I(m.title,Im,!0),w=I(m.summary,Tm,!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),ne=I(b.expected,2e3);return T?[{command:T,...ne===null?{}:{expected:ne}}]:[]}):[];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:n.truncated===!0,diagnostics:o};let s=[],c=0,l=new Set;for(let p of Array.isArray(n.results)?(n.results??[]).slice(0,16):[]){let f=Lx(p,r,i);if(!(!f||l.has(`${f.source}\0${f.title??""}`))){if(c+f.content.length>Tx)break;l.add(`${f.source}\0${f.title??""}`),c+=f.content.length,s.push(f)}}let u=hu(n.records,r,i);return{kind:"search",hits:Array.isArray(n.hits)?(n.hits??[]).slice(0,40).flatMap(p=>{if(!p||typeof p!="object"||Array.isArray(p))return r(),[];try{let f=Gt(p.record);if(f.projectId!==i)throw new Error("Project mismatch");let m=p.score;return m!==void 0&&(typeof m!="number"||!Number.isFinite(m))?(r(),[]):[{record:f,...m===void 0?{}:{score:m}}]}catch{return r(),[]}}):u.map(p=>({record:p})),results:s,records:u,truncated:n.truncated===!0,diagnostics:o}}function Fx(t,e,r,i){let n=t&&typeof t=="object"&&!Array.isArray(t)&&"result"in t?t.result:t;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=Gt(a),o.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:e.kind,changed:n.changed===!0,...o===void 0?{}:{record:o},...Array.isArray(n.records)?{records:hu(n.records,r,i)}:{},diagnostics:mu(n.diagnostics)}}var Mo=class{options;projectId;constructor(e){this.options=e,this.projectId=e.projectId??(e.projectRoot?gm(e.projectRoot):"project")}async status(){let e=this.options.config.token_env;if(e&&!this.token()){let a={code:"remote-token",message:`Remote Project Knowledge 未配置环境变量 ${e}。`};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=Bx(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(e){let r=e.kind==="search"?this.projectId:e.projectId??this.projectId,i=await this.request("query",Dx(e),e.kind==="search"?void 0:e.projectId);if(i===null)return Am(e);let n={value:!1},a=Mx(i,e,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge query 响应包含无效数据。"),Am(e)):a}async apply(e){let r=(e.kind==="upsert"?e.record.projectId:e.kind==="experience-delta"?e.delta.applicability.projectId:e.projectId)??this.projectId,i=await this.request("apply",Hx(e),e.kind==="upsert"?e.record.projectId:e.kind==="experience-delta"?e.delta.applicability.projectId:e.projectId);if(i===null)return{kind:e.kind,changed:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let n={value:!1},a=Fx(i,e,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge apply 响应格式无效。"),{kind:e.kind,changed:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge apply 响应格式无效。"}]}):a}async request(e,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:e,...this.options.config.scope?{scope:this.options.config.scope}:{},projectId:I(i,128,!0)??this.projectId,input:r},s=JSON.stringify(o);if(new TextEncoder().encode(s).byteLength>$x)return this.report("remote-request-size","Remote Project Knowledge 请求超过大小限制。"),null;try{let{response:c,bytes:l}=await ym({url:this.options.config.endpoint,timeoutMs:this.options.config.timeout_ms,maxResponseBytes:Ax,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 Vx(u,e,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(e,r){this.options.reportDiagnostic?.({code:e,message:r})}token(){let e=this.options.config.token_env;return e?this.options.env?.[e]??process.env[e]:void 0}};function Vx(t,e,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let i=t;return i.schema==="comet.project-knowledge.provider.v1"&&i.operation===e&&i.projectId===r&&Object.prototype.hasOwnProperty.call(i,"result")}function Am(t){return t.kind==="list"?{kind:"list",records:[],truncated:!1,diagnostics:yn()}:t.kind==="get"?{kind:"get",record:null,diagnostics:yn()}:t.kind==="expand"?{kind:"expand",record:null,diagnostics:yn()}:t.kind==="manifest"?{kind:"manifest",items:[],truncated:!1,diagnostics:yn()}:{kind:"search",hits:[],results:[],records:[],truncated:!1,diagnostics:yn()}}var $m=512,vu=256*1024,Hm=8*1024*1024,qx=2e3,Dm=G.join(".comet","runtime","native","capability-discovery-cache.json"),Nn="comet.native.capability-cache.v1",Lm=512*1024,Bm=32;function gu(t,e){let r=G.relative(G.resolve(t),G.resolve(e));return r===""||!G.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${G.sep}`)}function Wx(t,e){return G.relative(t,e).replaceAll(G.sep,"/")}function zx(t,e,r){t?.({code:e,message:r})}async function Gx(t,e){if(!gu(e,t))return!1;try{let r=await ti.lstat(t);return!r.isDirectory()||r.isSymbolicLink()?!1:gu(await ti.realpath(e),await ti.realpath(t))}catch{return!1}}async function yu(t){let e=G.resolve(t.projectRoot),r=Date.now()+qx,i=[],n=!0,a=0,o=async(c,l)=>{if(Date.now()>r){n=!1;return}if(!await Gx(c,e))return;let u=async d=>{if(Date.now()>r||i.length>=$m){n=!1;return}let p;try{p=await ti.readdir(d,{withFileTypes:!0})}catch{n=!1;return}for(let f of p.sort((m,h)=>m.name.localeCompare(h.name,"en"))){if(Date.now()>r){n=!1;return}if(f.isSymbolicLink())continue;let m=G.join(d,f.name);if(f.isDirectory()){await u(m);continue}if(!f.isFile()||!f.name.toLowerCase().endsWith(".md")||!gu(e,m))continue;let h=await ti.stat(m);if(h.size>vu)continue;if(a+h.size>Hm){n=!1;return}if(Date.now()>r){n=!1;return}let v=Wx(e,m),w;try{w=await Z(e,v,vu,{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:jm("sha256").update(w.bytes).digest("hex")}),i.length>=$m){n=!1;return}}};await u(c)};await o(G.resolve(e,...t.scope.currentSpecRoot.split("/")),"native-spec"),await o(G.resolve(e,...t.scope.archiveRoot.split("/")),"native-archive"),i.sort((c,l)=>c.source.localeCompare(l.source,"en"));let s=jm("sha256").update(JSON.stringify(i.map(({source:c,kind:l,size:u,mtimeMs:d,contentHash:p})=>({source:c,kind:l,size:u,mtimeMs:d,contentHash:p})))).digest("hex");return n||zx(t.reportDiagnostic,"capability-corpus-limit","能力候选语料发现达到时间或文件数量上限,当前结果可能不完整。"),{sources:i,fingerprint:s,complete:n}}function Om(t){return/^(?:#)\s+(.+)$/mu.exec(t)?.[1]?.trim()}function Kx(t,e,r){let i=`${e}
|
|
212
|
+
${t}`.toLocaleLowerCase();return r.reduce((n,a)=>n+(i.includes(a.toLocaleLowerCase())?1:0),0)}var wu=class{constructor(e,r,i){this.projectRoot=e;this.manifest=r;this.reportDiagnostic=i}projectRoot;manifest;reportDiagnostic;async status(){return{provider:"local",healthy:!0,writable:!1,diagnostics:[]}}async query(e){if(e.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>Hm){r.push({code:"capability-corpus-bytes",message:"能力候选语料达到总字节预算,剩余来源不会参与本次召回。"});break}try{let o=await Z(this.projectRoot,a.source,vu,{label:`${a.kind} capability Spec`});n+=o.bytes.length;let s=o.bytes.toString("utf8"),c=Kx(s,a.source,e.query.terms);if(c===0)continue;let l={absolutePath:a.absolutePath,source:a.source,kind:a.kind};i.push({content:s,source:a.source,...Om(s)?{title:Om(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(e){throw new Error("Native capability discovery is read-only")}};async function Mm(t){let r=(await pr(t.projectRoot))?.knowledge;if(r?.provider==="remote"){if(!r.remote)throw new Error("Configured remote Project Knowledge provider is missing remote settings");return new Mo({config:r.remote,projectRoot:t.projectRoot,...t.reportDiagnostic?{reportDiagnostic:t.reportDiagnostic}:{}})}let i=await yu(t);return new wu(G.resolve(t.projectRoot),i,t.reportDiagnostic)}function Fm(t){return JSON.stringify({workflow:t.scope.workflow,currentSpecRoot:t.scope.currentSpecRoot,archiveRoot:t.scope.archiveRoot,task:t.task.trim()})}function Jx(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.workflow==="native"&&(e.query===null||typeof e.query=="object"&&e.query!==null)&&Array.isArray(e.candidates)&&e.candidates.length<=5&&(e.associationDraft===null||typeof e.associationDraft=="object"&&e.associationDraft!==null)&&Array.isArray(e.diagnostics)&&typeof e.searched=="boolean"&&e.providerLimit===40}function Ux(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(e.schema!==Nn||!Array.isArray(e.entries)||e.entries.length>Bm)return null;let r=[];for(let i of e.entries){if(!i||typeof i!="object"||Array.isArray(i))return null;let n=i;if(typeof n.key!="string"||typeof n.fingerprint!="string"||!Jx(n.result))return null;r.push({key:n.key,fingerprint:n.fingerprint,result:n.result})}return{schema:Nn,entries:r}}async function Vm(t){try{let e=await ti.readFile(G.join(t,Dm),"utf8");return Buffer.byteLength(e,"utf8")>Lm?null:Ux(JSON.parse(e))}catch{return null}}async function qm(t){let e=G.resolve(t.projectRoot);if((await pr(e))?.knowledge?.provider==="remote")return null;let i=await yu({projectRoot:e,scope:t.scope});return i.complete?(await Vm(e))?.entries.find(o=>o.key===Fm(t)&&o.fingerprint===i.fingerprint)?.result??null:null}async function Wm(t){let e=G.resolve(t.projectRoot);if((await pr(e))?.knowledge?.provider==="remote")return;let i=await yu({projectRoot:e,scope:t.scope});if(!i.complete)return;let n=await Vm(e)??{schema:Nn,entries:[]},a=Fm(t),o=[{key:a,fingerprint:i.fingerprint,result:t.result},...n.entries.filter(l=>!(l.key===a&&l.fingerprint===i.fingerprint))].slice(0,Bm),s=JSON.stringify({schema:Nn,entries:o});if(Buffer.byteLength(s,"utf8")>Lm)return;let{atomicWriteJson:c}=await Promise.resolve().then(()=>(B(),Kh));await c(G.join(e,Dm),{schema:Nn,entries:o},{containedRoot:G.join(e,".comet","runtime","native")})}L();Sn();mr();function U(t,e,r){return t.language==="zh-CN"?r:e}function eC(t,e,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(t.phase==="shape"&&t.status==="await-user"&&t.loop.next_action==="confirm-shape")return e?{required:!0,message:U(t,"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(t,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:U(t,"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。")}:t.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(e&&t.phase==="shape"&&t.status==="active")return n(U(t,"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(t.phase==="verify"&&t.status==="active"&&t.loop.stage==="verify-ready"&&t.loop.next_action!=="await-verifier-result")return n(U(t,"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(t.phase==="verify"&&t.status==="active"&&t.loop.next_action==="await-verifier-result"){let a=i==="confirmed"?U(t,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):U(t,"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 n(`${a} ${U(t,"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(t.status==="blocked"&&t.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return t.loop.retry_epoch>=3?t.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."}:t.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(t.phase==="verify"&&t.status==="await-user"&&t.verification?.assurance==="semantic-verification-unavailable")return t.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(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="resolve-verifier-blocker")return t.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(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="await-user"){let o=(t.loop.stop_reason??(t.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 t.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(t.phase==="verify"&&t.status==="await-user"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:U(t,"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."+(t.workspace.isolation!=="current"&&t.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.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(t.workspace.isolation!=="current"&&t.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:U(t,"Accept the result","接受结果"),agentInstruction:U(t,"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(t.phase==="build"&&t.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)>=qo)??!1;return a&&!o&&!s&&!c?t.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."}:n(U(t,"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 n(U(t,"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 tC(t){let e=t.workspace.change_branch??"<change-branch>",r=t.workspace.target_branch??"<target-branch>";return t.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${e},目标分支为 ${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 ${e} 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 rC(t){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:t.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed","--finish",i,"--expected-state-version",String(t.state_version)],requiredInputs:[],inputOptions:[],description:U(t,a[1],a[0])})),{name:"defer-archive",stateVersion:t.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:U(t,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Um(t){return["comet","native","next",t.change,"--summary","<summary>",t.flag,"--expected-state-version",String(t.stateVersion),"--expected-action",t.action]}function vr(t,e){return{name:t,flag:e,valueKind:"text",required:!0,template:null}}function Gm(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function iC(t,e){return{name:t,flag:e,valueKind:"confirmation",required:!0,template:null}}function Km(t,e,r){return{name:t,flag:e,valueKind:"choice",required:!0,template:null,choices:[...r]}}function nC(t){return t?.coordinationChoiceRequired===!0||t?.schema==="comet.native.children.v2"&&t.children.length>=2}function aC(t){return["comet","native","next",t.change,"--summary","<summary>","--expected-state-version",String(t.stateVersion),"--expected-action","prepare-shape-confirmation"]}function it(t){return{name:t.name,stateVersion:t.stateVersion,expectedAction:t.expectedAction,commandArgs:Um({change:t.change,stateVersion:t.stateVersion,action:t.expectedAction,flag:t.flag}),requiredInputs:["summary",t.confirmationInput],inputOptions:[vr("summary","--summary"),iC(t.name,t.flag)]}}function Jm(t,e){return e.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:t.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",t.name,"--repair"],requiredInputs:[],inputOptions:[],description:U(t,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function oC(t){return/^verification\.md is (?:missing|stale|invalid)$/u.test(t)}function Wo(t){return[it({name:"revise-implementation",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),it({name:"revise-requirements",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function sC(t){let e={"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 t.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:e[n],template:i}}):[r])}function Ym(t,e,r={}){let i=nC(e)&&t.coordination_mode===void 0,n=eC(t,i,e,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(t.status==="await-user")return t.phase==="shape"&&t.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...i?["coordination-choice"]:[]],inputOptions:[vr("summary","--summary")],commandAlternatives:i?zm.map(s=>{let c=it({name:`confirm-shape-${s}`,change:t.name,stateVersion:t.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,Km("coordination-mode","--coordination-mode",[s])]}}):[it({name:"confirm-shape",change:t.name,stateVersion:t.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:t.phase==="verify"&&t.verification_result==="pass"&&t.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:[...t.workspace.isolation!=="current"&&t.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=it({name:`accept-result-${s}`,change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],it({name:"accept-result",change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Wo({change:t.name,stateVersion:t.state_version})],runnerAction:o("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.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:[it({name:"retry-verifier",change:t.name,stateVersion:t.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),it({name:"confirm-verifier-unavailable",change:t.name,stateVersion:t.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:t.phase==="verify"&&t.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:[it({name:"resolve-verifier-blocker",change:t.name,stateVersion:t.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Wo({change:t.name,stateVersion:t.state_version})],runnerAction:o("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:Wo({change:t.name,stateVersion:t.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Wo({change:t.name,stateVersion:t.state_version}),userCommunication:{...a.userCommunication,required:!0,message:t.blockers.length>0?t.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:t.blockers.length>0?t.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(t.status==="blocked"){let s=t.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Um({change:t.name,stateVersion:t.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(t.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:aC({change:t.name,stateVersion:t.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:t.acceptance.map(({id:m})=>m),acceptance_review:t.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:[Gm()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=e.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.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=e.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=e.children.some(({status:m})=>m==="needs-reverify"),u=e.children.some(({status:m})=>m==="ready"||m==="active"),d=e.supervisorStateVersion===void 0?null:e.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=qo)??null,p=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:e.supervisorStateVersion},description:U(t,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&p===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:p!==null?["comet","native","next",t.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",t.name,"--summary","<summary>",...t.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:p!==null?[p]:[vr("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:t.acceptance.map(({id:s})=>s),acceptance_review:t.acceptance.map(({id:s})=>{let c=t.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...t.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(t.phase==="verify"){let s=t.loop.next_action==="await-verifier-result",c=!!t.children_contract_hash,l=Gm();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",t.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(t,"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",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:sC([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:t.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:t.loop.iteration,attempt:t.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:t.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef: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(t.phase==="archive"&&t.status==="active"&&t.loop.stage==="archive-ready"&&!t.archived){let s=r.archiveMode??"archive-ready",l=t.workspace.isolation!=="current"&&t.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=Jm(t,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>oC(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:Jm(t,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Km("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...rC(t)],userCommunication:tC(t),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--dry-run"],requiredInputs:[],commandAlternatives:[it({name:"revise-requirements",change:t.name,stateVersion:t.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{promises as JC}from"node:fs";import ju from"node:path";Qr();Go();import{execFileSync as vC}from"child_process";import gC from"fs";import gr from"path";import{AsyncLocalStorage as ev}from"node:async_hooks";Pn();var wr=new ev,tv=new ev;function rv(t){return wr.getStore()?t():wr.run(new Map,t)}function wC(t){let e=wr.getStore();for(let r of t)e?.set(Jt(r.root),t);return t}function Ut(t,e){return gn(()=>vC("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function nt(t,e){return Jt(t)===Jt(e)}function Jt(t){let e=gr.resolve(t);try{let r=gC.realpathSync.native(e);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?e.toLowerCase():e}}function ge(t){try{let e=tv.getStore()?.get(Jt(t)),r=wr.getStore()?.get(e??Jt(t));if(r){let c=Zm(e??t,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=gr.resolve(Ut(t,["rev-parse","--show-toplevel"])),n=wr.getStore()?.get(Jt(i))??iv(t),a=Zm(i,n);if(wr.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Ut(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!nt(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Ko(t){try{let e=wr.getStore()?.get(tv.getStore()?.get(Jt(t))??Jt(t));return e?e.map(r=>({...r})):(Ut(t,["rev-parse","--is-inside-work-tree"]),iv(t))}catch{return[]}}function iv(t){let e=yC(Ut(t,["worktree","list","--porcelain","-z"]));return wC(e),e.map(r=>({...r}))}function yC(t){let e=t.split("\0"),r=[],i=null;for(let n of e)n.startsWith("worktree ")?(i&&r.push(i),i={root:gr.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}function yr(t){return Ko(t).map(e=>e.root)}function Zm(t,e){let r=e.find(a=>nt(gr.resolve(a.root),gr.resolve(t)));if(!r)return null;let i=gr.resolve(e[0].root),n=gr.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!nt(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function nv(t){try{return Ut(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function ii(t,e){try{return Ut(t,["check-ref-format","--branch",e]),Ut(t,["show-ref","--verify",`refs/heads/${e}`]),!0}catch{return!1}}function br(t,e){try{let r=Ut(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ze();B();Sn();import{promises as bC}from"node:fs";import NC from"node:os";import In from"node:path";function _n(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function An(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function de(t,e,r=!1){if(typeof t!="string"||!r&&t.length===0)throw new Error(`${e} must be ${r?"a string":"a non-empty string"}`);return t}function ni(t,e){return t===null?null:de(t,e)}function ai(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function kC(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function SC(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function oi(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function xu(t,e){if(t===null)return null;let r=de(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function EC(t,e){let r=de(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function Cu(t,e){let r=de(t,e);if(!In.isAbsolute(r))throw new Error(`${e} must be absolute`);return In.resolve(r)}function xC(t,e){let r=`Native local checks[${e}]`,i=_n(t,r);if(An(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)=>de(u,`${r}.argv[${d}]`,!0)),a=oi(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=xu(i.startedAt,`${r}.startedAt`),s=xu(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=ai(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=_n(i.activeProcess,`${r}.activeProcess`),d=oi(u.status,["starting","running"],`${r}.activeProcess.status`);if(An(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:ai(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:de(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:de(i.id,`${r}.id`),name:de(i.name,`${r}.name`),operationId:de(i.operationId,`${r}.operationId`),status:a,repeatable:SC(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ai(i.executionCount,`${r}.executionCount`),argv:n,cwd:Cu(i.cwd,`${r}.cwd`),exitCode:kC(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:de(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:oi(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:de(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function av(t){let e="Native local execution state",r=_n(t,e);if(An(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),e),r.schema!==kn)throw new Error(`Native local execution schema must be ${kn}`);let i=_n(r.workspace,"Native local workspace");An(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=_n(r.execution,"Native local execution");An(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=xu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:de(o.operationId,"Native local execution.operationId"),stage:oi(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:oi(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ni(o.executionId,"Native local execution.executionId"),status:oi(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ai(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:EC(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:ai(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(xC);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:kn,change:de(r.change,"Native local change"),basedOnStateVersion:ai(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:ni(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:ni(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:ni(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:ni(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Cu(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Cu(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ni(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:de(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function Nr(t){return av({schema:kn,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,candidateId:t.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:In.resolve(t.projectRoot),worktreeRoot:In.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null,machineId:NC.hostname()},execution:null,checks:[]})}async function kr(t,e,r={}){let i=av(e);await bC.mkdir(In.dirname(t),{recursive:!0}),await ae(t,i,r)}Yt();L();var $u=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uv="comet-state.yaml",dv="state.json";function ot(t,e){if(!$u.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=ju.join(t.changesDir,e);if(!te(t.changesDir,r))throw new Error("Native change path escaped");return r}function Tn(t,e){return ju.join(ot(t,e),uv)}function Xt(t,e){return ju.join(Ve(t,e),dv)}async function Ou(t,e){try{let r=await JC.readFile(Tn(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function pv(t){return{isolation:t?.isolation??"current",change_branch:t?.changeBranch??null,target_branch:t?.targetBranch??null,finish:null}}function Er(t){return nv(t)}function fv(t,e){if(!e)return;let r=ge(t);if(e.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==e.changeBranch))throw new Error(`Native workspace binding ${e.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Nt(t,e){return Tu(Tn(t,e))}import{promises as Ir}from"node:fs";import aw from"node:path";function Bu(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Pr=Bu();function Nv(t){Pr=t}var xr={exec:()=>null};function di(t){let e=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=e[i];return n||(n=t(i),e[i]=n),n}}function R(t,e=""){let r=typeof t=="string"?t:t.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(se.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,e)};return i}var UC=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}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:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:di(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:di(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:di(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:di(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:di(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:di(t=>new RegExp(`^ {0,${t}}>`))},YC=/^(?:[ \t]*(?:\n|$))+/,XC=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,QC=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,On=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ZC=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Mu=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,kv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Sv=R(kv).replace(/bull/g,Mu).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(),eP=R(kv).replace(/bull/g,Mu).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(),Fu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,tP=/^[^\n]+/,Vu=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,rP=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Vu).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),iP=R(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Mu).getRegex(),rs="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",qu=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,nP=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",qu).replace("tag",rs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ev=t=>R(Fu).replace("hr",On).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",t).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",rs).getRegex(),aP=Ev(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),oP=Ev(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),sP=R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",oP).getRegex(),Wu={blockquote:sP,code:XC,def:rP,fences:QC,heading:ZC,hr:On,html:nP,lheading:Sv,list:iP,newline:YC,paragraph:aP,table:xr,text:tP},hv=R("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",On).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",rs).getRegex(),cP={...Wu,lheading:eP,table:hv,paragraph:R(Fu).replace("hr",On).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",hv).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",rs).getRegex()},lP={...Wu,html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",qu).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(Fu).replace("hr",On).replace("heading",` *#{1,6} *[^
|
|
213
|
+
]`).replace("lheading",Sv).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},uP=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,dP=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,xv=/^( {2,}|\\)\n(?!\s*$)/,pP=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,kt=/[\p{P}\p{S}]/u,pi=/[\s\p{P}\p{S}]/u,Hn=/[^\s\p{P}\p{S}]/u,fP=R(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,pi).getRegex(),hP=/[\p{Pi}\p{Ps}"']/u,Cv=/(?!~)[\p{P}\p{S}]/u,mP=/(?!~)[\s\p{P}\p{S}]/u,vP=/(?:[^\s\p{P}\p{S}]|~)/u,gP=R(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",UC?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Pv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,wP=R(Pv,"u").replace(/punct/g,kt).getRegex(),yP=R(Pv,"u").replace(/punct/g,Cv).getRegex(),bP=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,NP=R(bP,"u").replace(/openQuote/g,hP).replace(/punct/g,kt).getRegex(),Rv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",kP=R(Rv,"gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),SP=R(Rv,"gu").replace(/notPunctSpace/g,vP).replace(/punctSpace/g,mP).replace(/punct/g,Cv).getRegex(),EP="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",xP=R(EP,"gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),CP=R("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),PP="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",RP=R(PP,"gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),_P=R(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,kt).getRegex(),AP="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",IP=R(AP,"gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),TP=R(/\\(punct)/,"gu").replace(/punct/g,kt).getRegex(),jP=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(),$P=R(qu).replace("(?:-->|$)","-->").getRegex(),OP=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",$P).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Zo=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,HP=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Zo).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),_v=R(/^!?\[(label)\]\[(ref)\]/).replace("label",Zo).replace("ref",Vu).getRegex(),Av=R(/^!?\[(ref)\](?:\[\])?/).replace("ref",Vu).getRegex(),DP=R("reflink|nolink(?!\\()","g").replace("reflink",_v).replace("nolink",Av).getRegex(),mv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,zu={_backpedal:xr,anyPunctuation:TP,autolink:jP,blockSkip:gP,br:xv,code:dP,del:xr,delLDelim:xr,delRDelim:xr,emStrongLDelim:wP,emStrongRDelimAst:kP,emStrongRDelimUnd:CP,escape:uP,link:HP,nolink:Av,punctuation:fP,reflink:_v,reflinkSearch:DP,tag:OP,text:pP,url:xr},LP={...zu,emStrongLDelim:NP,emStrongRDelimAst:xP,emStrongRDelimUnd:RP,link:R(/^!?\[(label)\]\((.*?)\)/).replace("label",Zo).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Zo).getRegex()},Hu={...zu,emStrongRDelimAst:SP,emStrongLDelim:yP,delLDelim:_P,delRDelim:IP,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",mv).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",mv).getRegex()},BP={...Hu,br:R(xv).replace("{2,}","*").getRegex(),text:R(Hu.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Qo={normal:Wu,gfm:cP,pedantic:lP},jn={normal:zu,gfm:Hu,breaks:BP,pedantic:LP},MP={"&":"&","<":"<",">":">",'"':""","'":"'"},vv=t=>MP[t];function st(t,e){if(e){if(se.escapeTest.test(t))return t.replace(se.escapeReplace,vv)}else if(se.escapeTestNoEncode.test(t))return t.replace(se.escapeReplaceNoEncode,vv);return t}function gv(t){try{t=encodeURI(t).replace(se.percentDecode,"%")}catch{return null}return t}function wv(t,e){let r=t.replace(se.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split(se.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(se.slashPipe,"|");return i}function Qt(t,e,r){let i=t.length;if(i===0)return"";let n=0;for(;n<i;){let a=t.charAt(i-n-1);if(a===e&&!r)n++;else if(a!==e&&r)n++;else break}return t.slice(0,i-n)}function yv(t){let e=t.split(`
|
|
214
|
+
`),r=e.length-1;for(;r>=0&&se.blankLine.test(e[r]);)r--;return e.length-r<=2?t:e.slice(0,r+1).join(`
|
|
215
|
+
`)}function FP(t,e){if(t.indexOf(e[1])===-1)return-1;let r=0;for(let i=0;i<t.length;i++)if(t[i]==="\\")i++;else if(t[i]===e[0])r++;else if(t[i]===e[1]&&(r--,r<0))return i;return r>0?-2:-1}function VP(t,e=0){let r=e,i="";for(let n of t)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function bv(t,e,r,i,n){let a=e.href,o=e.title||null,s=t[1].replace(n.other.outputLinkReplace,"$1"),c=t[0].charAt(0)==="!";i.state.inLink=!0;let l=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),p=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(p){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function qP(t,e,r){let i=t.match(r.other.indentCodeCompensation);if(i===null)return e;let n=i[1];return e.split(`
|
|
216
|
+
`).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=n.length?a.slice(n.length):a}).join(`
|
|
217
|
+
`)}var es=class{options;rules;lexer;constructor(t){this.options=t||Pr}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let r=this.options.pedantic?e[0]:yv(e[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let r=e[0],i=qP(r,e[3]||"",this.rules);return{type:"code",raw:r,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:i}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let r=e[2].trim();if(this.rules.other.endingHash.test(r)){let i=Qt(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:Qt(e[0],`
|
|
218
|
+
`),depth:e[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:Qt(e[0],`
|
|
219
|
+
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let r=Qt(e[0],`
|
|
220
|
+
`).split(`
|
|
221
|
+
`),i="",n="",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(`
|
|
222
|
+
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
223
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
224
|
+
${l}`:l,n=n?`${n}
|
|
225
|
+
${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 p=a.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let f=p,m=r.join(`
|
|
226
|
+
`),h=f.raw+`
|
|
227
|
+
`+m.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(h);a[a.length-1]=v,i=`${i}
|
|
228
|
+
${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="list"){let f=p,m=f.raw+`
|
|
229
|
+
`+r.join(`
|
|
230
|
+
`),h=this.list(m);a[a.length-1]=h,i=i.substring(0,i.length-p.raw.length)+h.raw,n=n.substring(0,n.length-f.raw.length)+h.raw,r=m.substring(a.at(-1).raw.length).split(`
|
|
231
|
+
`);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(t){let e=this.rules.block.list.exec(t);if(e){let r=e[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;t;){let c=!1,l="",u="";if(!(e=a.exec(t))||this.rules.block.hr.test(t))break;l=e[0],t=t.substring(l.length);let d=VP(e[2].split(`
|
|
232
|
+
`,1)[0],e[1].length),p=t.split(`
|
|
233
|
+
`,1)[0],f=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):f?m=e[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=e[1].length),f&&this.rules.other.blankLine.test(p)&&(l+=p+`
|
|
234
|
+
`,t=t.substring(p.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(;t;){let x=t.split(`
|
|
235
|
+
`,1)[0],g;if(p=x,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),g=p):g=p.replace(this.rules.other.tabCharGlobal," "),w.test(p)||y.test(p)||k.test(p)||E.test(p)||h.test(p)||v.test(p))break;if(g.search(this.rules.other.nonSpaceChar)>=m||!p.trim())u+=`
|
|
236
|
+
`+g.slice(m);else{if(f||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||y.test(d)||v.test(d))break;u+=`
|
|
237
|
+
`+p}f=!p.trim(),l+=x+`
|
|
238
|
+
`,t=t.substring(x.length+1),d=g.slice(m)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let c of n.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,n.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(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(t){let e=this.rules.block.html.exec(t);if(e){let r=yv(e[0]);return{type:"html",block:!0,raw:r,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:r}}}def(t){let e=this.rules.block.def.exec(t);if(e){let r=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:r,raw:Qt(e[0],`
|
|
239
|
+
`),href:i,title:n}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let r=wv(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
240
|
+
`):[],a={type:"table",raw:Qt(e[0],`
|
|
241
|
+
`),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)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 n)a.rows.push(wv(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let r=e[1].trim();return{type:"heading",raw:Qt(e[0],`
|
|
242
|
+
`),depth:e[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let r=e[1].charAt(e[1].length-1)===`
|
|
243
|
+
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:r,tokens:this.lexer.inline(r)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let r=e[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=FP(e[2],"()");if(a===-2)return;if(a>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+a;e[2]=e[2].substring(0,a),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let i=e[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=e[3]?e[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),bv(e,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=e[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return bv(r,n,r[0],this.lexer,this.rules)}}emStrong(t,e,r=""){let i=this.rules.inline.emStrongLDelim.exec(t);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=0,l=i[0][0],u=r===l,d=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,e=e.slice(-1*t.length+n);(i=d.exec(e))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(o=[...a].length,i[3]||i[4]){s+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let p=[...i[0]][0].length,f=t.slice(0,n+i.index+p+o);if(Math.min(n,o)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let r=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:e[0],text:r}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,r=""){let i=this.rules.inline.delLDelim.exec(t);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=this.rules.inline.delRDelim;for(c.lastIndex=0,e=e.slice(-1*t.length+n);(i=c.exec(e))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a||(o=[...a].length,o!==n))continue;if(i[3]||i[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let l=[...i[0]][0].length,u=t.slice(0,n+i.index+l+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let r,i;return e[2]==="@"?(r=e[1],i="mailto:"+r):(r=e[1],i=r),{type:"link",raw:e[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let r,i;if(e[2]==="@")r=e[0],i="mailto:"+r;else{let n;do n=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(n!==e[0]);r=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let r=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:r}}}},Te=class Du{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Pr,this.options.tokenizer=this.options.tokenizer||new es,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:Qo.normal,inline:jn.normal};this.options.pedantic?(r.block=Qo.pedantic,r.inline=jn.pedantic):this.options.gfm&&(r.block=Qo.gfm,this.options.breaks?r.inline=jn.breaks:r.inline=jn.gfm),this.tokenizer.rules=r}static get rules(){return{block:Qo,inline:jn}}static lex(e,r){return new Du(r).lex(e)}static lexInline(e,r){return new Du(r).inlineTokens(e)}lex(e){e=e.replace(se.carriageReturn,`
|
|
244
|
+
`),this.blockTokens(e,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let i=this.inlineQueue[r];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(se.tabCharGlobal," ").replace(se.spaceLine,""));let n=1/0;for(;e;){if(e.length<n)n=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},e,r))?(e=e.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(e)){e=e.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
|
|
245
|
+
`:r.push(a);continue}if(a=this.tokenizer.code(e)){e=e.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
246
|
+
`)?"":`
|
|
247
|
+
`)+a.raw,s.text+=`
|
|
248
|
+
`+a.text,this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(a=this.tokenizer.fences(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.heading(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.hr(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.blockquote(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.list(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.html(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.def(e)){e=e.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
249
|
+
`)?"":`
|
|
250
|
+
`)+a.raw,s.text+=`
|
|
251
|
+
`+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(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(e)){e=e.substring(a.raw.length),r.push(a);continue}let o=e;if(this.options.extensions?.startBlock){let s=1/0,c=e.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=e.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);i&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
|
|
252
|
+
`)?"":`
|
|
253
|
+
`)+a.raw,s.text+=`
|
|
254
|
+
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),i=o.length!==e.length,e=e.substring(a.raw.length);continue}if(a=this.tokenizer.text(e)){e=e.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
255
|
+
`)?"":`
|
|
256
|
+
`)+a.raw,s.text+=`
|
|
257
|
+
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}linkInText(e){if(!e.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&e.charAt(i.index-1)!=="!")return!0;for(let i of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(e,r=[]){this.tokenizer.lexer=this;let i=e;if(this.tokens.links&&e.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)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.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)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},e,r))?(e=e.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(e,this.tokens.links)){e=e.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(e,i,a)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(e,i,a)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(e)){e=e.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(e))){e=e.substring(s.raw.length),r.push(s);continue}let c=e;if(this.options.extensions?.startInline){let l=1/0,u=e.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=e.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){e=e.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return r}infiniteLoopError(e){let r="Infinite loop on byte: "+e;if(this.options.silent)console.error(r);else throw new Error(r)}},ts=class{options;parser;constructor(t){this.options=t||Pr}space(t){return""}code({text:t,lang:e,escaped:r}){let i=(e||"").match(se.notSpaceStart)?.[0],n=t.replace(se.endingNewline,"")+`
|
|
258
|
+
`;return i?'<pre><code class="language-'+st(i)+'">'+(r?n:st(n,!0))+`</code></pre>
|
|
259
|
+
`:"<pre><code>"+(r?n:st(n,!0))+`</code></pre>
|
|
260
|
+
`}blockquote({tokens:t}){return`<blockquote>
|
|
261
|
+
${this.parser.parse(t)}</blockquote>
|
|
262
|
+
`}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
|
|
263
|
+
`}hr(t){return`<hr>
|
|
264
|
+
`}list(t){let e=t.ordered,r=t.start,i="";for(let o=0;o<t.items.length;o++){let s=t.items[o];i+=this.listitem(s)}let n=e?"ol":"ul",a=e&&r!==1?' start="'+r+'"':"";return"<"+n+a+`>
|
|
265
|
+
`+i+"</"+n+`>
|
|
266
|
+
`}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
|
|
267
|
+
`}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
|
|
268
|
+
`}table(t){let e="",r="";for(let n=0;n<t.header.length;n++)r+=this.tablecell(t.header[n]);e+=this.tablerow({text:r});let i="";for(let n=0;n<t.rows.length;n++){let a=t.rows[n];r="";for(let o=0;o<a.length;o++)r+=this.tablecell(a[o]);i+=this.tablerow({text:r})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
|
|
269
|
+
<thead>
|
|
270
|
+
`+e+`</thead>
|
|
271
|
+
`+i+`</table>
|
|
272
|
+
`}tablerow({text:t}){return`<tr>
|
|
273
|
+
${t}</tr>
|
|
274
|
+
`}tablecell(t){let e=this.parser.parseInline(t.tokens),r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+e+`</${r}>
|
|
275
|
+
`}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${st(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:r}){let i=this.parser.parseInline(r),n=gv(t);if(n===null)return i;t=n;let a='<a href="'+t+'"';return e&&(a+=' title="'+st(e)+'"'),a+=">"+i+"</a>",a}image({href:t,title:e,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=gv(t);if(n===null)return st(r);t=n;let a=`<img src="${t}" alt="${st(r)}"`;return e&&(a+=` title="${st(e)}"`),a+=">",a}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:st(t.text)}},Gu=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},Ke=class Lu{options;renderer;textRenderer;constructor(e){this.options=e||Pr,this.options.renderer=this.options.renderer||new ts,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Gu}static parse(e,r){return new Lu(r).parse(e)}static parseInline(e,r){return new Lu(r).parseInline(e)}parse(e){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let n=e[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,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=n;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(e,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<e.length;n++){let a=e[n];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)){i+=s||"";continue}}let o=a;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=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 i}},$n=class{options;block;constructor(t){this.options=t||Pr}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?Te.lex:Te.lexInline}provideParser(t=this.block){return t?Ke.parse:Ke.parseInline}},WP=class{defaults=Bu();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ke;Renderer=ts;TextRenderer=Gu;Lexer=Te;Tokenizer=es;Hooks=$n;constructor(...t){this.use(...t)}walkTokens(t,e){let r=[];for(let i of t)switch(r=r.concat(e.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,e));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,e));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,e));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(a=>{let o=n[a].flat(1/0);r=r.concat(this.walkTokens(o,e))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,e)))}}return r}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=e.renderers[n.name];a?e.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:e.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=e[n.level];a?a.unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),i.extensions=e),r.renderer){let n=this.defaults.renderer||new ts(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new es(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new $n;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=n[o];$n.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&$n.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,l);return c.call(n,d)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,l);return d===!1&&(d=await c.apply(n,l)),d})();let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return Te.lex(t,e??this.defaults)}parser(t,e){return Ke.parse(t,e??this.defaults)}parseMarkdown(t){return(e,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.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 e>"u"||e===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=t),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(e):e,s=await(n.hooks?await n.hooks.provideLexer(t):t?Te.lex:Te.lexInline)(o,n),c=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(c,n.walkTokens));let l=await(n.hooks?await n.hooks.provideParser(t):t?Ke.parse:Ke.parseInline)(c,n);return n.hooks?await n.hooks.postprocess(l):l})().catch(a);try{n.hooks&&(e=n.hooks.preprocess(e));let o=(n.hooks?n.hooks.provideLexer(t):t?Te.lex:Te.lexInline)(e,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(t):t?Ke.parse:Ke.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(t,e){return r=>{if(r.message+=`
|
|
276
|
+
Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+st(r.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(r);throw r}}},Cr=new WP;function O(t,e){return Cr.parse(t,e)}O.options=O.setOptions=function(t){return Cr.setOptions(t),O.defaults=Cr.defaults,Nv(O.defaults),O};O.getDefaults=Bu;O.defaults=Pr;function zP(...t){return Cr.use(...t),O.defaults=Cr.defaults,Nv(O.defaults),O}O.use=zP;O.walkTokens=function(t,e){return Cr.walkTokens(t,e)};O.parseInline=Cr.parseInline;O.Parser=Ke;O.parser=Ke.parse;O.Renderer=ts;O.TextRenderer=Gu;O.Lexer=Te;O.lexer=Te.lex;O.Tokenizer=es;O.Hooks=$n;O.parse=O;var TO=O.options,jO=O.setOptions,$O=O.walkTokens,OO=O.parseInline;var HO=Ke.parse,DO=Te.lex;B();Rr();var Sd=At(mt(),1);import{promises as Is}from"fs";import Ye from"path";Ae();B();Rr();ke();ie();L();lt();Jn();ie();L();Jr();Vt();var U_=At(mt(),1);Jr();Vt();tt();tt();fr();Vl();Jr();tt();import{promises as Y_}from"node:fs";import X_ from"node:path";var yi=".gitignore",hd=4*1024*1024,vd="# >>> Comet managed project state >>>",Ag="# <<< Comet managed project state <<<";function Q_(t){return t.includes(`\r
|
|
200
277
|
`)?`\r
|
|
201
278
|
`:`
|
|
202
|
-
`}function
|
|
203
|
-
`,"utf8"),await
|
|
204
|
-
${
|
|
279
|
+
`}function Z_(t){return t.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function eA(t){return t.replace(/(?:\r\n|\n|\r)$/u,"")}function Ig(t){let e=[],r=!1;for(let i of Z_(t)){let n=eA(i);if(n===vd){if(r)throw new Error("Comet .gitignore managed block is malformed");r=!0;continue}if(n===Ag){if(!r)throw new Error("Comet .gitignore managed block is malformed");r=!1;continue}r||e.push(i)}if(r)throw new Error("Comet .gitignore managed block is incomplete");return e.join("")}function _g(t){let e=Ig(t).split(/\r?\n/u).map(r=>r.trim());return e.includes(".comet/runtime/")&&e.includes(".comet/current-change.json")}function md(t){let e=Q_(t),r=Ig(t);return r.length>0&&!/(?:\r\n|\n|\r)$/u.test(r)&&(r+=e),r+[vd,"!/.comet/","/.comet/*","!/.comet/config.yaml",Ag,""].join(e)}async function gd(t){let e=X_.resolve(t),r=await gt(e,yi,{label:"project .gitignore",expected:"file"}),i="",n=new Uint8Array;if(r.exists&&(n=(await Z(e,yi,hd,{label:"project .gitignore"})).bytes,i=Buffer.from(n).toString("utf8")),r.exists&&!i.includes(vd)&&_g(i))return;let a=md(i);if(a!==i){try{await hr(r.target,a,{containedRoot:e,exclusive:!r.exists,beforeCommit:r.exists?async()=>{if(!(await Z(e,yi,hd,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await gt(e,yi,{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(e,yi,hd,{label:"project .gitignore"}),l=Buffer.from(c.bytes).toString("utf8");if(md(l)!==l&&!_g(l))throw o}await gt(e,yi,{label:"project .gitignore",expected:"file"}),await Y_.access(r.target)}}import{AsyncLocalStorage as tA}from"node:async_hooks";var rA=new tA;function iA(){let t=rA.getStore();return t?.active?t:null}function nA(t,e){let r=t;for(let i of e)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Tg(t,e){return(...r)=>{let i=iA();if(i===null)return e(...r);let n=nA(`async:${t}`,r),a=i.entries.get(n);if(a)return a.value;let o=e(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}fr();var WD=Tg("hookWritePolicy",async t=>(await pr(t))?.hook??{allow_paths:[]});dn();import{randomUUID as aA}from"node:crypto";import{promises as xs}from"node:fs";import $g from"node:path";var Cs="comet.selection.v2",oA=16*1024;function wd(t){return $g.join(t,".comet","current-change.json")}function sA(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function jg(t){return t===null||typeof t=="string"}function cA(t){let e;try{e=JSON.parse(t)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!sA(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!jg(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Cs,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Cs)throw new Error(`current change selection schema must be ${Cs}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!jg(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function yd(t,e){let r=cA(JSON.stringify(e));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=wd(t),n=`${i}.${aA()}.tmp`;await xs.mkdir($g.dirname(i),{recursive:!0});try{await xs.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
280
|
+
`,"utf8"),await xs.rename(n,i)}catch(a){throw await xs.rm(n,{force:!0}),a}}Ml();ln();var WL=Number.MAX_SAFE_INTEGER;B();rt();var i1={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 fA}from"node:crypto";import{promises as Ps}from"node:fs";import Zt from"node:path";B();Ae();ie();L();var Un=/^[a-f0-9]{64}$/u,Hg=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,hA=16*1024,Nd=process.platform;function Bg(t,e){let r=Zt.relative(t,e);return Zt.isAbsolute(r)||r===".."||r.startsWith(`..${Zt.sep}`)?null:r.replaceAll("\\","/")||"."}function Mg(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function Fg(t,e){if(t.length===0||Mg(t)||t.includes("\\")||Zt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let r=Zt.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function kd(t,e){return fA("sha256").update(`${t}
|
|
281
|
+
${e}`).digest("hex")}async function Dg(t,e){let r=await Ps.realpath(e),i=await Ps.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nd==="win32"?Zt.normalize(r).toLowerCase():r;return kd(t,`${n}
|
|
205
282
|
${i.dev}
|
|
206
283
|
${i.ino}
|
|
207
|
-
${i.birthtimeMs}`)}async function
|
|
284
|
+
${i.birthtimeMs}`)}async function Lg(t,e){let r=await Ps.realpath(e),i=await Ps.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nd==="win32"?Zt.normalize(r).toLowerCase():r;return kd(t,n)}function mA(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function bd(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Mg(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function Vg(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(bd(t.changeBranch,"Native workspace change branch"),bd(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function vA(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(e).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!Hg.test(e.baseCommit)||typeof e.targetCommit!="string"||!Hg.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");bd(e.targetBranch,"Native workspace Git target branch")}function Rs(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(e).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!Un.test(String(e.projectRootId))||!Un.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");mA(e.capturedAt),Fg(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Un.test(String(e.projectRootPathId))||a&&!Un.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Un.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&vA(e.git),e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Vg(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function gA(t,e){return Zt.join(Ne(t,e),"workspace.json")}function wA(t,e){let r=gA(t,e),i=qe(t,r),n=Bg(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Fg(n,"Native workspace file ref")}}async function yA(t,e){try{let r=wA(t,e),i=await ue({root:r.root,ref:r.ref,maxBytes:hA});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function bA(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=Bg(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let r=ge(t.paths.projectRoot),i=r.isGitWorktree?br(t.paths.projectRoot,"HEAD"):null,n=t.binding?.targetBranch??r.currentBranch,a=n==null?null:br(t.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Dg("comet.native.workspace-project-root.v2",t.paths.projectRoot),Dg("comet.native.workspace-native-root.v2",t.paths.nativeRoot),Lg("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),Lg("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),d=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&Vg(t.binding);let p={capturedAt:d,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...t.sessionId?{sessionHash:kd("comet.native.workspace-session.v2",`${s}
|
|
208
285
|
${c}
|
|
209
|
-
${
|
|
286
|
+
${t.sessionId}`)}:{}},f=t.binding?{schema:"comet.native.workspace.v3",...p,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...p};return Rs(f),f}async function bi(t,e){let r=await yA(t,e);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Rs(r),r)}async function _s(t){Rs(t.identity);let e=await bA({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),r=[],i=[];return e.nativeRootRef!==t.identity.nativeRootRef&&r.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&r.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&r.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&r.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&r.push("native-root-legacy-identity")),Nd==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function As(t){if(Rs(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await _s(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ge(t.paths.projectRoot);return t.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!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:t.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 qg(t,e){let r=await bi(t,e);if(r===null)return null;let i=await As({paths:t,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}Fn();hs();hs();var Ts=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Ni=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},js=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},W1=Dn("en");function er(t,e){hi(e);let r=Ye.join(t.changesDir,e);if(!te(t.changesDir,r))throw new Error("Native change path escaped");return r}async function Ed(t,e){let r=Ne(t,e),i=Ye.join(r,"schema-migration.json");await j(te(t.runtimeDir,i)?t.runtimeDir:t.nativeRoot,i);try{return await Is.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function zg(t,e=Ye.dirname(t)){let r=Ye.relative(e,t).split(Ye.sep).join("/"),i=await ue({root:e,ref:r,maxBytes:null,includeHash:!1}),n=(0,Sd.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function SA(t,e){let r=Ye.join(er(t,e),Je);await j(t.nativeRoot,r);let i=fs(await zg(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Ed(t,e)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(i.status==="current"&&i.state&&await xA(t,i.state),i)}async function EA(t,e){let r=Ye.join(er(t,e),Je);await j(t.nativeRoot,r);let i=fs(await zg(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return i}async function xA(t,e){if(await Rg(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function tr(t,e){let r=await SA(t,e);if(r.status==="migration-required")throw new fi(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Ct(r.schema,r.minimumRuntimeVersion);return await qg(t,e),r.state}async function CA(t){let e;try{let i=await Kn({root:t.nativeRoot,directory:t.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await i.verify(),e=i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}return e.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort()}async function Gg(t){let e=[];for(let r of await CA(t)){let i=await EA(t,r);if(!i.state){if(await Wg(t,r))continue;e.push(r);continue}if(i.state.archived)continue;let n=await bi(t,r);if(!(!n&&await Wg(t,r))){if(n?.schema==="comet.native.workspace.v3"){if((await As({paths:t,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await _s({paths:t,identity:n})).state==="drifted")continue;e.push(r)}}return e}async function Wg(t,e){for(let r of yr(t.projectRoot))if(!nt(r,t.projectRoot))try{let i=await oe(r);if(!i)continue;let n=await yt(r,i.native.artifact_root),a=Ye.join(n.changesDir,e),o=Ye.join(a,"comet-state.yaml");try{let l=await Is.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Is.readFile(Ye.join(Ve(n,e),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&nt(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await Is.access(Ye.join(a,Je));let s=await bi(n,e);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await As({paths:n,identity:s})).state==="aligned")return!0;continue}if((await _s({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}Ae();ut();L();var RA=["outcome","scope","nonGoals","acceptanceExamples"],Z1=[...RA,"constraints","decisions","openQuestions","verificationExpectations"];var Yn=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change};Ae();J();var iI=At(mt(),1);ze();Ae();J();ke();L();Yt();$s();$s();mr();rr();ze();os();B();J();Os();ie();L();Kg();mr();rr();Ds();ze();import{promises as ea}from"node:fs";import ye from"node:path";ke();Ds();Mn();L();var ir=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Xg(t,e){let r=ye.relative(t,e);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function Ug(t){return JSON.stringify(t.native)}async function Ls(t,e){let r=await oe(t);if(r&&e){if(Ug(r)!==Ug(e))throw new Error(`Native worktree configuration differs from the source project: ${ye.join(t,".comet","config.yaml")}`);return!1}return!r&&e?(await hn(t,e),await Hs(t),!0):!1}async function MA(t,e){if(!Xg(t,e))return!1;let i=`/${ye.relative(t,e).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=re(t,["rev-parse","--git-common-dir"]),a=ye.resolve(t,n),o=ye.join(a,"info","exclude"),s="";try{s=await ea.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await ea.mkdir(ye.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
210
287
|
`)?"":`
|
|
211
|
-
`;return await
|
|
212
|
-
`,"utf8"),!0}function
|
|
288
|
+
`;return await ea.appendFile(o,`${c}${i}
|
|
289
|
+
`,"utf8"),!0}function FA(t,e,r){let i=ye.resolve(t,r??ye.join(".worktrees",e)),n=ye.resolve(t,re(t,["rev-parse","--git-common-dir"]));if(Xg(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(yr(t).some(a=>nt(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function VA(t){try{throw await ea.lstat(t),new Error(`Native worktree path already exists: ${t}`)}catch(e){if(e.code!=="ENOENT")throw e}}async function Yg(t){try{return await ea.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Pd(t){let e=ye.resolve(t.projectRoot);if(t.isolation==="current"){if(t.changeBranch||t.targetBranch||t.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=ge(e);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:e,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:e,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await yt(e,t.sourceConfig?.native.artifact_root??"docs");return Kv([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${t.isolation} workspace`,async()=>{let i=ge(e);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=t.changeBranch??`comet/${t.name}`;uu(e,n);let a=i.currentBranch===n,o=t.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(uu(e,o),!ii(e,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(t.isolation==="branch"){if(t.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let f=!1;if(!a){if(!lu(e))throw new Error("Native branch isolation requires a clean current working directory");if(ii(e,n))throw new Error(`Native change branch already exists: ${n}`);re(e,["switch","-c",n,o]),f=!0}let m;try{m=await Ls(e,t.sourceConfig)}catch(h){throw new ir(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:f,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:e,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:f,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let f=t.worktreePath?ye.resolve(i.primaryWorktreeRoot,t.worktreePath):void 0;if(f&&!nt(f,i.currentWorktreeRoot))throw new Error(`Native worktree path ${f} does not match the current worktree ${i.currentWorktreeRoot}`);let m;try{m=await Ls(e,t.sourceConfig)}catch(h){throw new ir(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:e,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:e,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:e,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Ko(i.primaryWorktreeRoot),c=s.find(f=>f.branch===n);if(c&&await Yg(c.root)){let f=t.worktreePath?ye.resolve(i.primaryWorktreeRoot,t.worktreePath):void 0;if(f&&!nt(f,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await Ls(c.root,t.sourceConfig)}catch(h){throw new ir(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await Yg(c.root)&&(re(i.primaryWorktreeRoot,["worktree","prune"]),s=Ko(i.primaryWorktreeRoot));let l=ii(e,n);if(s.some(f=>f.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=FA(i.primaryWorktreeRoot,t.name,t.worktreePath);await VA(u);let d=await MA(i.primaryWorktreeRoot,u),p={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{re(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),p.createdBranch=!l,p.createdWorktree=!0,p.configInitialized=await Ls(u,t.sourceConfig)}catch(f){throw new ir(`Native worktree preparation is incomplete: ${f.message}`,p,{cause:f})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:p}})}ze();ke();ie();mr();rr();Jo();Yt();_r();xn();Vo();ie();nd();Ho();Yt();_r();B();Rr();xn();L();Rr();xi();ke();Yt();_r();rr();var bI=Dn("en",{compact:!0});async function Id(t){return X(t.paths,`create portable change ${t.name}`,async()=>{if(!$u.test(t.name))throw new Error(`Invalid Native change name: ${t.name}`);t.initialProjectConfig&&await oe(t.paths.projectRoot)===null&&await hn(t.paths.projectRoot,t.initialProjectConfig),fv(t.paths.projectRoot,t.workspaceBinding);let e=(await Gg(t.paths)).filter(o=>o!==t.name);if(e.length>0)throw new Ni(t.workspaceBinding?.isolation??"current",e);let r=ot(t.paths,t.name),i=Ve(t.paths,t.name);await Promise.all([j(t.paths.nativeRoot,r),j(t.paths.runtimeDir,i)]);let n=!1,a=!1;try{await Ir.mkdir(t.paths.changesDir,{recursive:!0}),await Ir.mkdir(r,{recursive:!1}),n=!0,await Ir.mkdir(t.paths.changesRuntimeDir,{recursive:!0}),await Ir.mkdir(i,{recursive:!1}),a=!0,await Ir.mkdir(aw.join(r,"specs"),{recursive:!0}),await ee(aw.join(r,"brief.md"),Dn(t.language,{compact:!0}));let o=sv({name:t.name,language:t.language,workspace:pv(t.workspaceBinding),createdAt:t.now,nextAction:"prepare-shape-confirmation"});return await cv(Tn(t.paths,t.name),o,{containedRoot:t.paths.nativeRoot}),await kr(Xt(t.paths,t.name),Nr({portableState:o,projectRoot:t.paths.projectRoot,branch:Er(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),o}catch(o){throw a&&await Ir.rm(i,{recursive:!0,force:!0}),n&&await Ir.rm(r,{recursive:!0,force:!0}),o}})}ke();ie();mr();rr();Yt();_r();ze();os();J();ze();tt();B();var tq=8*1024*1024;Os();ie();_r();L();var Eq=1024*1024*1024;ie();Vo();xn();rr();ie();rr();ie();sd();ke();ie();var mz=16*1024;async function uw(t,e){return X(t,`select change ${e}`,async()=>{hi(e),await Ou(t,e)?await Nt(t,e):await tr(t,e),await yd(t.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:e,branch:null})})}Ds();dn();import ia from"path";import{realpathSync as uT}from"fs";function dw(t,e){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(t),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:e??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 pw(t){return t?t.command?`${_t.next} ${t.command}`:t.ask_user?`${_t.next} ${t.ask_user}`:null:null}function fw(t,e){let r=[t.summary],i=pw(t.next);return i&&r.push(i),t.user_message&&r.push("",_t.relay,t.user_message),e!==void 0&&r.push("",_t.details,JSON.stringify(e,null,2)),`${r.join(`
|
|
213
290
|
`)}
|
|
214
|
-
`}function
|
|
215
|
-
`)}
|
|
216
|
-
`)}}let r=
|
|
291
|
+
`}function hw(t,e,r){let i=[t.summary],n=pw(t.next);return n&&i.push(n),t.user_message&&i.push("",_t.relay,t.user_message),i.push("",`${_t.detail} ${e}`),r!==void 0&&i.push("",_t.details,JSON.stringify(r,null,2)),i.join(`
|
|
292
|
+
`)}J();Ae();J();var SI=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});xi();lt();ke();L();B();ut();Mn();ie();L();lt();Ar();J();J();Bs();Ei();ut();var mw={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:[]},xI=Pe("comet-native-runtime:v3:scope-reopen"),i2=[{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();Fn();var gw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],D2=new Set(gw),II=new Set([...gw,"minimum_runtime_version","revision"]),L2=new Set([...II,"operation"]),TI=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),B2=new Set([...TI,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);ms();Ae();Ae();ms();J();var W2={maxAcceptanceCriteria:rg.maxCriteria};xi();Jn();Ei();Bs();import{execFile as VI}from"node:child_process";Qr();Pn();xd();import{promisify as qI}from"node:util";B();ut();L();lt();vn();Ar();ie();B();_d();L();rt();xi();ie();Ar();var ra=class extends Error{recovery;constructor(e,r){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Jn();Ms();Ei();var KG=64*1024;var JG=3600*1e3;var UG=qI(VI);Ms();var Vs=class extends Error{details;constructor(e){let r=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=e}};ut();lt();B();rt();L();lt();ks();B();Rr();xi();var KK=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});ut();Mn();ie();L();lt();ks();var qs=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Ws=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};L();ke();function C(t,e,r){return t==="zh-CN"?r:e}var Td={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function bw(t,e){return typeof t=="string"&&Td[t]?C(e,Td[t].en,Td[t].zh):typeof t=="string"?t:""}function jd(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&typeof e.passed=="number"&&typeof e.failed=="number"&&typeof e.blocked=="number"&&typeof e.pending=="number"}function UI(t){let e={total:t.length,passed:0,failed:0,blocked:0,pending:0};for(let r of t){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;e[i]+=1}return e}function Nw(t,e){let r=[];t.failed>0&&r.push(C(e,`${t.failed} failed`,`${t.failed} 项失败`)),t.blocked>0&&r.push(C(e,`${t.blocked} blocked`,`${t.blocked} 项受阻`)),t.pending>0&&r.push(C(e,`${t.pending} pending`,`${t.pending} 项待验`));let i=C(e,`acceptance ${t.passed}/${t.total} passed`,`验收 ${t.passed}/${t.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function kw(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;if(typeof e.change!="string"||e.disposition!=="continue"&&e.disposition!=="await-user"&&e.disposition!=="blocked"&&e.disposition!=="done"||e.commandArgs!==null&&e.commandArgs!==void 0&&!Array.isArray(e.commandArgs))return!1;let r=e.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function $d(t){return/[\u4e00-\u9fff]/u.test(t.userCommunication.agentInstruction)?"zh-CN":"en"}function YI(t,e,r){return t==="done"?C(r,"complete","已完成"):t==="await-user"?C(r,"waiting for a user decision","等待用户决定"):t==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):e?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function XI(t,e,r){let i=$d(t),n=[];r&&n.push(r);let a=C(i,`Change ${t.change}`,`需求 ${t.change}`),o=bw(t.phase,i),s=YI(t.disposition,t.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),e&&e.total>0&&n.push(Nw(e,i));let c=t.userCommunication,l=Sw(t,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Sw(t,e){let r=t.userCommunication;if(t.disposition==="await-user"&&r.required)return{ask_user:C(e,"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(t.commandArgs&&t.commandArgs.length>0)return{command:t.commandArgs.join(" ")};if(t.disposition==="done")return{ask_user:C(e,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(t.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(e,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function QI(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&Array.isArray(e.items)}function ZI(t,e){let r=typeof t.name=="string"?t.name:"(unnamed)",i=bw(t.phase,e),n=t.status==="await-user"?C(e,"waiting for a user decision","等待用户决定"):t.status==="blocked"?C(e,"paused","已暂停"):t.status==="done"?C(e,"complete","已完成"):C(e,"in progress","进行中"),a=jd(t.acceptance)?`${C(e,", ",",")}${Nw(t.acceptance,e)}`:"";return` ${r} · ${i||String(t.phase??"?")} · ${n}${a}`}function eT(t){for(let e of t){let r=e.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function tT(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.healthy!="boolean"?!1:e.findings===void 0||Array.isArray(e.findings)}function rT(t){if(t.healthy){let i=t.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=iT(t.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(t.findings)?t.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 iT(t){return kw(t)?Sw(t,$d(t)):void 0}function Ew(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(tT(e))return rT(e);if(QI(e)){let i=eT(e.items);return{summary:[e.total===e.items.length?C(i,`Native changes (${e.total})`,`Native 需求列表(共 ${e.total} 条)`):C(i,`Native changes (showing ${e.items.length} of ${e.total})`,`Native 需求列表(显示 ${e.items.length}/${e.total} 条)`),...e.items.map(a=>ZI(a,i))].join(`
|
|
293
|
+
`)}}let r=e.continuation;if(kw(r)){let i=$d(r),n=XI(r,nT(e),oT(e,i));return aT(e)==="unconfirmed"?{...n,summary:`${n.summary}${C(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof e.artifactRoot=="string"&&typeof e.nativeRoot=="string"){let i=e.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in e;return{summary:C(i,n?`Comet Native artifacts live under ${e.artifactRoot} (state root: ${e.nativeRoot}).`:`Initialized Comet Native at ${e.nativeRoot} (artifacts: ${e.artifactRoot}).`,n?`Comet Native 产物位于 ${e.artifactRoot}(状态根目录:${e.nativeRoot})。`:`Comet Native 已初始化于 ${e.nativeRoot}(产物目录:${e.artifactRoot})。`)}}}function nT(t){if(jd(t.acceptance))return t.acceptance;let e=t.state;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(jd(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return UI(r.acceptance)}return null}function aT(t){let e=t.localExecution;if(!e||typeof e!="object"||Array.isArray(e))return;let r=e.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function oT(t,e){if(t.selected!==void 0&&typeof t.selected=="string")return C(e,`Selected ${t.selected}.`,`已选择需求 ${t.selected}。`);let r=t.migration;return r&&typeof r=="object"&&r.completed===!0?C(e,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function xw(t){let r=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:{};switch(t.code){case"document-invalid":return{summary:t.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}}Fo();Jo();var Cw=["--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."],Od=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:Cw,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
294
|
comet native spec remove <change-name> <capability>
|
|
218
295
|
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
296
|
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
|
|
222
|
-
${
|
|
223
|
-
`)}`}function
|
|
224
|
-
${r.output}`),r.examples&&i.push("",
|
|
297
|
+
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>]
|
|
298
|
+
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 zs(t,e){return`${t}:
|
|
299
|
+
${e.map(r=>` ${r}`).join(`
|
|
300
|
+
`)}`}function sT(t){let e=t.filter(i=>i!=="--help");if(e.length===0)return"";let r=e.slice(0,2).join(" ");return Od[r]||e.length>1&&Od[e[0]]?.subcommands?r:e[0]}function cT(t=[]){let e=sT(t),r=Od[e];if(!r)throw new Error(`Unknown Native help topic: ${e}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",zs("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",zs("Commands",r.subcommands));let n=e===""?r.options:[...r.options??[],...Cw];return n&&n.length>0&&i.push("",zs("Options",n)),i.push("",`Output:
|
|
301
|
+
${r.output}`),r.examples&&i.push("",zs("Examples",r.examples)),e===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${i.join(`
|
|
225
302
|
`)}
|
|
226
|
-
`}}var
|
|
227
|
-
`}function
|
|
228
|
-
`}:
|
|
229
|
-
${
|
|
230
|
-
${JSON.stringify(
|
|
231
|
-
`}:{exitCode:
|
|
232
|
-
`)}}async function
|
|
303
|
+
`}}var lT=cT().usage;var nU=10*1024*1024,Xe=class extends Error{};function Dd(t,e){let r=t.flatMap((i,n)=>i===e?[n]:[]);if(r.length>1)throw new Xe(`${e} may only be provided once`);return r.length===0?!1:(t.splice(r[0],1),!0)}function pt(t,e){let r=t.flatMap((a,o)=>a===e?[o]:[]);if(r.length>1)throw new Xe(`${e} may only be provided once`);if(r.length===0)return;let i=r[0],n=t[i+1];if(n===void 0||n.startsWith("--"))throw new Xe(`${e} requires a value`);return t.splice(i,2),n}function Rw(t){if(t.length>0)throw new Xe(`Unexpected argument: ${t[0]}`)}function _w(t,e){let r=t.shift();if(!r||r.startsWith("--"))throw new Xe(`${e} is required`);return r}function Aw(t,e="en"){let r=pt(t,"--language")??e;if(r!=="en"&&r!=="zh-CN")throw new Xe("--language must be en or zh-CN");return r}function Hd(t,e){let r=ia.normalize(Pw(t)),i=ia.normalize(Pw(e));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Pw(t){let e=ia.resolve(t);try{return uT.native(e)}catch{return e}}function dT(t,e){let r=ia.resolve(e,t),i=ge(e);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=ge(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!Hd(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||Hd(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:Hd(e,i.currentWorktreeRoot)?ia.resolve(e):i.currentWorktreeRoot}async function Iw(t,e=process.cwd()){return t?dT(t,e):zl(e)}function Tw(t,e){return t==="status"||t==="show"||t==="root"&&e[0]==="show"}function jw(t){return JSON.stringify(t,null,2)+`
|
|
304
|
+
`}function $w(t,e,r){return{command:t,exitCode:0,data:e,text:r??jw(e)}}function pT(t,e){if(e instanceof Yn)return{command:t,exitCode:65,data:{change:e.change,findings:e.findings},error:{code:"document-invalid",message:e.message}};if(e instanceof si)return{command:t,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:e.missingIds,incompleteIds:e.incompleteIds}},error:{code:"invalid-data",message:e.message}};if(e instanceof En)return{command:t,exitCode:65,error:{code:"invalid-data",message:e.message,issues:e.issues}};if(e instanceof Xe)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof qs)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof Ws)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof Ts)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof Ni)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof ir)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof js)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:e.message}};if(e instanceof Vs)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof ra)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let r=e.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Ow(t,e){let r=pT(t,e),i=r.error;if(!i)return r;let n=xw({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function fT(t,e,r=!1){let i=t.envelope??Ew(t.data);return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,agent:dw(t.data,t.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
|
|
305
|
+
`}:t.error?{exitCode:t.exitCode,stderr:i?hw(i,t.error.message,r?t.data:void 0):t.error.message}:i?{exitCode:t.exitCode,stdout:fw(i,r?t.data:void 0)}:r&&t.text!==void 0&&t.data!==void 0&&t.text!==jw(t.data)?{exitCode:t.exitCode,stdout:`${t.text}
|
|
306
|
+
${_t.details}
|
|
307
|
+
${JSON.stringify(t.data,null,2)}
|
|
308
|
+
`}:{exitCode:t.exitCode,stdout:t.text}}function hT(t,e,r=!1){let i=fT(t,e,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function Hw(t,e,r=!1){return hT(t,e,r).output}async function vT(t){let e=await ue({root:t.paths.specsDir,ref:`${t.capability}/spec.md`,maxBytes:null,includeHash:!1}),r=t.capability.split("/"),i=ot(t.paths,t.changeName),n=`specs/${t.capability}/spec.md`,a=`specs/${t.capability}/delta.yaml`;await mT.mkdir(Gs.join(i,"specs",...r),{recursive:!0}),await ee(Gs.join(i,...n.split("/")),e.text,{containedRoot:t.paths.nativeRoot});let o=zt(e.text),s=au(e.text),c={schema:"comet.native.delta.v1",capability:t.capability,base_hash:o,base_version:1,legacy_hash:Oo(e.text),base_requirements:Object.fromEntries(s.requirements.map(l=>[l.id,zt(l.raw)])),operations:[]};return await ee(Gs.join(i,...a.split("/")),nu(c),{containedRoot:t.paths.nativeRoot}),{specSource:n,deltaSource:a,baseHash:o}}async function gT(t,e,r,i){if(!r&&!i)return null;let n=[],a={workflow:"native",currentSpecRoot:`${e}/comet/specs`,archiveRoot:`${e}/comet/archive`};try{if(r&&!i){let l=await qm({projectRoot:t,scope:a,task:r});if(l)return l}let o=i?void 0:await Mm({projectRoot:t,scope:a,reportDiagnostic:l=>n.push(l)}),s=await am({projectRoot:t,scope:a,...o?{provider:o}:{},...r?{task:r}:{},...i?{capability:i}:{}}),c={...s,diagnostics:[...n,...s.diagnostics]};return r&&!i&&await Wm({projectRoot:t,scope:a,task:r,result:c}),c}catch(o){if(i)throw o;return{workflow:"native",query:null,candidates:[],associationDraft:null,diagnostics:[...n,{code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${o instanceof Error?o.message:String(o)}`}],searched:!!r,providerLimit:40}}}async function Dw(t,e){let r=_w(t,"change name"),i=await oe(e),n=Aw(t,i?.native.language??"en"),a=pt(t,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new Xe("--isolation must be current, branch, or worktree");let o=pt(t,"--change-branch"),s=pt(t,"--target-branch"),c=pt(t,"--worktree-path"),l=pt(t,"--task"),u=pt(t,"--capability");Rw(t);let d=i;if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let p=await Pd({projectRoot:e,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:d});e=p.projectRoot,i=await oe(e);let f=i===null?Xh("docs",n):void 0;if(i||(i=f),i.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let m=await yt(e,i.native.artifact_root);await Uh(m),await gd(e);let h=await gT(e,i.native.artifact_root,l,u),v=await Id({paths:m,name:r,language:n,workspaceBinding:p.binding,...f?{initialProjectConfig:f}:{}}),w,y;return h?.associationDraft&&(y=await vT({paths:m,changeName:v.name,capability:h.associationDraft.capability}),w=Gs.join(ot(m,v.name),"capability-association.yaml"),await ee(w,om(h.associationDraft),{containedRoot:m.nativeRoot})),await uw(m,v.name),f&&await Hs(e),{executionCwd:e,...$w("new",{...v,artifacts:Yh(m,v.name),preparation:p.preparation,...h===null?{}:{capabilityDiscovery:h,...w===void 0?{}:{associationPath:w},...y===void 0?{}:{deltaProposal:y}},continuation:Ym(v)},`Created Native change ${v.name}
|
|
309
|
+
`)}}async function Lw(t,e,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Dd(n,"--json"),Dd(n,"--verbose"),c=pt(n,"--project-root");let d=[...n,...a],p=async()=>{let f=await Iw(c);return{executionCwd:f,...await e(d,f)}};l=Tw(t,d)?await rv(p):await p()}catch(d){l=Ow(t,d)}let u=Hw(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
233
310
|
`)?"":`
|
|
234
|
-
`)),u.exitCode}process.exitCode=await
|
|
311
|
+
`)),u.exitCode}process.exitCode=await Lw("new",Dw);
|