@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,208 +1,286 @@
|
|
|
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
|
-
`,r)}var L=S(()=>{"use strict";Xo();Le()});function Dv(e){return e.toLowerCase().startsWith(".env")}function Yr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Dv(i))?"environment-file":r.some(i=>Hv.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Ov.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Ov,Hv,Xr=S(()=>{"use strict";Ov=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Hv=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as Lv}from"node:crypto";import{promises as xe}from"node:fs";import de from"node:path";import{TextDecoder as Bv}from"node:util";function Qo(e,t){let r=de.relative(e,t);return r===""||!de.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${de.sep}`)}function Mv(e){let t=de.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||de.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Yr(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function Fv(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Vv(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Se(r,i)?j(r,i):j(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Su(e){let t=await xe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await xe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function qv(e,t){let r=de.resolve(e),i=de.resolve(t);if(!Qo(r,i))throw new Error("Native artifact path is outside its root");let n=[await Su(r)],a=r;for(let o of de.relative(r,i).split(de.sep).filter(Boolean)){a=de.join(a,o);let s=await Su(a);if(!Qo(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Eu(e){for(let t of e){let r=await xe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Vv(t,r)||await xe.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function T(e){let t=Mv(e.ref),r=e.maxBytes===null?null:Fv(e.maxBytes??Zo),i=de.resolve(e.root,...t.split("/")),n=await qv(e.root,de.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await xe.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await xe.realpath(i);if(!Qo(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await xe.open(i,"r");try{let[l,c,u]=await Promise.all([s.stat(),xe.lstat(i),xe.realpath(i)]);if(await Eu(n),!l.isFile()||!c.isFile()||c.isSymbolicLink()||u!==o||!vn(a,l)||!vn(l,c))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?h.length:r+1-f,k=await s.read(h,0,Math.min(h.length,N),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([s.stat(),xe.lstat(i),xe.realpath(i)]);if(await Eu(n),!p.isFile()||p.isSymbolicLink()||v!==o||!vn(l,m)||!vn(l,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),w;try{w=new Bv("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:e.includeHash===!1?null:Lv("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var Zo,fe=S(()=>{"use strict";Xr();Le();Zo=1024*1024});var R=y(Y=>{"use strict";var es=Symbol.for("yaml.alias"),xu=Symbol.for("yaml.document"),gn=Symbol.for("yaml.map"),Cu=Symbol.for("yaml.pair"),ts=Symbol.for("yaml.scalar"),wn=Symbol.for("yaml.seq"),Xe=Symbol.for("yaml.node.type"),Wv=e=>!!e&&typeof e=="object"&&e[Xe]===es,zv=e=>!!e&&typeof e=="object"&&e[Xe]===xu,Gv=e=>!!e&&typeof e=="object"&&e[Xe]===gn,Jv=e=>!!e&&typeof e=="object"&&e[Xe]===Cu,Pu=e=>!!e&&typeof e=="object"&&e[Xe]===ts,Uv=e=>!!e&&typeof e=="object"&&e[Xe]===wn;function Ru(e){if(e&&typeof e=="object")switch(e[Xe]){case gn:case wn:return!0}return!1}function Kv(e){if(e&&typeof e=="object")switch(e[Xe]){case es:case gn:case ts:case wn:return!0}return!1}var Yv=e=>(Pu(e)||Ru(e))&&!!e.anchor;Y.ALIAS=es;Y.DOC=xu;Y.MAP=gn;Y.NODE_TYPE=Xe;Y.PAIR=Cu;Y.SCALAR=ts;Y.SEQ=wn;Y.hasAnchor=Yv;Y.isAlias=Wv;Y.isCollection=Ru;Y.isDocument=zv;Y.isMap=Gv;Y.isNode=Kv;Y.isPair=Jv;Y.isScalar=Pu;Y.isSeq=Uv});var Qr=y(rs=>{"use strict";var z=R(),ne=Symbol("break visit"),_u=Symbol("skip children"),Be=Symbol("remove node");function yn(e,t){let r=Au(t);z.isDocument(e)?ur(null,e.contents,r,Object.freeze([e]))===Be&&(e.contents=null):ur(null,e,r,Object.freeze([]))}yn.BREAK=ne;yn.SKIP=_u;yn.REMOVE=Be;function ur(e,t,r,i){let n=Iu(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Tu(e,i,n),ur(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=ur(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ne)return ne;o===Be&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=ur("key",t.key,r,i);if(a===ne)return ne;a===Be&&(t.key=null);let o=ur("value",t.value,r,i);if(o===ne)return ne;o===Be&&(t.value=null)}}return n}async function Nn(e,t){let r=Au(t);z.isDocument(e)?await dr(null,e.contents,r,Object.freeze([e]))===Be&&(e.contents=null):await dr(null,e,r,Object.freeze([]))}Nn.BREAK=ne;Nn.SKIP=_u;Nn.REMOVE=Be;async function dr(e,t,r,i){let n=await Iu(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Tu(e,i,n),dr(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await dr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ne)return ne;o===Be&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=await dr("key",t.key,r,i);if(a===ne)return ne;a===Be&&(t.key=null);let o=await dr("value",t.value,r,i);if(o===ne)return ne;o===Be&&(t.value=null)}}return n}function Au(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Iu(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(z.isMap(t))return r.Map?.(e,t,i);if(z.isSeq(t))return r.Seq?.(e,t,i);if(z.isPair(t))return r.Pair?.(e,t,i);if(z.isScalar(t))return r.Scalar?.(e,t,i);if(z.isAlias(t))return r.Alias?.(e,t,i)}function Tu(e,t,r){let i=t[t.length-1];if(z.isCollection(i))i.items[e]=r;else if(z.isPair(i))e==="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`)}}rs.visit=yn;rs.visitAsync=Nn});var is=y($u=>{"use strict";var ju=R(),Xv=Qr(),Qv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Zv=e=>e.replace(/[!,[\]{}]/g,t=>Qv[t]),Zr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.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(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} 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==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Zv(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&ju.isNode(t.contents)){let a={};Xv.visit(t.contents,(o,s)=>{ju.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:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
7
|
-
`)}};
|
|
8
|
-
`)?
|
|
4
|
+
var _g=Object.create;var md=Object.defineProperty;var Ag=Object.getOwnPropertyDescriptor;var Ig=Object.getOwnPropertyNames;var Tg=Object.getPrototypeOf,$g=Object.prototype.hasOwnProperty;var Ln=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var S=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var y=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var jg=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ig(t))!$g.call(e,n)&&n!==r&&md(e,n,{get:()=>t[n],enumerable:!(i=Ag(t,n))||i.enumerable});return e};var Ct=(e,t,r)=>(r=e!=null?_g(Tg(e)):{},jg(t||!e||!e.__esModule?md(r,"default",{value:e,enumerable:!0}):r,e));function xs(){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 Er,pi,vd,hi=S(()=>{"use strict";Er="comet.native.v4",pi="comet.native.local-execution.v4",vd=["multi-session","single-session"]});import{createHash as Og}from"crypto";function Re(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Hg(e,t){t.has(e)&&Re("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||Re("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Re("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Re("symbol properties are not supported"),`[${e.map(i=>Cs(i,t)).join(",")}]`}finally{t.delete(e)}}function Dg(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Re("only plain objects are supported"),t.has(e)&&Re("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Re("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Re("accessor properties are not supported"),`${JSON.stringify(o)}:${Cs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Cs(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Re("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Hg(e,t):Dg(e,t);case"bigint":case"function":case"symbol":case"undefined":return Re(`${typeof e} values are not supported`)}return Re("unsupported value type")}function Ps(e){return Cs(e,new Set)}function D(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return Og("sha256").update(`${e}
|
|
5
|
+
${Ps(t)}`).digest("hex")}var K=S(()=>{"use strict"});function Rs(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new mi({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var mi,Bn=S(()=>{"use strict";mi=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 vi=S(()=>{"use strict"});var Mn=S(()=>{"use strict";Bn();vi()});var Fn,zt=S(()=>{"use strict";K();Mn();Fn=3});import{AsyncLocalStorage as Jg}from"node:async_hooks";import{performance as Wn}from"node:perf_hooks";function _s(e=0){Ug+=1,Kg+=e;let t=Yg.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function zn(e){let t=Wn.now();try{return e()}finally{_s(Wn.now()-t)}}async function As(e){let t=Wn.now();try{return await e()}finally{_s(Wn.now()-t)}}var Ug,Kg,Yg,xr=S(()=>{"use strict";Ug=0,Kg=0,Yg=new Jg});import{existsSync as Xg}from"node:fs";import gi from"node:path";function Nd(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function Zg(e){let t=(Nd(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function ew(e,t,r){let n=gi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Nd(t,"PATH")??"").split(gi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=gi.win32.extname(e)?[e]:Zg(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(l=>s?gi.join(s,l):gi.resolve(r,l)))}function Gn(e,t,r){return ew(e,t,r).find(i=>Xg(i))??e}function Is(e){if(e.some(t=>Qg.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var Qg,uA,wi=S(()=>{"use strict";Qg=/[&|<>()^%"!\r\n]/u,uA=["$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 tw,execFileSync as pA}from"node:child_process";import kd from"node:path";async function Pt(e,t,r={}){let i=r.timeoutMs??rw,n=r.maxBufferBytes??iw;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=kd.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Gn(e,o,a):e,l=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);l&&Is(t);let c=()=>new Promise((u,d)=>{let f=!1,m=tw(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:l},(g,w,b)=>{f||(f=!0,clearTimeout(v),r.signal?.removeEventListener("abort",p),g?d(new yi(e,t,b.trim(),{cause:g,timedOut:nw(g)})):u(w))}),h=g=>{f||(f=!0,clearTimeout(v),r.signal?.removeEventListener("abort",p),m.kill("SIGKILL"),m.stdin?.destroy(),m.stdout?.destroy(),m.stderr?.destroy(),m.unref(),d(new yi(e,t,"",{timedOut:g})))},p=()=>h(!1),v=setTimeout(()=>h(!0),i);r.signal?.addEventListener("abort",p,{once:!0}),r.signal?.aborted&&p(),m.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(kd.win32.basename(e))?As(c):c()}function nw(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var rw,iw,yi,Jn=S(()=>{"use strict";xr();wi();rw=6e4,iw=8*1024*1024;yi=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}});import{promises as $s}from"node:fs";async function js(e,t){let r;for(let i=0;i<=Ts.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Ts.length||!dw.has(a??""))throw n;await new Promise(o=>setTimeout(o,Ts[i]))}throw r}async function Os(e,t){await js(()=>$s.rename(e,t),`rename ${t}`)}async function Hs(e){await js(()=>$s.unlink(e),`unlink ${e}`)}async function Ds(e,t){await js(()=>$s.link(e,t),`link ${t}`)}var dw,Ts,Ls=S(()=>{"use strict";dw=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Ts=[50,100,200]});function Rt(e){return e!==0&&e!==0n&&e!=="0"}function Ae(e,t){return Rt(e.dev)&&Rt(t.dev)&&Rt(e.ino)&&Rt(t.ino)}function j(e,t){let r=Rt(e.dev)&&Rt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Rt(e.ino)&&Rt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Ni=S(()=>{"use strict"});var Ge=S(()=>{"use strict";Ni()});import{randomUUID as fw}from"crypto";import{promises as ie}from"fs";import Ie from"path";function Kn(e,t){let r=Ie.relative(e,t);return r===""||!Ie.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ie.sep}`)}function pw(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Yn(e,t){return j({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function hw(e,t){return Yn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Pd(e){let t=await ie.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 ie.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Rr(e){for(let t of e){let r=await ie.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!pw(t,r)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function mw(e,t,r){let[i,n]=await Promise.all([ie.lstat(e),ie.realpath(e),r?Rr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Yn(i,t)||r&&!Kn(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function vw(e,t){let r=Ie.resolve(e),i=Ie.resolve(t);if(!Kn(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Pd(r)],a=Ie.relative(r,i).split(Ie.sep).filter(Boolean),o=r;for(let s of a){await Rr(n),o=Ie.join(o,s);try{await ie.mkdir(o)}catch(c){if(c.code!=="EEXIST")throw c}let l=await Pd(o);if(!Kn(n[0].realPath,l.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(l)}return await Rr(n),n}async function gw(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 ww(e,t,r={}){let i=Ie.dirname(e),n=r.containedRoot?await vw(r.containedRoot,i):null;n||await ie.mkdir(i,{recursive:!0});let a=Ie.join(i,`.${Ie.basename(e)}.${fw()}.tmp`),o,s,l;try{if(await r.beforeTemporaryOpen?.(),o=await ie.open(a,"wx"),s=await o.stat(),n){let[c,u]=await Promise.all([ie.lstat(a),ie.realpath(a)]);if(await Rr(n),!c.isFile()||c.isSymbolicLink()||!Yn(s,c)||!Kn(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(),l=await o.stat(),!Yn(s,l))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!l)throw new Error("Native atomic write temporary file was not written");if(l=await mw(a,l,n),await r.beforeCommit?.(),n){await Rr(n);let c=await ie.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!l||!hw(c,l))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await Ds(a,e),await Hs(a)):await Os(a,e),await gw(i)}catch(c){if(await o?.close(),!n)await ie.rm(a,{force:!0});else try{await Rr(n),await ie.rm(a,{force:!0})}catch{}throw c}}async function ve(e,t,r={}){await ww(e,t,r)}async function Z(e,t,r={}){await ve(e,JSON.stringify(t,null,2)+`
|
|
6
|
+
`,r)}var B=S(()=>{"use strict";Ls();Ge()});function Nw(e){return e.toLowerCase().startsWith(".env")}function ki(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Nw(i))?"environment-file":r.some(i=>bw.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>yw.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var yw,bw,Si=S(()=>{"use strict";yw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),bw=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as kw}from"node:crypto";import{promises as Te}from"node:fs";import ge from"node:path";import{TextDecoder as Sw}from"node:util";function Bs(e,t){let r=ge.relative(e,t);return r===""||!ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ge.sep}`)}function Ew(e){let t=ge.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ge.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=ki(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function xw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Cw(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ae(r,i)?j(r,i):j(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Rd(e){let t=await Te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Pw(e,t){let r=ge.resolve(e),i=ge.resolve(t);if(!Bs(r,i))throw new Error("Native artifact path is outside its root");let n=[await Rd(r)],a=r;for(let o of ge.relative(r,i).split(ge.sep).filter(Boolean)){a=ge.join(a,o);let s=await Rd(a);if(!Bs(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function _d(e){for(let t of e){let r=await Te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Cw(t,r)||await Te.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function $(e){let t=Ew(e.ref),r=e.maxBytes===null?null:xw(e.maxBytes??Ms),i=ge.resolve(e.root,...t.split("/")),n=await Pw(e.root,ge.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Te.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await Te.realpath(i);if(!Bs(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Te.open(i,"r");try{let[l,c,u]=await Promise.all([s.stat(),Te.lstat(i),Te.realpath(i)]);if(await _d(n),!l.isFile()||!c.isFile()||c.isSymbolicLink()||u!==o||!Xn(a,l)||!Xn(l,c))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let b=r===null?m.length:r+1-f,k=await s.read(m,0,Math.min(m.length,b),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(m.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[h,p,v]=await Promise.all([s.stat(),Te.lstat(i),Te.realpath(i)]);if(await _d(n),!p.isFile()||p.isSymbolicLink()||v!==o||!Xn(l,h)||!Xn(l,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),w;try{w=new Sw("utf-8",{fatal:!0}).decode(g)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:b})}return{ref:t,size:f,hash:e.includeHash===!1?null:kw("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var Ms,we=S(()=>{"use strict";Si();Ge();Ms=1024*1024});var _=y(ee=>{"use strict";var Fs=Symbol.for("yaml.alias"),Ad=Symbol.for("yaml.document"),Qn=Symbol.for("yaml.map"),Id=Symbol.for("yaml.pair"),qs=Symbol.for("yaml.scalar"),Zn=Symbol.for("yaml.seq"),ct=Symbol.for("yaml.node.type"),Rw=e=>!!e&&typeof e=="object"&&e[ct]===Fs,_w=e=>!!e&&typeof e=="object"&&e[ct]===Ad,Aw=e=>!!e&&typeof e=="object"&&e[ct]===Qn,Iw=e=>!!e&&typeof e=="object"&&e[ct]===Id,Td=e=>!!e&&typeof e=="object"&&e[ct]===qs,Tw=e=>!!e&&typeof e=="object"&&e[ct]===Zn;function $d(e){if(e&&typeof e=="object")switch(e[ct]){case Qn:case Zn:return!0}return!1}function $w(e){if(e&&typeof e=="object")switch(e[ct]){case Fs:case Qn:case qs:case Zn:return!0}return!1}var jw=e=>(Td(e)||$d(e))&&!!e.anchor;ee.ALIAS=Fs;ee.DOC=Ad;ee.MAP=Qn;ee.NODE_TYPE=ct;ee.PAIR=Id;ee.SCALAR=qs;ee.SEQ=Zn;ee.hasAnchor=jw;ee.isAlias=Rw;ee.isCollection=$d;ee.isDocument=_w;ee.isMap=Aw;ee.isNode=$w;ee.isPair=Iw;ee.isScalar=Td;ee.isSeq=Tw});var Ei=y(Vs=>{"use strict";var J=_(),se=Symbol("break visit"),jd=Symbol("skip children"),Je=Symbol("remove node");function ea(e,t){let r=Od(t);J.isDocument(e)?_r(null,e.contents,r,Object.freeze([e]))===Je&&(e.contents=null):_r(null,e,r,Object.freeze([]))}ea.BREAK=se;ea.SKIP=jd;ea.REMOVE=Je;function _r(e,t,r,i){let n=Hd(e,t,r,i);if(J.isNode(n)||J.isPair(n))return Dd(e,i,n),_r(e,n,r,i);if(typeof n!="symbol"){if(J.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=_r(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===se)return se;o===Je&&(t.items.splice(a,1),a-=1)}}}else if(J.isPair(t)){i=Object.freeze(i.concat(t));let a=_r("key",t.key,r,i);if(a===se)return se;a===Je&&(t.key=null);let o=_r("value",t.value,r,i);if(o===se)return se;o===Je&&(t.value=null)}}return n}async function ta(e,t){let r=Od(t);J.isDocument(e)?await Ar(null,e.contents,r,Object.freeze([e]))===Je&&(e.contents=null):await Ar(null,e,r,Object.freeze([]))}ta.BREAK=se;ta.SKIP=jd;ta.REMOVE=Je;async function Ar(e,t,r,i){let n=await Hd(e,t,r,i);if(J.isNode(n)||J.isPair(n))return Dd(e,i,n),Ar(e,n,r,i);if(typeof n!="symbol"){if(J.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Ar(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===se)return se;o===Je&&(t.items.splice(a,1),a-=1)}}}else if(J.isPair(t)){i=Object.freeze(i.concat(t));let a=await Ar("key",t.key,r,i);if(a===se)return se;a===Je&&(t.key=null);let o=await Ar("value",t.value,r,i);if(o===se)return se;o===Je&&(t.value=null)}}return n}function Od(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Hd(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(J.isMap(t))return r.Map?.(e,t,i);if(J.isSeq(t))return r.Seq?.(e,t,i);if(J.isPair(t))return r.Pair?.(e,t,i);if(J.isScalar(t))return r.Scalar?.(e,t,i);if(J.isAlias(t))return r.Alias?.(e,t,i)}function Dd(e,t,r){let i=t[t.length-1];if(J.isCollection(i))i.items[e]=r;else if(J.isPair(i))e==="key"?i.key=r:i.value=r;else if(J.isDocument(i))i.contents=r;else{let n=J.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Vs.visit=ea;Vs.visitAsync=ta});var Ws=y(Bd=>{"use strict";var Ld=_(),Ow=Ei(),Hw={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Dw=e=>e.replace(/[!,[\]{}]/g,t=>Hw[t]),xi=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.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(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} 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==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Dw(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Ld.isNode(t.contents)){let a={};Ow.visit(t.contents,(o,s)=>{Ld.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:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
7
|
+
`)}};xi.defaultYaml={explicit:!1,version:"1.2"};xi.defaultTags={"!!":"tag:yaml.org,2002:"};Bd.Directives=xi});var ra=y(Ci=>{"use strict";var Md=_(),Lw=Ei();function Bw(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Fd(e){let t=new Set;return Lw.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function qd(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Mw(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Fd(e));let o=qd(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Md.isScalar(o.node)||Md.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}}Ci.anchorIsValid=Bw;Ci.anchorNames=Fd;Ci.createNodeAnchors=Mw;Ci.findNewAnchor=qd});var zs=y(Vd=>{"use strict";function Pi(e,t,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=Pi(e,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=Pi(e,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=Pi(e,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=Pi(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Vd.applyReviver=Pi});var _t=y(zd=>{"use strict";var Fw=_();function Wd(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Wd(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Fw.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}zd.toJS=Wd});var ia=y(Jd=>{"use strict";var qw=zs(),Gd=_(),Vw=_t(),Gs=class{constructor(t){Object.defineProperty(this,Gd.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Gd.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Vw.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof a=="function"?qw.applyReviver(a,{"":s},"",s):s}};Jd.NodeBase=Gs});var Ri=y(Ud=>{"use strict";var Ww=ra(),zw=Ei(),Ir=_(),Gw=ia(),Jw=_t(),Js=class extends Gw.NodeBase{constructor(t){super(Ir.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],zw.visit(t,{Node:(a,o)=>{(Ir.isAlias(o)||Ir.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(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let s=i.get(o);if(s||(Jw.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=na(n,o,i)),s.count*s.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Ww.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function na(e,t,r){if(Ir.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Ir.isCollection(t)){let i=0;for(let n of t.items){let a=na(e,n,r);a>i&&(i=a)}return i}else if(Ir.isPair(t)){let i=na(e,t.key,r),n=na(e,t.value,r);return Math.max(i,n)}return 1}Ud.Alias=Js});var q=y(Us=>{"use strict";var Uw=_(),Kw=ia(),Yw=_t(),Xw=e=>!e||typeof e!="function"&&typeof e!="object",At=class extends Kw.NodeBase{constructor(t){super(Uw.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Yw.toJS(this.value,t,r)}toString(){return String(this.value)}};At.BLOCK_FOLDED="BLOCK_FOLDED";At.BLOCK_LITERAL="BLOCK_LITERAL";At.PLAIN="PLAIN";At.QUOTE_DOUBLE="QUOTE_DOUBLE";At.QUOTE_SINGLE="QUOTE_SINGLE";Us.Scalar=At;Us.isScalarValue=Xw});var _i=y(Yd=>{"use strict";var Qw=Ri(),Ut=_(),Kd=q(),Zw="tag:yaml.org,2002:";function ey(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function ty(e,t,r){if(Ut.isDocument(e)&&(e=e.contents),Ut.isNode(e))return e;if(Ut.isPair(e)){let d=r.schema[Ut.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,l;if(i&&e&&typeof e=="object"){if(l=s.get(e),l)return l.anchor??(l.anchor=n(e)),new Qw.Alias(l.anchor);l={anchor:null,node:null},s.set(e,l)}t?.startsWith("!!")&&(t=Zw+t.slice(2));let c=ey(e,t,o.tags);if(!c){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Kd.Scalar(e);return l&&(l.node=d),d}c=e instanceof Map?o[Ut.MAP]:Symbol.iterator in Object(e)?o[Ut.SEQ]:o[Ut.MAP]}a&&(a(c),delete r.onTagObj);let u=c?.createNode?c.createNode(r.schema,e,r):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(r.schema,e,r):new Kd.Scalar(e);return t?u.tag=t:c.default||(u.tag=c.tag),l&&(l.node=u),u}Yd.createNode=ty});var oa=y(aa=>{"use strict";var ry=_i(),Ue=_(),iy=ia();function Ks(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return ry.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Xd=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ys=class extends iy.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Ue.isNode(i)||Ue.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Xd(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Ue.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ks(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ue.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Ue.isScalar(a)?a.value:a:Ue.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ue.isPair(r))return!1;let i=r.value;return i==null||t&&Ue.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ue.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ue.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ks(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};aa.Collection=Ys;aa.collectionFromPath=Ks;aa.isEmptyPath=Xd});var Ai=y(sa=>{"use strict";var ny=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Xs(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var ay=(e,t,r)=>e.endsWith(`
|
|
8
|
+
`)?Xs(r,t):r.includes(`
|
|
9
9
|
`)?`
|
|
10
|
-
`+
|
|
11
|
-
`)r===
|
|
12
|
-
`&&
|
|
13
|
-
`&&k!==" "&&(f=p)}if(p>=d)if(f)c.push(f),d=f+l,f=void 0;else if(r===
|
|
14
|
-
${t}${e.slice(0,
|
|
15
|
-
${t}${e.slice(k+1,
|
|
16
|
-
`);i=t,n=t+1,a=e[n]}return i}
|
|
17
|
-
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function
|
|
10
|
+
`+Xs(r,t):(e.endsWith(" ")?"":" ")+r;sa.indentComment=Xs;sa.lineComment=ay;sa.stringifyComment=ny});var Zd=y(Ii=>{"use strict";var oy="flow",Qs="block",ca="quoted";function sy(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let l=Math.max(1+a,1+n-t.length);if(e.length<=l)return e;let c=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?c.push(0):d=n-i);let f,m,h=!1,p=-1,v=-1,g=-1;r===Qs&&(p=Qd(e,p,t.length),p!==-1&&(d=p+l));for(let b;b=e[p+=1];){if(r===ca&&b==="\\"){switch(v=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(b===`
|
|
11
|
+
`)r===Qs&&(p=Qd(e,p,t.length)),d=p+t.length+l,f=void 0;else{if(b===" "&&m&&m!==" "&&m!==`
|
|
12
|
+
`&&m!==" "){let k=e[p+1];k&&k!==" "&&k!==`
|
|
13
|
+
`&&k!==" "&&(f=p)}if(p>=d)if(f)c.push(f),d=f+l,f=void 0;else if(r===ca){for(;m===" "||m===" ";)m=b,b=e[p+=1],h=!0;let k=p>g+1?p-2:v-1;if(u[k])return e;c.push(k),u[k]=!0,d=k+l,f=void 0}else h=!0}m=b}if(h&&s&&s(),c.length===0)return e;o&&o();let w=e.slice(0,c[0]);for(let b=0;b<c.length;++b){let k=c[b],x=c[b+1]||e.length;k===0?w=`
|
|
14
|
+
${t}${e.slice(0,x)}`:(r===ca&&u[k]&&(w+=`${e[k]}\\`),w+=`
|
|
15
|
+
${t}${e.slice(k+1,x)}`)}return w}function Qd(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
16
|
+
`);i=t,n=t+1,a=e[n]}return i}Ii.FOLD_BLOCK=Qs;Ii.FOLD_FLOW=oy;Ii.FOLD_QUOTED=ca;Ii.foldFlowLines=sy});var $i=y(ef=>{"use strict";var $e=q(),It=Zd(),ua=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),da=e=>/^(%|---|\.\.\.)/m.test(e);function cy(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
17
|
+
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Ti(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(da(e)?" ":""),o="",s=0;for(let l=0,c=r[l];c;c=r[++l])if(c===" "&&r[l+1]==="\\"&&r[l+2]==="n"&&(o+=r.slice(s,l)+"\\ ",l+=1,s=l,c="\\"),c==="\\")switch(r[l+1]){case"u":{o+=r.slice(s,l);let u=r.substr(l+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(l,6)}l+=5,s=l+1}break;case"n":if(i||r[l+2]==='"'||r.length<n)l+=1;else{for(o+=r.slice(s,l)+`
|
|
18
18
|
|
|
19
19
|
`;r[l+2]==="\\"&&r[l+3]==="n"&&r[l+4]!=='"';)o+=`
|
|
20
|
-
`,l+=2;o+=a,r[l+2]===" "&&(o+="\\"),l+=1,s=l+1}break;default:l+=1}return o=s?o+r.slice(s):r,i?o:
|
|
21
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
22
|
-
${r}`)+"'";return t.implicitKey?i:
|
|
20
|
+
`,l+=2;o+=a,r[l+2]===" "&&(o+="\\"),l+=1,s=l+1}break;default:l+=1}return o=s?o+r.slice(s):r,i?o:It.foldFlowLines(o,a,It.FOLD_QUOTED,ua(t,!1))}function Zs(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
21
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Ti(e,t);let r=t.indent||(da(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
22
|
+
${r}`)+"'";return t.implicitKey?i:It.foldFlowLines(i,r,It.FOLD_FLOW,ua(t,!1))}function Tr(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Ti;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Zs:a&&!n?i=Ti:i=r?Zs:Ti}return i(e,t)}var ec;try{ec=new RegExp(`(^|(?<!
|
|
23
23
|
))
|
|
24
24
|
+(?!
|
|
25
|
-
|$)`,"g")}catch{
|
|
25
|
+
|$)`,"g")}catch{ec=/\n+(?!\n|$)/g}function la({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:l}=i.options;if(!o||/\n[\t ]+$/.test(r))return Tr(r,i);let c=i.indent||(i.forceBlockIndent||da(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===$e.Scalar.BLOCK_FOLDED?!1:t===$e.Scalar.BLOCK_LITERAL?!0:!cy(r,l,c.length);if(!r)return u?`|
|
|
26
26
|
`:`>
|
|
27
|
-
`;let d,f;for(f=r.length;f>0;--f){let
|
|
28
|
-
`&&
|
|
29
|
-
`);
|
|
30
|
-
`&&(
|
|
31
|
-
`)g=v;else break}let w=r.substring(0,g<v?g+1:v);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${c}`));let k=(p?c?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let
|
|
32
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),
|
|
33
|
-
${c}${
|
|
34
|
-
${c}${w}${r}${
|
|
35
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
36
|
-
`)?
|
|
37
|
-
`))return
|
|
38
|
-
${l}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:
|
|
39
|
-
${t.indent}${s}`:s}
|
|
40
|
-
${s}:`):(v=`${v}:`,f&&(v+=
|
|
41
|
-
`:"",w){let
|
|
42
|
-
${
|
|
43
|
-
`&&
|
|
27
|
+
`;let d,f;for(f=r.length;f>0;--f){let x=r[f-1];if(x!==`
|
|
28
|
+
`&&x!==" "&&x!==" ")break}let m=r.substring(f),h=m.indexOf(`
|
|
29
|
+
`);h===-1?d="-":r===m||h!==m.length-1?(d="+",a&&a()):d="",m&&(r=r.slice(0,-m.length),m[m.length-1]===`
|
|
30
|
+
`&&(m=m.slice(0,-1)),m=m.replace(ec,`$&${c}`));let p=!1,v,g=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")p=!0;else if(x===`
|
|
31
|
+
`)g=v;else break}let w=r.substring(0,g<v?g+1:v);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${c}`));let k=(p?c?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let x=r.replace(/\n+/g,`
|
|
32
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),E=!1,H=ua(i,!0);o!=="folded"&&t!==$e.Scalar.BLOCK_FOLDED&&(H.onOverflow=()=>{E=!0});let N=It.foldFlowLines(`${w}${x}${m}`,c,It.FOLD_BLOCK,H);if(!E)return`>${k}
|
|
33
|
+
${c}${N}`}return r=r.replace(/\n+/g,`$&${c}`),`|${k}
|
|
34
|
+
${c}${w}${r}${m}`}function ly(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:l,indentStep:c,inFlow:u}=t;if(s&&a.includes(`
|
|
35
|
+
`)||u&&/[[\]{},]/.test(a))return Tr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
36
|
+
`)?Tr(a,t):la(e,t,r,i);if(!s&&!u&&n!==$e.Scalar.PLAIN&&a.includes(`
|
|
37
|
+
`))return la(e,t,r,i);if(da(a)){if(l==="")return t.forceBlockIndent=!0,la(e,t,r,i);if(s&&l===c)return Tr(a,t)}let d=a.replace(/\n+/g,`$&
|
|
38
|
+
${l}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:m,tags:h}=t.doc.schema;if(h.some(f)||m?.some(f))return Tr(a,t)}return s?d:It.foldFlowLines(d,l,It.FOLD_FLOW,ua(t,!1))}function uy(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==$e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=$e.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case $e.Scalar.BLOCK_FOLDED:case $e.Scalar.BLOCK_LITERAL:return n||a?Tr(o.value,t):la(o,t,r,i);case $e.Scalar.QUOTE_DOUBLE:return Ti(o.value,t);case $e.Scalar.QUOTE_SINGLE:return Zs(o.value,t);case $e.Scalar.PLAIN:return ly(o,t,r,i);default:return null}},c=l(s);if(c===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(c=l(f),c===null)throw new Error(`Unsupported default string type ${f}`)}return c}ef.stringifyString=uy});var ji=y(tc=>{"use strict";var dy=ra(),Tt=_(),fy=Ai(),py=$i();function hy(e,t){let r=Object.assign({blockQuote:!0,commentString:fy.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function my(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(Tt.isScalar(t)){i=t.value;let n=e.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===t.format)??n.find(a=>!a.format)}else i=t,r=e.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 vy(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Tt.isScalar(e)||Tt.isCollection(e))&&e.anchor;a&&dy.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function gy(e,t,r,i){if(Tt.isPair(e))return e.toString(t,r,i);if(Tt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Tt.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>n=l});n??(n=my(t.doc.schema.tags,a));let o=vy(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):Tt.isScalar(a)?py.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Tt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
39
|
+
${t.indent}${s}`:s}tc.createStringifyContext=hy;tc.stringify=gy});var af=y(nf=>{"use strict";var lt=_(),tf=q(),rf=ji(),Oi=Ai();function wy({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=r,f=lt.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(lt.isCollection(e)||!lt.isNode(e)&&typeof e=="object"){let H="With simple keys, collection cannot be used as a key value";throw new Error(H)}}let m=!d&&(!e||f&&t==null&&!r.inFlow||lt.isCollection(e)||(lt.isScalar(e)?e.type===tf.Scalar.BLOCK_FOLDED||e.type===tf.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(d||!a),indent:s+l});let h=!1,p=!1,v=rf.stringify(e,r,()=>h=!0,()=>p=!0);if(!m&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(a||t==null)return h&&i&&i(),v===""?"?":m?`? ${v}`:v}else if(a&&!d||t==null&&m)return v=`? ${v}`,f&&!h?v+=Oi.lineComment(v,r.indent,c(f)):p&&n&&n(),v;h&&(f=null),m?(f&&(v+=Oi.lineComment(v,r.indent,c(f))),v=`? ${v}
|
|
40
|
+
${s}:`):(v=`${v}:`,f&&(v+=Oi.lineComment(v,r.indent,c(f))));let g,w,b;lt.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,b=t.comment):(g=!1,w=null,b=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!m&&!f&<.isScalar(t)&&(r.indentAtStart=v.length+1),p=!1,!u&&l.length>=2&&!r.inFlow&&!m&<.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let k=!1,x=rf.stringify(t,r,()=>k=!0,()=>p=!0),E=" ";if(f||g||w){if(E=g?`
|
|
41
|
+
`:"",w){let H=c(w);E+=`
|
|
42
|
+
${Oi.indentComment(H,r.indent)}`}x===""&&!r.inFlow?E===`
|
|
43
|
+
`&&b&&(E=`
|
|
44
44
|
|
|
45
|
-
`):
|
|
46
|
-
${r.indent}`}else if(!
|
|
47
|
-
`),
|
|
48
|
-
${r.indent}`)}}else(
|
|
49
|
-
`)&&(
|
|
45
|
+
`):E+=`
|
|
46
|
+
${r.indent}`}else if(!m&<.isCollection(t)){let H=x[0],N=x.indexOf(`
|
|
47
|
+
`),z=N!==-1,xt=r.inFlow??t.flow??t.items.length===0;if(z||!xt){let Sr=!1;if(z&&(H==="&"||H==="!")){let G=x.indexOf(" ");H==="&"&&G!==-1&&G<N&&x[G+1]==="!"&&(G=x.indexOf(" ",G+1)),(G===-1||N<G)&&(Sr=!0)}Sr||(E=`
|
|
48
|
+
${r.indent}`)}}else(x===""||x[0]===`
|
|
49
|
+
`)&&(E="");return v+=E+x,r.inFlow?k&&i&&i():b&&!k?v+=Oi.lineComment(v,r.indent,c(b)):p&&n&&n(),v}nf.stringifyPair=wy});var ic=y(rc=>{"use strict";var of=Ln("process");function yy(e,...t){e==="debug"&&console.log(...t)}function by(e,t){(e==="debug"||e==="warn")&&(typeof of.emitWarning=="function"?of.emitWarning(t):console.warn(t))}rc.debug=yy;rc.warn=by});var va=y(ma=>{"use strict";var ha=_(),sf=q(),fa="<<",pa={identify:e=>e===fa||typeof e=="symbol"&&e.description===fa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new sf.Scalar(Symbol(fa)),{addToJSMap:cf}),stringify:()=>fa},Ny=(e,t)=>(pa.identify(t)||ha.isScalar(t)&&(!t.type||t.type===sf.Scalar.PLAIN)&&pa.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===pa.tag&&r.default);function cf(e,t,r){let i=lf(e,r);if(ha.isSeq(i))for(let n of i.items)nc(e,t,n);else if(Array.isArray(i))for(let n of i)nc(e,t,n);else nc(e,t,i)}function nc(e,t,r){let i=lf(e,r);if(!ha.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function lf(e,t){return e&&ha.isAlias(t)?t.resolve(e.doc,e):t}ma.addMergeToJSMap=cf;ma.isMergeKey=Ny;ma.merge=pa});var oc=y(ff=>{"use strict";var ky=ic(),uf=va(),Sy=ji(),df=_(),ac=_t();function Ey(e,t,{key:r,value:i}){if(df.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(uf.isMergeKey(e,r))uf.addMergeToJSMap(e,t,i);else{let n=ac.toJS(r,"",e);if(t instanceof Map)t.set(n,ac.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=xy(r,n,e),o=ac.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function xy(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(df.isNode(e)&&r?.doc){let i=Sy.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=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),ky.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(t)}ff.addPairToJSMap=Ey});var $t=y(sc=>{"use strict";var pf=_i(),Cy=af(),Py=oc(),ga=_();function Ry(e,t,r){let i=pf.createNode(e,void 0,r),n=pf.createNode(t,void 0,r);return new wa(i,n)}var wa=class e{constructor(t,r=null){Object.defineProperty(this,ga.NODE_TYPE,{value:ga.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return ga.isNode(r)&&(r=r.clone(t)),ga.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Py.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?Cy.stringifyPair(this,t,r,i):JSON.stringify(this)}};sc.Pair=wa;sc.createPair=Ry});var cc=y(mf=>{"use strict";var Kt=_(),hf=ji(),ya=Ai();function _y(e,t,r){return(t.inFlow??e.flow?Iy:Ay)(e,t,r)}function Ay({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:l,options:{commentString:c}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let h=0;h<t.length;++h){let p=t[h],v=null;if(Kt.isNode(p))!d&&p.spaceBefore&&f.push(""),ba(r,f,p.commentBefore,d),p.comment&&(v=p.comment);else if(Kt.isPair(p)){let w=Kt.isNode(p.key)?p.key:null;w&&(!d&&w.spaceBefore&&f.push(""),ba(r,f,w.commentBefore,d))}d=!1;let g=hf.stringify(p,u,()=>v=null,()=>d=!0);v&&(g+=ya.lineComment(g,a,c(v))),d&&v&&(d=!1),f.push(i+g)}let m;if(f.length===0)m=n.start+n.end;else{m=f[0];for(let h=1;h<f.length;++h){let p=f[h];m+=p?`
|
|
50
50
|
${l}${p}`:`
|
|
51
|
-
`}}return e?(
|
|
52
|
-
`+
|
|
53
|
-
`)),
|
|
51
|
+
`}}return e?(m+=`
|
|
52
|
+
`+ya.indentComment(c(e),l),s&&s()):d&&o&&o(),m}function Iy({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let l=Object.assign({},t,{indent:i,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let h=0;h<e.length;++h){let p=e[h],v=null;if(Kt.isNode(p))p.spaceBefore&&d.push(""),ba(t,d,p.commentBefore,!1),p.comment&&(v=p.comment);else if(Kt.isPair(p)){let w=Kt.isNode(p.key)?p.key:null;w&&(w.spaceBefore&&d.push(""),ba(t,d,w.commentBefore,!1),w.comment&&(c=!0));let b=Kt.isNode(p.value)?p.value:null;b?(b.comment&&(v=b.comment),b.commentBefore&&(c=!0)):p.value==null&&w?.comment&&(v=w.comment)}v&&(c=!0);let g=hf.stringify(p,l,()=>v=null);c||(c=d.length>u||g.includes(`
|
|
53
|
+
`)),h<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(c||(c=d.reduce((w,b)=>w+b.length+2,2)+(g.length+2)>t.options.lineWidth)),c&&(g+=",")),v&&(g+=ya.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:f,end:m}=r;if(d.length===0)return f+m;if(!c){let h=d.reduce((p,v)=>p+v.length+2,2);c=t.options.lineWidth>0&&h>t.options.lineWidth}if(c){let h=f;for(let p of d)h+=p?`
|
|
54
54
|
${a}${n}${p}`:`
|
|
55
|
-
`;return`${
|
|
56
|
-
${n}${
|
|
57
|
-
`:" ")}return
|
|
55
|
+
`;return`${h}
|
|
56
|
+
${n}${m}`}else return`${f}${o}${d.join(" ")}${o}${m}`}function ba({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=ya.indentComment(t(i),e);r.push(a.trimStart())}}mf.stringifyCollection=_y});var Ot=y(uc=>{"use strict";var Ty=cc(),$y=oc(),jy=oa(),jt=_(),Na=$t(),Oy=q();function Hi(e,t){let r=jt.isScalar(t)?t.value:t;for(let i of e)if(jt.isPair(i)&&(i.key===t||i.key===r||jt.isScalar(i.key)&&i.key.value===r))return i}var lc=class extends jy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(jt.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(l,c)=>{if(typeof a=="function")c=a.call(r,l,c);else if(Array.isArray(a)&&!a.includes(l))return;(c!==void 0||n)&&o.items.push(Na.createPair(l,c,i))};if(r instanceof Map)for(let[l,c]of r)s(l,c);else if(r&&typeof r=="object")for(let l of Object.keys(r))s(l,r[l]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;jt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Na.Pair(t,t?.value):i=new Na.Pair(t.key,t.value);let n=Hi(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);jt.isScalar(n.value)&&Oy.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(t){let r=Hi(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Hi(this.items,t)?.value;return(!r&&jt.isScalar(n)?n.value:n)??void 0}has(t){return!!Hi(this.items,t)}set(t,r){this.add(new Na.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)$y.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!jt.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Ty.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};uc.YAMLMap=lc;uc.findPair=Hi});var $r=y(gf=>{"use strict";var Hy=_(),vf=Ot(),Dy={collection:"map",default:!0,nodeClass:vf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Hy.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>vf.YAMLMap.from(e,t,r)};gf.map=Dy});var Ht=y(wf=>{"use strict";var Ly=_i(),By=cc(),My=oa(),Sa=_(),Fy=q(),qy=_t(),dc=class extends My.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Sa.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=ka(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=ka(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Sa.isScalar(n)?n.value:n}has(t){let r=ka(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=ka(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Sa.isScalar(n)&&Fy.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(qy.toJS(a,String(n++),r));return i}toString(t,r,i){return t?By.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let l=r instanceof Set?s:String(o++);s=n.call(r,l,s)}a.items.push(Ly.createNode(s,void 0,i))}}return a}};function ka(e){let t=Sa.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}wf.YAMLSeq=dc});var jr=y(bf=>{"use strict";var Vy=_(),yf=Ht(),Wy={collection:"seq",default:!0,nodeClass:yf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Vy.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>yf.YAMLSeq.from(e,t,r)};bf.seq=Wy});var Di=y(Nf=>{"use strict";var zy=$i(),Gy={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),zy.stringifyString(e,t,r,i)}};Nf.string=Gy});var Ea=y(Ef=>{"use strict";var kf=q(),Sf={identify:e=>e==null,createNode:()=>new kf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new kf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Sf.test.test(e)?e:t.options.nullStr};Ef.nullTag=Sf});var fc=y(Cf=>{"use strict";var Jy=q(),xf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Jy.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&xf.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Cf.boolTag=xf});var Or=y(Pf=>{"use strict";function Uy({format:e,minFractionDigits:t,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(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Pf.stringifyNumber=Uy});var hc=y(xa=>{"use strict";var Ky=q(),pc=Or(),Yy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:pc.stringifyNumber},Xy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():pc.stringifyNumber(e)}},Qy={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 Ky.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:pc.stringifyNumber};xa.float=Qy;xa.floatExp=Xy;xa.floatNaN=Yy});var vc=y(Pa=>{"use strict";var Rf=Or(),Ca=e=>typeof e=="bigint"||Number.isInteger(e),mc=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function _f(e,t,r){let{value:i}=e;return Ca(i)&&i>=0?r+i.toString(t):Rf.stringifyNumber(e)}var Zy={identify:e=>Ca(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>mc(e,2,8,r),stringify:e=>_f(e,8,"0o")},eb={identify:Ca,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>mc(e,0,10,r),stringify:Rf.stringifyNumber},tb={identify:e=>Ca(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>mc(e,2,16,r),stringify:e=>_f(e,16,"0x")};Pa.int=eb;Pa.intHex=tb;Pa.intOct=Zy});var If=y(Af=>{"use strict";var rb=$r(),ib=Ea(),nb=jr(),ab=Di(),ob=fc(),gc=hc(),wc=vc(),sb=[rb.map,nb.seq,ab.string,ib.nullTag,ob.boolTag,wc.intOct,wc.int,wc.intHex,gc.floatNaN,gc.floatExp,gc.float];Af.schema=sb});var jf=y($f=>{"use strict";var cb=q(),lb=$r(),ub=jr();function Tf(e){return typeof e=="bigint"||Number.isInteger(e)}var Ra=({value:e})=>JSON.stringify(e),db=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ra},{identify:e=>e==null,createNode:()=>new cb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ra},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ra},{identify:Tf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Tf(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Ra}],fb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},pb=[lb.map,ub.seq].concat(db,fb);$f.schema=pb});var bc=y(Of=>{"use strict";var Li=Ln("buffer"),yc=q(),hb=$i(),mb={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Li.Buffer=="function")return Li.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.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 t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof Li.Buffer=="function")s=o instanceof Li.Buffer?o.toString("base64"):Li.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<o.length;++c)l+=String.fromCharCode(o[c]);s=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=yc.Scalar.BLOCK_LITERAL),t!==yc.Scalar.QUOTE_DOUBLE){let l=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),c=Math.ceil(s.length/l),u=new Array(c);for(let d=0,f=0;d<c;++d,f+=l)u[d]=s.substr(f,l);s=u.join(t===yc.Scalar.BLOCK_LITERAL?`
|
|
57
|
+
`:" ")}return hb.stringifyString({comment:e,type:t,value:s},i,n,a)}};Of.binary=mb});var Ia=y(Aa=>{"use strict";var _a=_(),Nc=$t(),vb=q(),gb=Ht();function Hf(e,t){if(_a.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!_a.isPair(i)){if(_a.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Nc.Pair(new vb.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
|
|
58
58
|
${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
|
|
59
|
-
${a.comment}`:i.comment}i=n}e.items[r]=Un.isPair(i)?i:new $s.Pair(i)}}else t("Expected a sequence for this tag");return e}function Id(e,t,r){let{replacer:i}=r,n=new jw.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,l;if(Array.isArray(o))if(o.length===2)s=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)s=c[0],l=o[s];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else s=o;n.items.push($s.createPair(s,l,r))}return n}var $w={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ad,createNode:Id};Kn.createPairs=Id;Kn.pairs=$w;Kn.resolvePairs=Ad});var Ds=y(Hs=>{"use strict";var Td=R(),Os=wt(),pi=Et(),Ow=xt(),jd=Yn(),Lt=class e extends Ow.YAMLSeq{constructor(){super(),this.add=pi.YAMLMap.prototype.add.bind(this),this.delete=pi.YAMLMap.prototype.delete.bind(this),this.get=pi.YAMLMap.prototype.get.bind(this),this.has=pi.YAMLMap.prototype.has.bind(this),this.set=pi.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(Td.isPair(n)?(a=Os.toJS(n.key,"",r),o=Os.toJS(n.value,a,r)):a=Os.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=jd.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Lt.tag="tag:yaml.org,2002:omap";var Hw={collection:"seq",identify:e=>e instanceof Map,nodeClass:Lt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=jd.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Td.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Lt,r)},createNode:(e,t,r)=>Lt.from(e,t,r)};Hs.YAMLOMap=Lt;Hs.omap=Hw});var Ld=y(Ls=>{"use strict";var $d=M();function Od({value:e,source:t},r){return t&&(e?Hd:Dd).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Hd={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 $d.Scalar(!0),stringify:Od},Dd={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 $d.Scalar(!1),stringify:Od};Ls.falseTag=Dd;Ls.trueTag=Hd});var Bd=y(Xn=>{"use strict";var Dw=M(),Bs=vr(),Lw={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:Bs.stringifyNumber},Bw={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():Bs.stringifyNumber(e)}},Mw={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 Dw.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:Bs.stringifyNumber};Xn.float=Mw;Xn.floatExp=Bw;Xn.floatNaN=Lw});var Fd=y(mi=>{"use strict";var Md=vr(),hi=e=>typeof e=="bigint"||Number.isInteger(e);function Qn(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 Ms(e,t,r){let{value:i}=e;if(hi(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Md.stringifyNumber(e)}var Fw={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Qn(e,2,2,r),stringify:e=>Ms(e,2,"0b")},Vw={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Qn(e,1,8,r),stringify:e=>Ms(e,8,"0")},qw={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Qn(e,0,10,r),stringify:Md.stringifyNumber},Ww={identify:hi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Qn(e,2,16,r),stringify:e=>Ms(e,16,"0x")};mi.int=qw;mi.intBin=Fw;mi.intHex=Ww;mi.intOct=Vw});var Vs=y(Fs=>{"use strict";var ta=R(),Zn=kt(),ea=Et(),Bt=class e extends ea.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;ta.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Zn.Pair(t.key,null):r=new Zn.Pair(t,null),ea.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=ea.findPair(this.items,t);return!r&&ta.isPair(i)?ta.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=ea.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Zn.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(Zn.createPair(o,null,i));return a}};Bt.tag="tag:yaml.org,2002:set";var zw={collection:"map",identify:e=>e instanceof Set,nodeClass:Bt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Bt.from(e,t,r),resolve(e,t){if(ta.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Bt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Fs.YAMLSet=Bt;Fs.set=zw});var Ws=y(ra=>{"use strict";var Gw=vr();function qs(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 Vd(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Gw.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 Jw={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})=>qs(e,r),stringify:Vd},Uw={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=>qs(e,!1),stringify:Vd},qd={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(qd.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),l=t[7]?Number((t[7]+"00").substr(1,3)):0,c=Date.UTC(r,i-1,n,a||0,o||0,s||0,l),u=t[8];if(u&&u!=="Z"){let d=qs(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ra.floatTime=Uw;ra.intTime=Jw;ra.timestamp=qd});var Gd=y(zd=>{"use strict";var Kw=hr(),Yw=qn(),Xw=mr(),Qw=di(),Zw=js(),Wd=Ld(),zs=Bd(),ia=Fd(),ey=On(),ty=Ds(),ry=Yn(),iy=Vs(),Gs=Ws(),ny=[Kw.map,Xw.seq,Qw.string,Yw.nullTag,Wd.trueTag,Wd.falseTag,ia.intBin,ia.intOct,ia.int,ia.intHex,zs.floatNaN,zs.floatExp,zs.float,Zw.binary,ey.merge,ty.omap,ry.pairs,iy.set,Gs.intTime,Gs.floatTime,Gs.timestamp];zd.schema=ny});var rf=y(Ks=>{"use strict";var Yd=hr(),ay=qn(),Xd=mr(),oy=di(),sy=xs(),Js=Ps(),Us=_s(),cy=xd(),ly=Rd(),Qd=js(),vi=On(),Zd=Ds(),ef=Yn(),Jd=Gd(),tf=Vs(),na=Ws(),Ud=new Map([["core",cy.schema],["failsafe",[Yd.map,Xd.seq,oy.string]],["json",ly.schema],["yaml11",Jd.schema],["yaml-1.1",Jd.schema]]),Kd={binary:Qd.binary,bool:sy.boolTag,float:Js.float,floatExp:Js.floatExp,floatNaN:Js.floatNaN,floatTime:na.floatTime,int:Us.int,intHex:Us.intHex,intOct:Us.intOct,intTime:na.intTime,map:Yd.map,merge:vi.merge,null:ay.nullTag,omap:Zd.omap,pairs:ef.pairs,seq:Xd.seq,set:tf.set,timestamp:na.timestamp},uy={"tag:yaml.org,2002:binary":Qd.binary,"tag:yaml.org,2002:merge":vi.merge,"tag:yaml.org,2002:omap":Zd.omap,"tag:yaml.org,2002:pairs":ef.pairs,"tag:yaml.org,2002:set":tf.set,"tag:yaml.org,2002:timestamp":na.timestamp};function dy(e,t,r){let i=Ud.get(t);if(i&&!e)return r&&!i.includes(vi.merge)?i.concat(vi.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Ud.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(vi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Kd[o]:o;if(!s){let l=JSON.stringify(o),c=Object.keys(Kd).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return a.includes(s)||a.push(s),a},[])}Ks.coreKnownTags=uy;Ks.getTags=dy});var Qs=y(nf=>{"use strict";var Ys=R(),fy=hr(),py=mr(),hy=di(),aa=rf(),my=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Xs=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?aa.getTags(t,"compat"):t?aa.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?aa.coreKnownTags:{},this.tags=aa.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Ys.MAP,{value:fy.map}),Object.defineProperty(this,Ys.SCALAR,{value:hy.string}),Object.defineProperty(this,Ys.SEQ,{value:py.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?my:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};nf.Schema=Xs});var of=y(af=>{"use strict";var vy=R(),Zs=ci(),gi=ni();function gy(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);l?(r.push(l),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Zs.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let l=a(e.commentBefore);r.unshift(gi.indentComment(l,""))}let o=!1,s=null;if(e.contents){if(vy.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(gi.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let l=s?void 0:()=>o=!0,c=Zs.stringify(e.contents,n,()=>s=null,l);s&&(c+=gi.lineComment(c,"",a(s))),(c[0]==="|"||c[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${c}`:r.push(c)}else r.push(Zs.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let l=a(e.comment);l.includes(`
|
|
60
|
-
`)?(r.push("..."),r.push(
|
|
59
|
+
${a.comment}`:i.comment}i=n}e.items[r]=_a.isPair(i)?i:new Nc.Pair(i)}}else t("Expected a sequence for this tag");return e}function Df(e,t,r){let{replacer:i}=r,n=new gb.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,l;if(Array.isArray(o))if(o.length===2)s=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)s=c[0],l=o[s];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else s=o;n.items.push(Nc.createPair(s,l,r))}return n}var wb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Hf,createNode:Df};Aa.createPairs=Df;Aa.pairs=wb;Aa.resolvePairs=Hf});var Ec=y(Sc=>{"use strict";var Lf=_(),kc=_t(),Bi=Ot(),yb=Ht(),Bf=Ia(),Yt=class e extends yb.YAMLSeq{constructor(){super(),this.add=Bi.YAMLMap.prototype.add.bind(this),this.delete=Bi.YAMLMap.prototype.delete.bind(this),this.get=Bi.YAMLMap.prototype.get.bind(this),this.has=Bi.YAMLMap.prototype.has.bind(this),this.set=Bi.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(Lf.isPair(n)?(a=kc.toJS(n.key,"",r),o=kc.toJS(n.value,a,r)):a=kc.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=Bf.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Yt.tag="tag:yaml.org,2002:omap";var bb={collection:"seq",identify:e=>e instanceof Map,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Bf.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Lf.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Yt,r)},createNode:(e,t,r)=>Yt.from(e,t,r)};Sc.YAMLOMap=Yt;Sc.omap=bb});var Wf=y(xc=>{"use strict";var Mf=q();function Ff({value:e,source:t},r){return t&&(e?qf:Vf).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var qf={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Mf.Scalar(!0),stringify:Ff},Vf={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 Mf.Scalar(!1),stringify:Ff};xc.falseTag=Vf;xc.trueTag=qf});var zf=y(Ta=>{"use strict";var Nb=q(),Cc=Or(),kb={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:Cc.stringifyNumber},Sb={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():Cc.stringifyNumber(e)}},Eb={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 Nb.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:Cc.stringifyNumber};Ta.float=Eb;Ta.floatExp=Sb;Ta.floatNaN=kb});var Jf=y(Fi=>{"use strict";var Gf=Or(),Mi=e=>typeof e=="bigint"||Number.isInteger(e);function $a(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 Pc(e,t,r){let{value:i}=e;if(Mi(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Gf.stringifyNumber(e)}var xb={identify:Mi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>$a(e,2,2,r),stringify:e=>Pc(e,2,"0b")},Cb={identify:Mi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>$a(e,1,8,r),stringify:e=>Pc(e,8,"0")},Pb={identify:Mi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>$a(e,0,10,r),stringify:Gf.stringifyNumber},Rb={identify:Mi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>$a(e,2,16,r),stringify:e=>Pc(e,16,"0x")};Fi.int=Pb;Fi.intBin=xb;Fi.intHex=Rb;Fi.intOct=Cb});var _c=y(Rc=>{"use strict";var Ha=_(),ja=$t(),Oa=Ot(),Xt=class e extends Oa.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Ha.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new ja.Pair(t.key,null):r=new ja.Pair(t,null),Oa.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Oa.findPair(this.items,t);return!r&&Ha.isPair(i)?Ha.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=Oa.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new ja.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(ja.createPair(o,null,i));return a}};Xt.tag="tag:yaml.org,2002:set";var _b={collection:"map",identify:e=>e instanceof Set,nodeClass:Xt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Xt.from(e,t,r),resolve(e,t){if(Ha.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Xt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Rc.YAMLSet=Xt;Rc.set=_b});var Ic=y(Da=>{"use strict";var Ab=Or();function Ac(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 Uf(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Ab.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 Ib={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})=>Ac(e,r),stringify:Uf},Tb={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=>Ac(e,!1),stringify:Uf},Kf={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(Kf.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),l=t[7]?Number((t[7]+"00").substr(1,3)):0,c=Date.UTC(r,i-1,n,a||0,o||0,s||0,l),u=t[8];if(u&&u!=="Z"){let d=Ac(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Da.floatTime=Tb;Da.intTime=Ib;Da.timestamp=Kf});var Qf=y(Xf=>{"use strict";var $b=$r(),jb=Ea(),Ob=jr(),Hb=Di(),Db=bc(),Yf=Wf(),Tc=zf(),La=Jf(),Lb=va(),Bb=Ec(),Mb=Ia(),Fb=_c(),$c=Ic(),qb=[$b.map,Ob.seq,Hb.string,jb.nullTag,Yf.trueTag,Yf.falseTag,La.intBin,La.intOct,La.int,La.intHex,Tc.floatNaN,Tc.floatExp,Tc.float,Db.binary,Lb.merge,Bb.omap,Mb.pairs,Fb.set,$c.intTime,$c.floatTime,$c.timestamp];Xf.schema=qb});var cp=y(Hc=>{"use strict";var rp=$r(),Vb=Ea(),ip=jr(),Wb=Di(),zb=fc(),jc=hc(),Oc=vc(),Gb=If(),Jb=jf(),np=bc(),qi=va(),ap=Ec(),op=Ia(),Zf=Qf(),sp=_c(),Ba=Ic(),ep=new Map([["core",Gb.schema],["failsafe",[rp.map,ip.seq,Wb.string]],["json",Jb.schema],["yaml11",Zf.schema],["yaml-1.1",Zf.schema]]),tp={binary:np.binary,bool:zb.boolTag,float:jc.float,floatExp:jc.floatExp,floatNaN:jc.floatNaN,floatTime:Ba.floatTime,int:Oc.int,intHex:Oc.intHex,intOct:Oc.intOct,intTime:Ba.intTime,map:rp.map,merge:qi.merge,null:Vb.nullTag,omap:ap.omap,pairs:op.pairs,seq:ip.seq,set:sp.set,timestamp:Ba.timestamp},Ub={"tag:yaml.org,2002:binary":np.binary,"tag:yaml.org,2002:merge":qi.merge,"tag:yaml.org,2002:omap":ap.omap,"tag:yaml.org,2002:pairs":op.pairs,"tag:yaml.org,2002:set":sp.set,"tag:yaml.org,2002:timestamp":Ba.timestamp};function Kb(e,t,r){let i=ep.get(t);if(i&&!e)return r&&!i.includes(qi.merge)?i.concat(qi.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(ep.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(qi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?tp[o]:o;if(!s){let l=JSON.stringify(o),c=Object.keys(tp).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return a.includes(s)||a.push(s),a},[])}Hc.coreKnownTags=Ub;Hc.getTags=Kb});var Bc=y(lp=>{"use strict";var Dc=_(),Yb=$r(),Xb=jr(),Qb=Di(),Ma=cp(),Zb=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Lc=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ma.getTags(t,"compat"):t?Ma.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ma.coreKnownTags:{},this.tags=Ma.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Dc.MAP,{value:Yb.map}),Object.defineProperty(this,Dc.SCALAR,{value:Qb.string}),Object.defineProperty(this,Dc.SEQ,{value:Xb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Zb:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};lp.Schema=Lc});var dp=y(up=>{"use strict";var eN=_(),Mc=ji(),Vi=Ai();function tN(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);l?(r.push(l),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Mc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let l=a(e.commentBefore);r.unshift(Vi.indentComment(l,""))}let o=!1,s=null;if(e.contents){if(eN.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Vi.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let l=s?void 0:()=>o=!0,c=Mc.stringify(e.contents,n,()=>s=null,l);s&&(c+=Vi.lineComment(c,"",a(s))),(c[0]==="|"||c[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${c}`:r.push(c)}else r.push(Mc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let l=a(e.comment);l.includes(`
|
|
60
|
+
`)?(r.push("..."),r.push(Vi.indentComment(l,""))):r.push(`... ${l}`)}else r.push("...");else{let l=e.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Vi.indentComment(a(l),"")))}return r.join(`
|
|
61
61
|
`)+`
|
|
62
|
-
`}
|
|
62
|
+
`}up.stringifyDocument=tN});var Wi=y(fp=>{"use strict";var rN=Ri(),Hr=oa(),ye=_(),iN=$t(),nN=_t(),aN=Bc(),oN=dp(),Fc=ra(),sN=zs(),cN=_i(),qc=Ws(),Vc=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ye.NODE_TYPE,{value:ye.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 qc.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[ye.NODE_TYPE]:{value:ye.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=ye.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Dr(this.contents)&&this.contents.add(t)}addIn(t,r){Dr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Fc.anchorNames(this);t.anchor=!r||i.has(r)?Fc.findNewAnchor(r||"a",i):r}return new rN.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=r.filter(v).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:c,tag:u}=i??{},{onAnchor:d,setAnchors:f,sourceObjects:m}=Fc.createNodeAnchors(this,o||"a"),h={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:n,schema:this.schema,sourceObjects:m},p=cN.createNode(t,u,h);return s&&ye.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new iN.Pair(n,a)}delete(t){return Dr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Hr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Dr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return ye.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return Hr.isEmptyPath(t)?!r&&ye.isScalar(this.contents)?this.contents.value:this.contents:ye.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return ye.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Hr.isEmptyPath(t)?this.contents!==void 0:ye.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=Hr.collectionFromPath(this.schema,[t],r):Dr(this.contents)&&this.contents.set(t,r)}setIn(t,r){Hr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=Hr.collectionFromPath(this.schema,Array.from(t),r):Dr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new qc.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new qc.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new aN.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},l=nN.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:c,res:u}of s.anchors.values())a(u,c);return typeof o=="function"?sN.applyReviver(o,{"":l},"",l):l}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return oN.stringifyDocument(this,t)}};function Dr(e){if(ye.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}fp.Document=Vc});var Ji=y(Gi=>{"use strict";var zi=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Wc=class extends zi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},zc=class extends zi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},lN=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.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=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
63
63
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,l=r.linePos[1];l?.line===i&&l.col>n&&(s=Math.max(1,Math.min(l.col-n,80-a)));let c=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
64
64
|
|
|
65
65
|
${o}
|
|
66
66
|
${c}
|
|
67
|
-
`}};
|
|
68
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(
|
|
69
|
-
`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||
|
|
70
|
-
`+
|
|
71
|
-
`+
|
|
72
|
-
|
|
73
|
-
`+
|
|
74
|
-
`+v.comment:c.comment=v.comment),c.range=[i.offset,p,v.offset]}else c.range=[i.offset,p,p];return c}
|
|
75
|
-
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:p,type:a,comment:n.comment,range:[i,v,v]}}let l=t.indent+n.indent,c=t.offset+n.length,u=0;for(let p=0;p<s;++p){let[v,g]=o[p];if(g===""||g==="\r")n.indent===0&&v.length>l&&(l=v.length);else{v.length<l&&r(c+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(l=v.length),u=p,l===0&&!e.atRoot&&r(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=v.length+g.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>l&&(s=p+1);let d="",f="",
|
|
76
|
-
`;for(let p=u;p<s;++p){let[v,g]=o[p];c+=v.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&v.length<l){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(c-g.length-(w?2:1),"BAD_INDENT",k),v=""}a===
|
|
67
|
+
`}};Gi.YAMLError=zi;Gi.YAMLParseError=Wc;Gi.YAMLWarning=zc;Gi.prettifyError=lN});var Ui=y(pp=>{"use strict";function uN(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let l=!1,c=s,u=s,d="",f="",m=!1,h=!1,p=null,v=null,g=null,w=null,b=null,k=null,x=null;for(let N of e)switch(h&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),p&&(c&&N.type!=="comment"&&N.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),N.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&N.source.includes(" ")&&(p=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let z=N.source.substring(1)||" ";d?d+=f+z:d=z,f="",c=!1;break}case"newline":c?d?d+=N.source:(!k||r!=="seq-item-ind")&&(l=!0):f+=N.source,c=!0,m=!0,(v||g)&&(w=N),u=!0;break;case"anchor":v&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=N,x??(x=N.offset),c=!1,u=!1,h=!0;break;case"tag":{g&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),g=N,x??(x=N.offset),c=!1,u=!1,h=!0;break}case r:(v||g)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),k=N,c=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){b&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),b=N,c=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),c=!1,u=!1}let E=e[e.length-1],H=E?E.offset+E.source.length:n;return h&&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"),p&&(c&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:k,spaceBefore:l,comment:d,hasNewline:m,anchor:v,tag:g,newlineAfterProp:w,end:H,start:x??H}}pp.resolveProps=uN});var Fa=y(hp=>{"use strict";function Gc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
68
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(Gc(t.key)||Gc(t.value))return!0}return!1;default:return!0}}hp.containsNewline=Gc});var Jc=y(mp=>{"use strict";var dN=Fa();function fN(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&dN.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}mp.flowIndentCheck=fN});var Uc=y(gp=>{"use strict";var vp=_();function pN(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||vp.isScalar(a)&&vp.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}gp.mapIncludes=pN});var Sp=y(kp=>{"use strict";var wp=$t(),hN=Ot(),yp=Ui(),mN=Fa(),bp=Jc(),vN=Uc(),Np="All mapping items must start at the same column";function gN({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??hN.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let l=i.offset,c=null;for(let u of i.items){let{start:d,key:f,sep:m,value:h}=u,p=yp.resolveProps(d,{indicator:"explicit-key-ind",next:f??m?.[0],offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!p.found;if(v){if(f&&(f.type==="block-seq"?n(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&n(l,"BAD_INDENT",Np)),!p.anchor&&!p.tag&&!m){c=p.end,p.comment&&(s.comment?s.comment+=`
|
|
69
|
+
`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||mN.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&n(l,"BAD_INDENT",Np);r.atKey=!0;let g=p.end,w=f?e(r,f,p,n):t(r,g,d,null,p,n);r.schema.compat&&bp.flowIndentCheck(i.indent,f,n),r.atKey=!1,vN.mapIncludes(r,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let b=yp.resolveProps(m??[],{indicator:"map-value-ind",next:h,offset:w.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=b.end,b.found){v&&(h?.type==="block-map"&&!b.hasNewline&&n(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&p.start<b.found.offset-1024&&n(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=h?e(r,h,b,n):t(r,l,m,null,b,n);r.schema.compat&&bp.flowIndentCheck(i.indent,h,n),l=k.range[2];let x=new wp.Pair(w,k);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(w.comment?w.comment+=`
|
|
70
|
+
`+b.comment:w.comment=b.comment);let k=new wp.Pair(w);r.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return c&&c<l&&n(c,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,l,c??l],s}kp.resolveBlockMap=gN});var xp=y(Ep=>{"use strict";var wN=Ht(),yN=Ui(),bN=Jc();function NN({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??wN.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let l=i.offset,c=null;for(let{start:u,value:d}of i.items){let f=yN.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(l,"MISSING_CHAR","Sequence item without - indicator");else{c=f.end,f.comment&&(s.comment=f.comment);continue}let m=d?e(r,d,f,n):t(r,f.end,u,null,f,n);r.schema.compat&&bN.flowIndentCheck(i.indent,d,n),l=m.range[2],s.items.push(m)}return s.range=[i.offset,l,c??l],s}Ep.resolveBlockSeq=NN});var Lr=y(Cp=>{"use strict";function kN(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:l,type:c}=s;switch(c){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=l.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=l),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=l.length}}return{comment:n,offset:t}}Cp.resolveEnd=kN});var Ap=y(_p=>{"use strict";var SN=_(),EN=$t(),Pp=Ot(),xN=Ht(),CN=Lr(),Rp=Ui(),PN=Fa(),RN=Uc(),Kc="Block collections are not allowed within flow collections",Yc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function _N({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",l=a?.nodeClass??(o?Pp.YAMLMap:xN.YAMLSeq),c=new l(r.schema);c.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 g=i.items[v],{start:w,key:b,sep:k,value:x}=g,E=Rp.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:b??k?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!x){v===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(c.comment?c.comment+=`
|
|
71
|
+
`+E.comment:c.comment=E.comment),d=E.end;continue}!o&&r.options.strict&&PN.containsNewline(b)&&n(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let H="";e:for(let N of w)switch(N.type){case"comma":case"space":break;case"comment":H=N.source.substring(1);break e;default:break e}if(H){let N=c.items[c.items.length-1];SN.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
|
|
72
|
+
`+H:N.comment=H,E.comment=E.comment.substring(H.length+1)}}if(!o&&!k&&!E.found){let H=x?e(r,x,E,n):t(r,E.end,k,null,E,n);c.items.push(H),d=H.range[2],Yc(x)&&n(H.range,"BLOCK_IN_FLOW",Kc)}else{r.atKey=!0;let H=E.end,N=b?e(r,b,E,n):t(r,H,w,null,E,n);Yc(b)&&n(N.range,"BLOCK_IN_FLOW",Kc),r.atKey=!1;let z=Rp.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:x,offset:N.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(z.found){if(!o&&!E.found&&r.options.strict){if(k)for(let G of k){if(G===z.found)break;if(G.type==="newline"){n(G,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<z.found.offset-1024&&n(z.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(z.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let xt=x?e(r,x,z,n):z.found?t(r,z.end,k,null,z,n):null;xt?Yc(x)&&n(xt.range,"BLOCK_IN_FLOW",Kc):z.comment&&(N.comment?N.comment+=`
|
|
73
|
+
`+z.comment:N.comment=z.comment);let Sr=new EN.Pair(N,xt);if(r.options.keepSourceTokens&&(Sr.srcToken=g),o){let G=c;RN.mapIncludes(r,G.items,N)&&n(H,"DUPLICATE_KEY","Map keys must be unique"),G.items.push(Sr)}else{let G=new Pp.YAMLMap(r.schema);G.flow=!0,G.items.push(Sr);let hd=(xt??N).range;G.range=[N.range[0],hd[1],hd[2]],c.items.push(G)}d=xt?xt.range[2]:z.end}}let f=o?"}":"]",[m,...h]=i.end,p=d;if(m?.source===f)p=m.offset+m.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${f}`:`${v} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",g),m&&m.source.length!==1&&h.unshift(m)}if(h.length>0){let v=CN.resolveEnd(h,p,r.options.strict,n);v.comment&&(c.comment?c.comment+=`
|
|
74
|
+
`+v.comment:c.comment=v.comment),c.range=[i.offset,p,v.offset]}else c.range=[i.offset,p,p];return c}_p.resolveFlowCollection=_N});var Tp=y(Ip=>{"use strict";var AN=_(),IN=q(),TN=Ot(),$N=Ht(),jN=Sp(),ON=xp(),HN=Ap();function Xc(e,t,r,i,n,a){let o=r.type==="block-map"?jN.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?ON.resolveBlockSeq(e,t,r,i,a):HN.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function DN(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:m}=i,h=f&&a?f.offset>a.offset?f:a:f??a;h&&(!m||m.offset<h.offset)&&n(h,"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===TN.YAMLMap.tagName&&s==="map"||o===$N.YAMLSeq.tagName&&s==="seq")return Xc(e,t,r,n,o);let l=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!l){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Xc(e,t,r,n,o)}let c=Xc(e,t,r,n,o,l),u=l.resolve?.(c,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??c,d=AN.isNode(u)?u:new IN.Scalar(u);return d.range=c.range,d.tag=o,l?.format&&(d.format=l.format),d}Ip.composeCollection=DN});var Zc=y($p=>{"use strict";var Qc=q();function LN(e,t,r){let i=t.offset,n=BN(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Qc.Scalar.BLOCK_FOLDED:Qc.Scalar.BLOCK_LITERAL,o=t.source?MN(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let v=o[p][1];if(v===""||v==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
|
|
75
|
+
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:p,type:a,comment:n.comment,range:[i,v,v]}}let l=t.indent+n.indent,c=t.offset+n.length,u=0;for(let p=0;p<s;++p){let[v,g]=o[p];if(g===""||g==="\r")n.indent===0&&v.length>l&&(l=v.length);else{v.length<l&&r(c+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(l=v.length),u=p,l===0&&!e.atRoot&&r(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=v.length+g.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>l&&(s=p+1);let d="",f="",m=!1;for(let p=0;p<u;++p)d+=o[p][0].slice(l)+`
|
|
76
|
+
`;for(let p=u;p<s;++p){let[v,g]=o[p];c+=v.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&v.length<l){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(c-g.length-(w?2:1),"BAD_INDENT",k),v=""}a===Qc.Scalar.BLOCK_LITERAL?(d+=f+v.slice(l)+g,f=`
|
|
77
77
|
`):v.length>l||g[0]===" "?(f===" "?f=`
|
|
78
|
-
`:!
|
|
78
|
+
`:!m&&f===`
|
|
79
79
|
`&&(f=`
|
|
80
80
|
|
|
81
81
|
`),d+=f+v.slice(l)+g,f=`
|
|
82
|
-
`,
|
|
82
|
+
`,m=!0):g===""?f===`
|
|
83
83
|
`?d+=`
|
|
84
84
|
`:f=`
|
|
85
|
-
`:(d+=f+g,f=" ",
|
|
85
|
+
`:(d+=f+g,f=" ",m=!1)}switch(n.chomp){case"-":break;case"+":for(let p=s;p<o.length;++p)d+=`
|
|
86
86
|
`+o[p][0].slice(l);d[d.length-1]!==`
|
|
87
87
|
`&&(d+=`
|
|
88
88
|
`);break;default:d+=`
|
|
89
|
-
`}let
|
|
89
|
+
`}let h=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,h,h]}}function BN({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",l=-1;for(let f=1;f<n.length;++f){let m=n[f];if(!s&&(m==="-"||m==="+"))s=m;else{let h=Number(m);!o&&h?o=h:l===-1&&(l=e+f)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let m=t[f];switch(m.type){case"space":c=!0;case"newline":d+=m.source.length;break;case"comment":r&&!c&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=m.source.length,u=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),d+=m.source.length;break;default:{let h=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",h);let p=m.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function MN(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}$p.resolveBlockScalar=LN});var tl=y(Op=>{"use strict";var el=q(),FN=Lr();function qN(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,l,c=(f,m,h)=>r(i+f,m,h);switch(n){case"scalar":s=el.Scalar.PLAIN,l=VN(a,c);break;case"single-quoted-scalar":s=el.Scalar.QUOTE_SINGLE,l=WN(a,c);break;case"double-quoted-scalar":s=el.Scalar.QUOTE_DOUBLE,l=zN(a,c);break;default:return r(e,"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=FN.resolveEnd(o,u,t,r);return{value:l,type:s,comment:d.comment,range:[i,u,d.offset]}}function VN(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),jp(e)}function WN(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),jp(e.slice(1,-1)).replace(/''/g,"'")}function jp(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
90
90
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
91
91
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
|
|
92
92
|
`?n+=a:a=`
|
|
93
|
-
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function
|
|
93
|
+
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function zN(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
|
|
94
94
|
`))if(n===`
|
|
95
|
-
`){let{fold:a,offset:o}=
|
|
95
|
+
`){let{fold:a,offset:o}=GN(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=JN[a];if(o)r+=o;else if(a===`
|
|
96
96
|
`)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
|
|
97
|
-
`)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=
|
|
97
|
+
`)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=UN(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
|
|
98
98
|
`&&!(o==="\r"&&e[i+2]===`
|
|
99
|
-
`)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function
|
|
99
|
+
`)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function GN(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
|
|
100
100
|
`||i==="\r")&&!(i==="\r"&&e[t+2]!==`
|
|
101
101
|
`);)i===`
|
|
102
102
|
`&&(r+=`
|
|
103
|
-
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var
|
|
104
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
103
|
+
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var JN={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
104
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function UN(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Op.resolveFlowScalar=qN});var Lp=y(Dp=>{"use strict";var Qt=_(),Hp=q(),KN=Zc(),YN=tl();function XN(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?KN.resolveBlockScalar(e,t,i):YN.resolveFlowScalar(t,e.options.strict,i),l=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,c;e.options.stringKeys&&e.atKey?c=e.schema[Qt.SCALAR]:l?c=QN(e.schema,n,l,r,i):t.type==="scalar"?c=ZN(e,n,t,i):c=e.schema[Qt.SCALAR];let u;try{let d=c.resolve(n,f=>i(r??t,"TAG_RESOLVE_FAILED",f),e.options);u=Qt.isScalar(d)?d:new Hp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",f),u=new Hp.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),l&&(u.tag=l),c.format&&(u.format=c.format),o&&(u.comment=o),u}function QN(e,t,r,i,n){if(r==="!")return e[Qt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Qt.SCALAR])}function ZN({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Qt.SCALAR];if(r.compat){let s=r.compat.find(l=>l.default&&l.test?.test(i))??r[Qt.SCALAR];if(o.tag!==s.tag){let l=t.tagString(o.tag),c=t.tagString(s.tag),u=`Value may be parsed as either ${l} or ${c}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Dp.composeScalar=XN});var Mp=y(Bp=>{"use strict";function ek(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Bp.emptyScalarPosition=ek});var Vp=y(il=>{"use strict";var tk=Ri(),rk=_(),ik=Tp(),Fp=Lp(),nk=Lr(),ak=Mp(),ok={composeNode:qp,composeEmptyNode:rl};function qp(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:l}=r,c,u=!0;switch(t.type){case"alias":c=sk(e,t,i),(s||l)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Fp.composeScalar(e,t,l,i),s&&(c.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=ik.composeCollection(ok,e,t,r,i),s&&(c.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=rl(e,t.offset,void 0,null,r,i)),s&&c.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!rk.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&i(l??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(c.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?c.comment=o:c.commentBefore=o),e.options.keepSourceTokens&&u&&(c.srcToken=t),c}function rl(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:l},c){let u={type:"scalar",offset:ak.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Fp.composeScalar(e,u,s,c);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=l),d}function sk({options:e},{offset:t,source:r,end:i},n){let a=new tk.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=nk.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}il.composeEmptyNode=rl;il.composeNode=qp});var Gp=y(zp=>{"use strict";var ck=Wi(),Wp=Vp(),lk=Lr(),uk=Ui();function dk(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),l=new ck.Document(void 0,s),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=uk.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(l.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")),l.contents=n?Wp.composeNode(c,n,u,o):Wp.composeEmptyNode(c,u.end,i,null,u,o);let d=l.contents.range[2],f=lk.resolveEnd(a,d,!1,o);return f.comment&&(l.comment=f.comment),l.range=[r,d,f.offset],l}zp.composeDoc=dk});var al=y(Kp=>{"use strict";var fk=Ln("process"),pk=Ws(),hk=Wi(),Ki=Ji(),Jp=_(),mk=Gp(),vk=Lr();function Yi(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function Up(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
|
|
105
105
|
|
|
106
106
|
`:`
|
|
107
|
-
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var
|
|
108
|
-
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(
|
|
107
|
+
`)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var nl=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Yi(r);a?this.warnings.push(new Ki.YAMLWarning(o,i,n)):this.errors.push(new Ki.YAMLParseError(o,i,n))},this.directives=new pk.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Up(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
108
|
+
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Jp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Jp.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
|
|
109
109
|
${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
|
|
110
|
-
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
111
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
110
|
+
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Up(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(fk.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Yi(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=mk.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Ki.YAMLParseError(Yi(t),"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 Ki.YAMLParseError(Yi(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=vk.resolveEnd(t.end,t.offset+t.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}
|
|
111
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Ki.YAMLParseError(Yi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new hk.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}}};Kp.Composer=nl});var Qp=y(qa=>{"use strict";var gk=Zc(),wk=tl(),yk=Ji(),Yp=$i();function bk(e,t=!0,r){if(e){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 yk.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return wk.resolveFlowScalar(e,t,i);case"block-scalar":return gk.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function Nk(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Yp.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:i,source:`
|
|
112
112
|
`}];switch(s[0]){case"|":case">":{let c=s.indexOf(`
|
|
113
113
|
`),u=s.substring(0,c),d=s.substring(c+1)+`
|
|
114
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return
|
|
115
|
-
`}),{type:"block-scalar",offset:a,indent:i,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:l};default:return{type:"scalar",offset:a,indent:i,source:s,end:l}}}function
|
|
114
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Xp(f,l)||f.push({type:"newline",offset:-1,indent:i,source:`
|
|
115
|
+
`}),{type:"block-scalar",offset:a,indent:i,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:l};default:return{type:"scalar",offset:a,indent:i,source:s,end:l}}}function kk(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=e.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=Yp.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":Sk(e,l);break;case'"':ol(e,l,"double-quoted-scalar");break;case"'":ol(e,l,"single-quoted-scalar");break;default:ol(e,l,"scalar")}}function Sk(e,t){let r=t.indexOf(`
|
|
116
116
|
`),i=t.substring(0,r),n=t.substring(r+1)+`
|
|
117
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];
|
|
118
|
-
`});for(let l of Object.keys(e))l!=="type"&&l!=="offset"&&delete e[l];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function
|
|
119
|
-
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}
|
|
117
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Xp(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
118
|
+
`});for(let l of Object.keys(e))l!=="type"&&l!=="offset"&&delete e[l];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Xp(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function ol(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
119
|
+
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}qa.createScalarToken=Nk;qa.resolveAsScalar=bk;qa.setScalarValue=kk});var eh=y(Zp=>{"use strict";var Ek=e=>"type"in e?Wa(e):Va(e);function Wa(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Wa(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Va(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Va(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Va(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Va({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Wa(t)),r)for(let a of r)n+=a.source;return i&&(n+=Wa(i)),n}Zp.stringify=Ek});var nh=y(ih=>{"use strict";var sl=Symbol("break visit"),xk=Symbol("skip children"),th=Symbol("remove item");function Zt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),rh(Object.freeze([]),e,t)}Zt.BREAK=sl;Zt.SKIP=xk;Zt.REMOVE=th;Zt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Zt.parentCollection=(e,t)=>{let r=Zt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function rh(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=rh(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===sl)return sl;s===th&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}ih.visit=Zt});var za=y(ce=>{"use strict";var cl=Qp(),Ck=eh(),Pk=nh(),ll="\uFEFF",ul="",dl="",fl="",Rk=e=>!!e&&"items"in e,_k=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Ak(e){switch(e){case ll:return"<BOM>";case ul:return"<DOC>";case dl:return"<FLOW_END>";case fl:return"<SCALAR>";default:return JSON.stringify(e)}}function Ik(e){switch(e){case ll:return"byte-order-mark";case ul:return"doc-mode";case dl:return"flow-error-end";case fl:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
120
120
|
`:case`\r
|
|
121
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
122
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
123
|
-
\r `),
|
|
121
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ce.createScalarToken=cl.createScalarToken;ce.resolveAsScalar=cl.resolveAsScalar;ce.setScalarValue=cl.setScalarValue;ce.stringify=Ck.stringify;ce.visit=Pk.visit;ce.BOM=ll;ce.DOCUMENT=ul;ce.FLOW_END=dl;ce.SCALAR=fl;ce.isCollection=Rk;ce.isScalar=_k;ce.prettyToken=Ak;ce.tokenType=Ik});var ml=y(oh=>{"use strict";var Xi=za();function je(e){switch(e){case void 0:case" ":case`
|
|
122
|
+
`:case"\r":case" ":return!0;default:return!1}}var ah=new Set("0123456789ABCDEFabcdef"),Tk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ga=new Set(",[]{}"),$k=new Set(` ,[]{}
|
|
123
|
+
\r `),pl=e=>!e||$k.has(e),hl=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
124
124
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
125
125
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
|
|
126
126
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
127
|
-
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&
|
|
128
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
127
|
+
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&je(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
128
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Xi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Xi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&je(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&&!je(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&je(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 t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(pl),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+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("..."))&&je(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Xi.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(pl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||je(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
129
129
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
130
|
-
`,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 t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>
|
|
130
|
+
`,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 t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>je(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
131
131
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
132
132
|
`)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(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
133
133
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
134
134
|
`;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
135
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield
|
|
135
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Xi.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=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(je(a)||t&&Ga.has(a))break;r=i}else if(je(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
136
136
|
`?(i+=1,n=`
|
|
137
|
-
`,a=this.buffer[i+1]):r=i),a==="#"||t&&
|
|
138
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&
|
|
137
|
+
`,a=this.buffer[i+1]):r=i),a==="#"||t&&Ga.has(a))break;if(n===`
|
|
138
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Ga.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Xi.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(pl),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(je(i)||r&&Ga.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!je(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(Tk.has(r))r=this.buffer[++t];else if(r==="%"&&ah.has(this.buffer[t+1])&&ah.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
139
139
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
140
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};
|
|
140
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};oh.Lexer=hl});var gl=y(sh=>{"use strict";var vl=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};sh.LineCounter=vl});var yl=y(fh=>{"use strict";var jk=Ln("process"),ch=za(),Ok=ml();function Dt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function lh(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function dh(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ja(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Br(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Ua(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function uh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Dt(t.start,"explicit-key-ind")&&!Dt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,dh(t.value)?t.value.end?Ua(t.value.end,t.sep):t.value.end=t.sep:Ua(t.start,t.sep),delete t.sep)}var wl=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Ok.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,jk.env.LOG_TOKENS&&console.log("|",ch.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=ch.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let 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"&&uh(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&&lh(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 t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{lh(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Ja(this.peek(2)),i=Br(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
-
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let 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):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
142
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let 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):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Ua(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.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 l=r.sep[s];switch(l.type){case"newline":o.push(s);break;case"space":break;case"comment":l.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Dt(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(dh(r.key)&&!Dt(r.sep,"newline")){let o=Br(r.start),s=r.key,l=r.sep;l.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:l}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Dt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Br(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?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Dt(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?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Dt(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&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let 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):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Ua(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Dt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.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(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.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":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);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===t.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=Ja(i),a=Br(n);uh(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
143
143
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
144
|
-
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=
|
|
144
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Ja(t),i=Br(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=Ja(t),i=Br(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};fh.Parser=wl});var gh=y(Zi=>{"use strict";var ph=al(),Hk=Wi(),Qi=Ji(),Dk=ic(),Lk=_(),Bk=gl(),hh=yl();function mh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Bk.LineCounter||null,prettyErrors:t}}function Mk(e,t={}){let{lineCounter:r,prettyErrors:i}=mh(t),n=new hh.Parser(r?.addNewLine),a=new ph.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Qi.prettifyError(e,r)),s.warnings.forEach(Qi.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function vh(e,t={}){let{lineCounter:r,prettyErrors:i}=mh(t),n=new hh.Parser(r?.addNewLine),a=new ph.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Qi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Qi.prettifyError(e,r)),o.warnings.forEach(Qi.prettifyError(e,r))),o}function Fk(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=vh(e,r);if(!n)return null;if(n.warnings.forEach(a=>Dk.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 qk(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),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(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return Lk.isDocument(e)&&!i?e.toString(r):new Hk.Document(e,i,r).toString(r)}Zi.parse=Fk;Zi.parseAllDocuments=Mk;Zi.parseDocument=vh;Zi.stringify=qk});var ut=y(I=>{"use strict";var Vk=al(),Wk=Wi(),zk=Bc(),bl=Ji(),Gk=Ri(),Lt=_(),Jk=$t(),Uk=q(),Kk=Ot(),Yk=Ht(),Xk=za(),Qk=ml(),Zk=gl(),eS=yl(),Ka=gh(),wh=Ei();I.Composer=Vk.Composer;I.Document=Wk.Document;I.Schema=zk.Schema;I.YAMLError=bl.YAMLError;I.YAMLParseError=bl.YAMLParseError;I.YAMLWarning=bl.YAMLWarning;I.Alias=Gk.Alias;I.isAlias=Lt.isAlias;I.isCollection=Lt.isCollection;I.isDocument=Lt.isDocument;I.isMap=Lt.isMap;I.isNode=Lt.isNode;I.isPair=Lt.isPair;I.isScalar=Lt.isScalar;I.isSeq=Lt.isSeq;I.Pair=Jk.Pair;I.Scalar=Uk.Scalar;I.YAMLMap=Kk.YAMLMap;I.YAMLSeq=Yk.YAMLSeq;I.CST=Xk;I.Lexer=Qk.Lexer;I.LineCounter=Zk.LineCounter;I.Parser=eS.Parser;I.parse=Ka.parse;I.parseAllDocuments=Ka.parseAllDocuments;I.parseDocument=Ka.parseDocument;I.stringify=Ka.stringify;I.visit=wh.visit;I.visitAsync=wh.visitAsync});function iS(e,t){return Nl[e][t]}function Ya(e){return bh.get(e.trim().toLocaleLowerCase("en-US"))??null}function Xa(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${iS(e,i)}
|
|
145
145
|
`).join(`
|
|
146
|
-
`)}var $c,gb,wb,mp,hp,Vt=S(()=>{"use strict";$c={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:"验证预期"}},gb={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:"结论"}},wb={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:"结论"}},mp=new Map,hp=new Map;for(let e of Object.keys($c)){for(let[t,r]of Object.entries($c[e]))mp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(gb[e]))hp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(wb[e]))hp.set(r.toLocaleLowerCase("en-US"),t)}});import Rt from"path";function Eb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Rt.posix.isAbsolute(r)||Rt.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=Eb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Sp(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 Na(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||Rt.posix.isAbsolute(i)||Rt.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 et(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ep(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 Dc(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>wa)throw new Error(`${t} exceeds ${wa} 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>ya)throw new Error(`${t} contains more than ${ya} wildcard tokens`);return e}function Np(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=>Dc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Ri(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 bp(e,t,r){let i=Ri(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 xb(e){if(e===void 0)return{...oe,include:[...oe.include],exclude:[...oe.exclude]};let t=et(e,"native.snapshot");return{include:Np(t.include,"native.snapshot.include",oe.include),exclude:Np(t.exclude,"native.snapshot.exclude",oe.exclude),max_files:Ri(t.max_files,oe.max_files,"native.snapshot.max_files"),max_total_bytes:Ri(t.max_total_bytes,oe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ri(t.max_duration_ms,oe.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Ri(t.max_selection_records,oe.max_selection_records,"native.snapshot.max_selection_records")}}function Cb(e){if(e===void 0)return;let t=et(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=et(t.cleanup,"native.pending_root_move.cleanup"),l=s.kind,c=s.state,u=s.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(c!=="prepared"&&c!=="quarantined"&&c!=="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:l,state:c,manifestHash:u}}return{id:r,fromArtifactRoot:qt(i),toArtifactRoot:qt(n),stage:a,...o?{cleanup:o}:{}}}function Pb(e){if(e===void 0)return;let t=et(e,"native.finish");if(t.pull_request===void 0)return{};let r=et(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(Rt.posix.isAbsolute(i[0])||Rt.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??Nb;if(!Number.isSafeInteger(n)||n<1||n>yp)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${yp}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function Rb(e,t={}){let r=et(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??Hc;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 l=Cb(r.pending_root_move),c=Pb(r.finish);return{artifact_root:qt(i),language:Ep(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:xb(r.snapshot),...c?{finish:c}:{},...l?{pending_root_move:l}:{}}}function _b(e){let t=et(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:Sp(t.artifact_layout),language:Ep(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function Ab(e){let r=et(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)=>Na(i,`hook.allow_paths[${n}]`)))]}}function Ib(e){if(e===void 0)return{...ga};let t=et(e,"memory"),r=t.learning??ga.learning,i=t.retrieval??ga.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 Lc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Tb(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")||Rt.posix.isAbsolute(r)||Rt.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>vp)throw new Error(`${t} exceeds ${vp} 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>gp)throw new Error(`${t} contains more than ${gp} wildcard tokens`);return r}function jb(e){let t=Lc(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)=>Tb(n,`knowledge.local.include[${a}]`)))],max_file_mb:bp(t.max_file_mb,wp.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:bp(t.max_total_mb,wp.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 $b(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 Ob(e){let t=Lc(e,"knowledge.remote"),r=$b(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 Hb(e){if(e===void 0)return{...kp};let t=Lc(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:jb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Ob(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 Db(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Lb(e,t,r,i,n,a,o,s){let l=e.schema!==void 0;if(!(l||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!l)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 Ai(e,t={}){let r=(0,Oc.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=Db(n.ambient_resume),o=n.hook===void 0?void 0:Ab(n.hook),s=Ib(n.memory),l=Hb(n.knowledge),c=n.native===void 0?void 0:Rb(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:_b(n.classic),d=Lb(n,o,s,l,c,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:l,...o?{hook:o}:{},...c?{native:c}:{},...u?{classic:u}:{}}}function ba(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ga},knowledge:{...kp},native:{artifact_root:qt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Hc,snapshot:{...oe,include:[...oe.include],exclude:[...oe.exclude]}}}}var Oc,_i,wa,ya,vp,gp,Hc,ga,wp,kp,Nb,yp,bb,kb,Sb,oe,_t=S(()=>{"use strict";Oc=mt(Ze(),1),_i=Number.MAX_SAFE_INTEGER,wa=1024,ya=64,vp=1024,gp=64,Hc=5,ga={learning:!0,retrieval:!0},wp={include:[],max_file_mb:1,max_total_mb:32},kp={provider:"local"},Nb=12e4,yp=6e5,bb=[".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/**"],kb=["**/.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"],Sb=[...bb,...kb].sort((e,t)=>e.localeCompare(t,"en")),oe={include:["**/*"],exclude:[...Sb],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as ka,promises as Wt}from"fs";function Bc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function xp(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ii(e){return{dev:e.dev,ino:e.ino,birthtime:Bc(e)}}function Sa(e,t){let r=Ii(e),i=Ii(t);return Se(r,i)?j(r,i):j(r,i)&&Bc(e)===Bc(t)&&xp(e)===xp(t)&&e.size===t.size}async function br(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 Wt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Re("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Re("too-large",`${i} exceeds ${t} bytes`);let o=await Wt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ii(a)});let s=process.platform==="win32"?ka.O_RDONLY:ka.O_RDONLY|ka.O_NOFOLLOW|ka.O_NONBLOCK,l;try{l=await Wt.open(e,s)}catch(c){throw c.code==="ELOOP"?new Re("not-regular-file",`${i} must be a regular file`,{cause:c}):c}try{let[c,u,d]=await Promise.all([l.stat({bigint:n}),Wt.lstat(e,{bigint:n}),Wt.realpath(e)]);if(!c.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Sa(a,c)||!Sa(a,u))throw new Re("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Ii(c)}),await r.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-h,{bytesRead:N}=await l.read(m,0,Math.min(m.length,w),null);if(N===0)break;if(h+=N,h>t)throw new Re("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([l.stat({bigint:n}),Wt.lstat(e,{bigint:n}),Wt.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Sa(a,p)||!Sa(a,v))throw new Re("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Ii(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:g}}finally{await l.close()}}var Re,Ti=S(()=>{"use strict";Kr();Re=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Ea}from"fs";import At from"path";function Bb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Mc(e,t){let r=At.relative(e,t);return r===""||!At.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${At.sep}`)}async function Cp(e,t){let r=At.resolve(e),i=await Ea.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ea.realpath(r)}async function Pp(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=At.join(n,r[a]);let o;try{o=await Ea.lstat(n)}catch(u){if(Bb(u))return{exists:!1,kind:"missing"};throw u}let s=At.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let l=a===r.length-1;if(!l&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(l&&(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 c=await Ea.realpath(n);if(!Mc(t,c))throw new Error(`${i.label} resolves outside the project root`);if(l)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function kr(e,t,r){let i=Na(t,r.label),n=At.resolve(e),a=await Cp(n,r.label),o=i.split("/"),s=At.resolve(n,...o);if(!Mc(n,s))throw new Error(`${r.label} must stay inside the project root`);let l=await Pp(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:l.exists,kind:l.kind}}async function tt(e,t,r,i){let n=await kr(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 Cp(n.projectRoot,i.label);return br(n.target,r,{...i,verify:async(o,s)=>{if(!Mc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Pp(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var It=S(()=>{"use strict";Ti();_t()});import{createHash as Mb}from"crypto";function Fb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function xa(e,t={}){return(await Ca(e,t)).document}async function Vb(e){try{return(await tt(e,ji,_i,{label:ji})).bytes}catch(t){if(Fb(t))return null;throw t}}function qb(e){return e?{exists:!0,sha256:Mb("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Ca(e,t={}){let r=await Vb(e);return{document:r?Ai(r.toString("utf8"),t):null,identity:qb(r)}}async function Fc(e){return(await xa(e))?.config??null}var ji,Sr=S(()=>{"use strict";_t();It();ji=".comet/config.yaml"});var Er=S(()=>{"use strict";Xo();Kr()});var D_,Vc=S(()=>{"use strict";Er();Sr();It();D_=16*1024});var zc=S(()=>{"use strict";Er();_t();Sr();It();Vc()});import{existsSync as _p,promises as zt}from"fs";import _ from"path";import Ub from"os";async function Gc(e){try{return await zt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Yb(e){try{let t=await zt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Cr(e,t){let r=_.relative(e,t);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function xr(e){let t=[],r=e;for(;!await Gc(r);){let n=_.dirname(r);if(n===r)break;t.push(_.basename(r)),r=n}let i=await zt.realpath(r);return _.resolve(i,...t.reverse())}async function Jc(e){try{return(await zt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ra(e){let t=_.resolve(e);try{(await zt.stat(t)).isDirectory()||(t=_.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=_.resolve(Ub.homedir());for(;;){if(!(t===i&&r!==i)){let o=_.join(t,...Pa.split("/")),s=t===r||await Yb(o);if(await Gc(o)&&s)return t}if(await Gc(_.join(t,".git")))return t;let a=_.dirname(t);if(a===t)return r;t=a}}function _a(e){return qt(e)}async function Xb(e,t){let r=_a(t),i=_.resolve(e,...r.split("/")),n=await zt.realpath(e),a=await xr(i);if(!Cr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Pr(e,t){let r=_a(t),i=await Xb(e,r),n=_.join(i,"comet");if(await Jc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([xr(i),xr(n)]);if(!Cr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=_.resolve(e),l=_.join(s,".comet","runtime","native");if(await Jc(l))throw new Error("The Native Runtime root must not be a symbolic link");let[c,u]=await Promise.all([zt.realpath(s),xr(l)]);if(!Cr(c,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(e,...Pa.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:_.join(n,"specs"),changesDir:_.join(n,"changes"),archiveDir:_.join(n,"archive"),runtimeDir:l,changesRuntimeDir:_.join(l,"changes"),locksDir:_.join(l,"locks"),transactionsDir:_.join(l,"transactions")}}function Ap(e){if(!Kb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function _e(e,t){Ap(t);let r=_.join(e.changesRuntimeDir,t);if(!X(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Uc(e,t){Ap(t);let r=_.join(e.changesDir,t,"runtime");if(!X(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ae(e,t){let r=_e(e,t);if(_p(r))return r;let i=Uc(e,t);return _p(i)?i:r}function Kc(e,t){if(!t.startsWith("runtime/")||_.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=_.resolve(e,...t.slice(8).split("/"));if(!X(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function ce(e,t){let r=_.resolve(t);if(X(e.runtimeDir,r))return e.runtimeDir;if(X(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function X(e,t){return Cr(_.resolve(e),_.resolve(t))}async function I(e,t){let r=_.resolve(e),i=_.resolve(t);if(!Cr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Jc(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([xr(r),xr(i)]);if(!Cr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Pa,Kb,H=S(()=>{"use strict";_t();Pa=".comet/config.yaml",Kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function Zb(e="docs",t="en"){return ba(e,t)}async function Ie(e){let t=(await xa(e))?.config??null;return t?.native?t:null}async function Aa(e){let t=await Ie(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Ip(e){let t=await Ra(e.startPath),r=await Ie(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Pa} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?_a(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??Zb(i??"docs"),a=await Pr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var he=S(()=>{"use strict";_t();Sr();zc();L();H()});import{existsSync as ek}from"node:fs";import Oi from"node:path";function Tp(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function rk(e){let t=(Tp(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function ik(e,t,r){let n=Oi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Tp(t,"PATH")??"").split(Oi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Oi.win32.extname(e)?[e]:rk(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(l=>s?Oi.join(s,l):Oi.resolve(r,l)))}function Yc(e,t,r){return ik(e,t,r).find(i=>ek(i))??e}function Xc(e){if(e.some(t=>tk.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var tk,oA,Ia=S(()=>{"use strict";tk=/[&|<>()^%"!\r\n]/u,oA=["$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{execFileSync as nk}from"node:child_process";import jp from"node:path";function sk(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function Ta(e,t,r={}){let i=r.timeoutMs??ak,n=r.maxBufferBytes??ok;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=jp.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Yc(e,o,a):e,l=jp.win32.extname(s).toLowerCase(),c=l===".bat"||l===".cmd";process.platform==="win32"&&c&&Xc(t);try{return nk(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&c})}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Qc(e,t,d,{cause:u,timedOut:sk(u)})}}var ak,ok,Qc,$p=S(()=>{"use strict";Ia();ak=6e4,ok=8*1024*1024,Qc=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}});import{promises as Op}from"node:fs";import Hp from"node:path";function uk(e){let t=el.get(e);if(!t)return;let r=t.value===null?lk:ck;if(Date.now()-t.at>r){el.delete(e);return}return t.value}async function Hi(e){if(e===process.pid&&Zc!==null)return Zc;let t=uk(e);if(t!==void 0)return t;let r=await dk(e);return e===process.pid&&r!==null&&(Zc=r),e!==process.pid&&el.set(e,{value:r,at:Date.now()}),r}async function dk(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Op.readFile(`/proc/${e}/stat`,"utf8"),Op.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await pk(e);if(process.platform==="darwin"){let t=Ta("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return t?`darwin:${t}`:null}}catch{}return null}function fk(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function pk(e){try{let n=Ta(Hp.win32.join(process.env.SystemRoot??"C:\\Windows","System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:5e3,maxBufferBytes:4096}),a=/^CreationDate=(\S+)/mu.exec(n);if(a)return`win32-wmic:${a[1]}`}catch{}let t=process.env.SystemRoot??"C:\\Windows",r=Hp.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=Ta(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return fk(i)}function ja(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function tl(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Hi(e);return r===t?"alive":r===null||ja(r)!==ja(t)&&Dp.has(ja(r))&&Dp.has(ja(t))?"unknown":"dead"}var Zc,ck,lk,el,Dp,$a=S(()=>{"use strict";$p();Zc=null,ck=6e4,lk=1e4,el=new Map;Dp=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as hk}from"async_hooks";import{randomUUID as Mp}from"crypto";import{promises as me}from"fs";import Fp from"os";import F from"path";function gk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function wk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Vp(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Ha(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Se(r,i)?j(r,i):j(r,i)&&e.size===t.size}function Da(e,t){return Ha(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function yk(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Da(e.identity,t.identity)}async function Te(e){let t,r;try{let i=await br(e,Lp,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Re?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Lp} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:wk(JSON.parse(t.toString("utf8")),e),identity:Vp(r)}}async function Nk(e){return(await Te(e))?.owner??null}async function il(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Fp.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await tl(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function bk(e,t){try{await me.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await me.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function La(e,t){let r=await Te(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Da(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await me.mkdir(t,{recursive:!0});let i=F.join(t,`${F.basename(e.file)}.${e.owner.id}.${Mp()}.removed`);try{await me.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Te(i);if(!n||n.owner.id!==e.owner.id||!Ha(n.identity,e.identity))throw await bk(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await me.rm(i,{force:!0}),"removed"}async function qp(e){let t=await Hi(process.pid);return{id:Mp(),pid:process.pid,hostname:Fp.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Wp(e,t){let r;try{r=await me.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await Nk(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
147
|
-
|
|
146
|
+
`)}var Nl,tS,rS,bh,yh,er=S(()=>{"use strict";Nl={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:"验证预期"}},tS={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:"结论"}},rS={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:"结论"}},bh=new Map,yh=new Map;for(let e of Object.keys(Nl)){for(let[t,r]of Object.entries(Nl[e]))bh.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(tS[e]))yh.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(rS[e]))yh.set(r.toLocaleLowerCase("en-US"),t)}});import Bt from"path";function cS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Bt.posix.isAbsolute(r)||Bt.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 tr(e){let t=cS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Rh(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 to(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||Bt.posix.isAbsolute(i)||Bt.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 dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _h(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 El(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>Za)throw new Error(`${t} exceeds ${Za} 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>eo)throw new Error(`${t} contains more than ${eo} wildcard tokens`);return e}function xh(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=>El(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function en(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 Ch(e,t,r){let i=en(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 lS(e){if(e===void 0)return{...le,include:[...le.include],exclude:[...le.exclude]};let t=dt(e,"native.snapshot");return{include:xh(t.include,"native.snapshot.include",le.include),exclude:xh(t.exclude,"native.snapshot.exclude",le.exclude),max_files:en(t.max_files,le.max_files,"native.snapshot.max_files"),max_total_bytes:en(t.max_total_bytes,le.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:en(t.max_duration_ms,le.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:en(t.max_selection_records,le.max_selection_records,"native.snapshot.max_selection_records")}}function uS(e){if(e===void 0)return;let t=dt(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=dt(t.cleanup,"native.pending_root_move.cleanup"),l=s.kind,c=s.state,u=s.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(c!=="prepared"&&c!=="quarantined"&&c!=="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:l,state:c,manifestHash:u}}return{id:r,fromArtifactRoot:tr(i),toArtifactRoot:tr(n),stage:a,...o?{cleanup:o}:{}}}function dS(e){if(e===void 0)return;let t=dt(e,"native.finish");if(t.pull_request===void 0)return{};let r=dt(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(Bt.posix.isAbsolute(i[0])||Bt.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??nS;if(!Number.isSafeInteger(n)||n<1||n>Eh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Eh}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function fS(e,t={}){let r=dt(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??Sl;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 l=uS(r.pending_root_move),c=dS(r.finish);return{artifact_root:tr(i),language:_h(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:lS(r.snapshot),...c?{finish:c}:{},...l?{pending_root_move:l}:{}}}function pS(e){let t=dt(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:Rh(t.artifact_layout),language:_h(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function hS(e){let r=dt(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)=>to(i,`hook.allow_paths[${n}]`)))]}}function mS(e){if(e===void 0)return{...Qa};let t=dt(e,"memory"),r=t.learning??Qa.learning,i=t.retrieval??Qa.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 xl(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function vS(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")||Bt.posix.isAbsolute(r)||Bt.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>Nh)throw new Error(`${t} exceeds ${Nh} 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>kh)throw new Error(`${t} contains more than ${kh} wildcard tokens`);return r}function gS(e){let t=xl(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)=>vS(n,`knowledge.local.include[${a}]`)))],max_file_mb:Ch(t.max_file_mb,Sh.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Ch(t.max_total_mb,Sh.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 wS(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 yS(e){let t=xl(e,"knowledge.remote"),r=wS(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 bS(e){if(e===void 0)return{...Ph};let t=xl(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:gS(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:yS(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 NS(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function kS(e,t,r,i,n,a,o,s){let l=e.schema!==void 0;if(!(l||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!l)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 rn(e,t={}){let r=(0,kl.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=NS(n.ambient_resume),o=n.hook===void 0?void 0:hS(n.hook),s=mS(n.memory),l=bS(n.knowledge),c=n.native===void 0?void 0:fS(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:pS(n.classic),d=kS(n,o,s,l,c,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:l,...o?{hook:o}:{},...c?{native:c}:{},...u?{classic:u}:{}}}function ro(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Qa},knowledge:{...Ph},native:{artifact_root:tr(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Sl,snapshot:{...le,include:[...le.include],exclude:[...le.exclude]}}}}var kl,tn,Za,eo,Nh,kh,Sl,Qa,Sh,Ph,nS,Eh,aS,oS,sS,le,Mt=S(()=>{"use strict";kl=Ct(ut(),1),tn=Number.MAX_SAFE_INTEGER,Za=1024,eo=64,Nh=1024,kh=64,Sl=5,Qa={learning:!0,retrieval:!0},Sh={include:[],max_file_mb:1,max_total_mb:32},Ph={provider:"local"},nS=12e4,Eh=6e5,aS=[".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/**"],oS=["**/.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"],sS=[...aS,...oS].sort((e,t)=>e.localeCompare(t,"en")),le={include:["**/*"],exclude:[...sS],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as io,promises as rr}from"fs";function Cl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ah(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function nn(e){return{dev:e.dev,ino:e.ino,birthtime:Cl(e)}}function no(e,t){let r=nn(e),i=nn(t);return Ae(r,i)?j(r,i):j(r,i)&&Cl(e)===Cl(t)&&Ah(e)===Ah(t)&&e.size===t.size}async function Mr(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 rr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Oe("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Oe("too-large",`${i} exceeds ${t} bytes`);let o=await rr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:nn(a)});let s=process.platform==="win32"?io.O_RDONLY:io.O_RDONLY|io.O_NOFOLLOW|io.O_NONBLOCK,l;try{l=await rr.open(e,s)}catch(c){throw c.code==="ELOOP"?new Oe("not-regular-file",`${i} must be a regular file`,{cause:c}):c}try{let[c,u,d]=await Promise.all([l.stat({bigint:n}),rr.lstat(e,{bigint:n}),rr.realpath(e)]);if(!c.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!no(a,c)||!no(a,u))throw new Oe("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:nn(c)}),await r.hooks?.afterOpen?.();let f=[],m=0,h=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-m,{bytesRead:b}=await l.read(h,0,Math.min(h.length,w),null);if(b===0)break;if(m+=b,m>t)throw new Oe("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(h.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([l.stat({bigint:n}),rr.lstat(e,{bigint:n}),rr.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!no(a,p)||!no(a,v))throw new Oe("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:nn(p)}),{bytes:Buffer.concat(f,m),stat:p,realPath:g}}finally{await l.close()}}var Oe,an=S(()=>{"use strict";Ni();Oe=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as ao}from"fs";import Ft from"path";function SS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Pl(e,t){let r=Ft.relative(e,t);return r===""||!Ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ft.sep}`)}async function Ih(e,t){let r=Ft.resolve(e),i=await ao.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ao.realpath(r)}async function Th(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Ft.join(n,r[a]);let o;try{o=await ao.lstat(n)}catch(u){if(SS(u))return{exists:!1,kind:"missing"};throw u}let s=Ft.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let l=a===r.length-1;if(!l&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(l&&(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 c=await ao.realpath(n);if(!Pl(t,c))throw new Error(`${i.label} resolves outside the project root`);if(l)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Fr(e,t,r){let i=to(t,r.label),n=Ft.resolve(e),a=await Ih(n,r.label),o=i.split("/"),s=Ft.resolve(n,...o);if(!Pl(n,s))throw new Error(`${r.label} must stay inside the project root`);let l=await Th(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:l.exists,kind:l.kind}}async function Ke(e,t,r,i){let n=await Fr(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 Ih(n.projectRoot,i.label);return Mr(n.target,r,{...i,verify:async(o,s)=>{if(!Pl(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Th(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var ft=S(()=>{"use strict";an();Mt()});import{createHash as ES}from"crypto";function xS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function oo(e,t={}){return(await so(e,t)).document}async function CS(e){try{return(await Ke(e,on,tn,{label:on})).bytes}catch(t){if(xS(t))return null;throw t}}function PS(e){return e?{exists:!0,sha256:ES("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function so(e,t={}){let r=await CS(e);return{document:r?rn(r.toString("utf8"),t):null,identity:PS(r)}}async function Rl(e){return(await oo(e))?.config??null}var on,qr=S(()=>{"use strict";Mt();ft();on=".comet/config.yaml"});var Vr=S(()=>{"use strict";Ls();Ni()});var jT,_l=S(()=>{"use strict";Vr();qr();ft();jT=16*1024});var Tl=S(()=>{"use strict";Vr();Mt();qr();ft();_l()});import{existsSync as jh,promises as ir}from"fs";import A from"path";import TS from"os";async function $l(e){try{return await ir.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jS(e){try{let t=await ir.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function zr(e,t){let r=A.relative(e,t);return r===""||!A.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${A.sep}`)}async function Wr(e){let t=[],r=e;for(;!await $l(r);){let n=A.dirname(r);if(n===r)break;t.push(A.basename(r)),r=n}let i=await ir.realpath(r);return A.resolve(i,...t.reverse())}async function jl(e){try{return(await ir.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function lo(e){let t=A.resolve(e);try{(await ir.stat(t)).isDirectory()||(t=A.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=A.resolve(TS.homedir());for(;;){if(!(t===i&&r!==i)){let o=A.join(t,...co.split("/")),s=t===r||await jS(o);if(await $l(o)&&s)return t}if(await $l(A.join(t,".git")))return t;let a=A.dirname(t);if(a===t)return r;t=a}}function uo(e){return tr(e)}async function OS(e,t){let r=uo(t),i=A.resolve(e,...r.split("/")),n=await ir.realpath(e),a=await Wr(i);if(!zr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Gr(e,t){let r=uo(t),i=await OS(e,r),n=A.join(i,"comet");if(await jl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Wr(i),Wr(n)]);if(!zr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=A.resolve(e),l=A.join(s,".comet","runtime","native");if(await jl(l))throw new Error("The Native Runtime root must not be a symbolic link");let[c,u]=await Promise.all([ir.realpath(s),Wr(l)]);if(!zr(c,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:A.join(e,...co.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:A.join(n,"specs"),changesDir:A.join(n,"changes"),archiveDir:A.join(n,"archive"),runtimeDir:l,changesRuntimeDir:A.join(l,"changes"),locksDir:A.join(l,"locks"),transactionsDir:A.join(l,"transactions")}}function Oh(e){if(!$S.test(e))throw new Error(`Invalid Native change name: ${e}`)}function He(e,t){Oh(t);let r=A.join(e.changesRuntimeDir,t);if(!te(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Ol(e,t){Oh(t);let r=A.join(e.changesDir,t,"runtime");if(!te(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function De(e,t){let r=He(e,t);if(jh(r))return r;let i=Ol(e,t);return jh(i)?i:r}function Hl(e,t){if(!t.startsWith("runtime/")||A.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=A.resolve(e,...t.slice(8).split("/"));if(!te(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function fe(e,t){let r=A.resolve(t);if(te(e.runtimeDir,r))return e.runtimeDir;if(te(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function te(e,t){return zr(A.resolve(e),A.resolve(t))}async function T(e,t){let r=A.resolve(e),i=A.resolve(t);if(!zr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await jl(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Wr(r),Wr(i)]);if(!zr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var co,$S,L=S(()=>{"use strict";Mt();co=".comet/config.yaml",$S=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function DS(e="docs",t="en"){return ro(e,t)}async function Le(e){let t=(await oo(e))?.config??null;return t?.native?t:null}async function fo(e){let t=await Le(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Hh(e){let t=await lo(e.startPath),r=await Le(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${co} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?uo(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??DS(i??"docs"),a=await Gr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var be=S(()=>{"use strict";Mt();qr();Tl();B();L()});import{createHash as Ll,randomUUID as LS}from"node:crypto";import{promises as pe}from"node:fs";import BS from"node:os";import ue from"node:path";async function Dl(e,t){let r=await pe.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await pe.readFile(e),n=await pe.lstat(e,{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 Bh(e){try{let t=JSON.parse((await Dl(ue.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=ue.join(e,t.file),i=await Dl(r,65536);return Ll("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function qS(e,t){let r,i=LS(),n=ue.join(e,`probe-${i}.cs`),a=ue.join(e,`probe-${i}.exe`),o=ue.join(e,`probe-${i}.json`);try{if(await pe.mkdir(e,{recursive:!0,mode:448}),(await pe.lstat(e)).isSymbolicLink())return null;r=await pe.open(ue.join(e,"prepare.lock"),"wx",384);let s=await Bh(e);if(s)return s;await pe.writeFile(n,Lh,{flag:"wx",mode:384});let l;for(let u of["Framework64","Framework"]){let d=ue.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await pe.access(d),l=d;break}catch{}}if(!l)return null;await Pt(l,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let c=Ll("sha256").update(await Dl(a,65536)).digest("hex");return await pe.writeFile(o,JSON.stringify({file:ue.basename(a),hash:c}),{flag:"wx",mode:384}),await pe.rename(o,ue.join(e,"probe.json")),a}catch{return null}finally{await pe.unlink(n).catch(()=>{}),await pe.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await pe.unlink(ue.join(e,"prepare.lock")).catch(()=>{}))}}async function Dh(e,t,r){try{let i=await Pt(ue.join(t,"System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"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 Pt(ue.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function VS(e,t){let r=po.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:qS(e,t),retryAfter:1/0};return po.set(e,i),i.promise.then(n=>{po.get(e)===i&&(n?po.delete(e):i.retryAfter=performance.now()+FS)}),i.promise}async function Mh(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=ue.join(t.cacheRoot??ue.join(BS.tmpdir(),"comet-process-identity"),MS),n=async c=>{if(!c)return null;try{let d=(await Pt(c,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await Bh(i);if(a){let c=await n(a);return c||Dh(e,r,new AbortController().signal)}let o=VS(i,r),s=new AbortController,l=c=>{if(!c)throw new Error("Probe unavailable");return c};try{return await Promise.any([o.then(n).then(l),Dh(e,r,s.signal).then(l)])}catch{return null}finally{s.abort()}}var Lh,MS,FS,po,Fh=S(()=>{"use strict";Jn();Lh=`using System;
|
|
147
|
+
using System.Runtime.InteropServices;
|
|
148
|
+
class CometProcessIdentity {
|
|
149
|
+
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
|
150
|
+
[DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
|
|
151
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
|
152
|
+
static int Main(string[] args) {
|
|
153
|
+
int pid; if(args.Length != 1 || !int.TryParse(args[0], out pid) || pid <= 0) return 1;
|
|
154
|
+
IntPtr handle=OpenProcess(0x1000, false, pid); if(handle == IntPtr.Zero) return 1;
|
|
155
|
+
try { long creation, exit, kernel, user; if(!GetProcessTimes(handle,out creation,out exit,out kernel,out user)) return 1;
|
|
156
|
+
Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
|
|
157
|
+
} finally { CloseHandle(handle); }
|
|
158
|
+
}
|
|
159
|
+
}`,MS=Ll("sha256").update(Lh).digest("hex"),FS=1e4,po=new Map});import{promises as qh}from"node:fs";function zS(e){let t=Ml.get(e);if(t){if(Date.now()-t.at>WS){Ml.delete(e);return}return t.value}}async function cn(e){if(e===process.pid&&Bl!==null)return Bl;let t=zS(e);if(t!==void 0)return t;let r=ho.get(e);r||(r=GS(e),ho.set(e,r));let i=await r;return ho.get(e)===r&&ho.delete(e),e===process.pid&&i!==null&&(Bl=i),i===null&&Ml.set(e,{value:null,at:Date.now()}),i}async function GS(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([qh.readFile(`/proc/${e}/stat`,"utf8"),qh.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await Mh(e);if(process.platform==="darwin"){let t=(await Pt("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return t?`darwin:${t}`:null}}catch{}return null}function mo(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function Fl(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await cn(e);return r===t?"alive":r===null||mo(r)!==mo(t)&&Vh.has(mo(r))&&Vh.has(mo(t))?"unknown":"dead"}var Bl,WS,Ml,ho,Vh,vo=S(()=>{"use strict";Jn();Fh();Bl=null,WS=1e4,Ml=new Map,ho=new Map;Vh=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as JS}from"async_hooks";import{randomUUID as Gh}from"crypto";import{promises as Ne}from"fs";import Jh from"os";import V from"path";function YS(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function XS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Uh(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function wo(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ae(r,i)?j(r,i):j(r,i)&&e.size===t.size}function ln(e,t){return wo(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function QS(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&ln(e.identity,t.identity)}async function ke(e){let t,r;try{let i=await Mr(e,Wh,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Oe?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Wh} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:XS(JSON.parse(t.toString("utf8")),e),identity:Uh(r)}}async function ZS(e){return(await ke(e))?.owner??null}async function Vl(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Jh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await Fl(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function eE(e,t){try{await Ne.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Ne.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function yo(e,t){let r=await ke(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!ln(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ne.mkdir(t,{recursive:!0});let i=V.join(t,`${V.basename(e.file)}.${e.owner.id}.${Gh()}.removed`);try{await Ne.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ke(i);if(!n||n.owner.id!==e.owner.id||!wo(n.identity,e.identity))throw await eE(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ne.rm(i,{force:!0}),"removed"}async function Kh(e){let t=await cn(process.pid);return{id:Gh(),pid:process.pid,hostname:Jh.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Yh(e,t){let r;try{r=await Ne.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await ZS(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
160
|
+
`,"utf8"),await r.sync(),i=Uh(await r.stat({bigint:!0}))}finally{await r.close()}let n=await ke(e);if(!i||!n||n.owner.id!==t.id||!wo(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function tE(e,t){let r=await T(e.runtimeDir,e.locksDir);await Ne.mkdir(r,{recursive:!0});let i=await T(e.runtimeDir,V.join(r,ql));await Ne.mkdir(i,{recursive:!0});let n=await Kh(t),a=V.join(i,`.${n.id}.tmp`),o=V.join(i,`${n.id}.claim`);try{let s=await Yh(a,n);await Ne.rename(a,o);let l=await ke(o);if(!l||!wo(s,l.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:l.identity}}finally{await Ne.rm(a,{force:!0})}}async function rE(e){let t=V.dirname(e.file),r=!1,i=V.basename(e.file);for(let n of await Ne.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=V.join(t,n.name);if(V.resolve(a)!==V.resolve(e.file))try{let o=await ke(a),s=await Vl(o);if(s.status==="missing")continue;let l=await ke(a);if(!l)continue;if(!o||l.owner.id!==o.owner.id||!ln(l.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await yo(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Xh(e){let t=await ke(e.file);if(t){if(t.owner.id!==e.owner.id||!ln(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await yo(t,V.dirname(e.file))}}async function iE(e,t){let r=Date.now()+US;for(;;){let i=await tE(e,t);if(!await rE(i))return i;if(await Xh(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 nE(e){let t=go.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return go.set(e,n),await t,()=>{r(),go.get(e)===n&&go.delete(e)}}async function Wl(e,t,r){let i=V.resolve(e.locksDir),n=zh.getStore();if(n?.has(i))return r();let a=await nE(i);try{let o=await iE(e,t),s=new Map(n??[]);return s.set(i,o),await zh.run(s,async()=>{try{return await r()}finally{await Xh(o)}})}finally{a()}}async function bo(e,t,r){return Wl(e,`acquire ${t}`,async()=>{let i=await T(e.runtimeDir,e.locksDir);await Ne.mkdir(i,{recursive:!0});let n=await T(e.runtimeDir,V.join(i,YS(t))),a=await Kh(r),o=await Yh(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function No(e){await ke(e.file)&&await Wl({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${V.basename(e.file)}`,async()=>{let t=await ke(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!ln(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=V.join(e.locksDir,ql);await yo(t,r)})}function aE(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 Qh(e){return Vl(await ke(e))}async function Zh(e,t,r,i={}){return Wl(e,`take over ${V.basename(t)}`,async()=>{let n=await T(e.runtimeDir,e.locksDir),a=await T(e.runtimeDir,t);if(V.resolve(V.dirname(a))!==V.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await ke(a),s=await Vl(o);if(s.status==="missing")return{status:"missing"};if(r&&!QS(r,s))return{status:"changed",diagnosis:s};let l=i.allowAgedUnknown===!0&&s.status==="unknown"&&aE(o?.owner??null)>=KS;if(s.status!=="stale"&&!l||!o)return{status:"changed",diagnosis:s};let c=V.join(n,ql);return await yo(o,c)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Wh,ql,US,KS,zh,go,un=S(()=>{"use strict";an();vo();L();Ge();Wh=16*1024,ql=".coordinator",US=5e3,KS=900*1e3,zh=new JS,go=new Map});import{createHash as oE}from"node:crypto";function or(e){return e.replaceAll(`\r
|
|
148
161
|
`,`
|
|
149
162
|
`).replaceAll("\r",`
|
|
150
|
-
`)}function
|
|
151
|
-
`),i=
|
|
163
|
+
`)}function Jr(e){return oE("sha256").update(or(e)).digest("hex")}function Kl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new R(`${t} must be an object`);return e}function am(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new R(`${r} has unknown field(s): ${i.join(", ")}`)}function Yl(e,t){if(typeof e!="string"||e.trim().length===0)throw new R(`${t} must be a non-empty string`);return e.trim()}function tm(e,t){if(e!==void 0){if(typeof e!="string")throw new R(`${t} must be text`);return or(e).replace(/^\n+|\n+$/gu,"")}}function ko(e,t){let r=Yl(e,t).toLowerCase();if(!cE.test(r))throw new R(`${t} must be a SHA-256 hash`);return r}function rm(e,t,r){let i=Kl(e,t),n=Object.entries(i);if(n.length>em)throw new R(`${t} must contain at most ${em} entries`);let a={};for(let[o,s]of n){if(Jl(o,`${t} ID`)!==o)throw new R(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=ko(s,`${t}.${o}`)}return a}function Jl(e,t){let r=Yl(e,t);if(!nm.test(r))throw new R(`${t} is not a valid stable requirement ID`);return r}function lE(e,t){let r=Yl(e,t);if(!sE.test(r))throw new R(`${t} is not a valid capability ID`);return r}function uE(e,t){let r=`Native delta operations[${t}]`,i=Kl(e,r);am(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Jl(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new R(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Jl(i.to_id,`${r}.to_id`),l=tm(i.title,`${r}.title`),c=tm(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:ko(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!c?.trim())throw new R(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!c?.trim())throw new R(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||l!==void 0||c!==void 0||!u)throw new R(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||c==="")throw new R(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...l===void 0?{}:{title:l},...c===void 0?{}:{body:c},...u===void 0?{}:{expected_hash:u}}}function dE(e){let t=Kl(e,"Native delta");if(am(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==zl)throw new R(`Native delta schema must be ${zl}`);let r=lE(t.capability,"Native delta capability"),i=ko(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new R("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:ko(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=rm(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:rm(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new R("Native delta operations must be an array");let s=t.operations.map(uE),l=new Set;for(let[c,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let f of d){if(l.has(f))throw new R(`Native delta operations contain duplicate or overlapping requirement ID ${f} at ${c}`);l.add(f)}}if(o!==void 0){if(a===void 0)throw new R("Native delta independent_requirements requires base_requirements");for(let[c,u]of Object.entries(o)){if(l.has(c))throw new R(`Native delta requirement ${c} cannot be both addressed and independent`);let d=a[c];if(u===null?d!==void 0:d!==u)throw new R(`Native delta independent_requirements does not match baseline ${c}`)}}return{schema:zl,capability:r,base_hash:i,base_version:Number(t.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function fE(e){let t=(0,Ul.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new R(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function dn(e){return dE(typeof e=="string"?fE(e):e)}function pE(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function hE(e){let t=[],r=null;for(let[i,n]of e.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(!nm.test(s))throw new R(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function ar(e){let t=or(e),r=t.split(`
|
|
164
|
+
`),i=hE(r),n=[],a=new Set;for(let c of i){if(a.has(c.id))throw new R(`Native total Spec contains duplicate requirement ID ${c.id}`);a.add(c.id);let u=r.length;for(let d=c.line+1;d<r.length;d+=1){if(i.some(m=>m.line===d)){u=d;break}let f=pE(r[d]);if(f!==null&&f<=c.level){u=d;break}}n.push({start:c.line,end:u,marker:c})}let o=new Map;for(let c of n){let u=`${r.slice(c.start,c.end).join(`
|
|
152
165
|
`)}${c.end<r.length?`
|
|
153
166
|
`:""}`,d=r.slice(c.start+1,c.end).join(`
|
|
154
167
|
`).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(c.marker.id,{id:c.marker.id,level:c.marker.level,title:c.marker.title,body:d,raw:u,startLine:c.start,endLine:c.end})}let s=[],l=0;for(let c of n)s.push(r.slice(l,c.start).join(`
|
|
155
168
|
`)),l=c.end;return s.push(r.slice(l).join(`
|
|
156
169
|
`)),{text:t,lines:r,requirements:o,legacyText:s.join(`
|
|
157
|
-
`)}}function
|
|
170
|
+
`)}}function Xl(e){return Jr(e)}function pt(e){return Jr(e)}function om(e){let t=ar(e).legacyText;return Jr(t.split(`
|
|
158
171
|
`).filter(r=>r.trim().length>0).join(`
|
|
159
|
-
`).trim())}function
|
|
172
|
+
`).trim())}function sm(e,t){let r=ar(e),i=[];for(let n of t.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new R(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
|
|
160
173
|
|
|
161
174
|
`)}
|
|
162
|
-
`}function
|
|
175
|
+
`}function So(e,t,r,i){let n=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,a=or(i).replace(/\n+$/u,"");return[n,"",...a.split(`
|
|
163
176
|
`),"",""].join(`
|
|
164
|
-
`)}function
|
|
177
|
+
`)}function Gl(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function Eo(e,t){if(e.operation==="rename"){if(!t)throw new R(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function mE(e,t,r){let i=ar(e),n=[...i.lines],a=i.requirements.get(t.id);if(!a)throw new R(`Requirement target disappeared: ${t.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
|
|
165
178
|
`)),n.join(`
|
|
166
|
-
`)}function
|
|
179
|
+
`)}function vE(e,t){let r=or(e),i=r.length===0||r.endsWith(`
|
|
167
180
|
|
|
168
181
|
`)?"":`
|
|
169
182
|
`,n=`${r}${i}`;return`${n.endsWith(`
|
|
170
183
|
`)||n.length===0?n:`${n}
|
|
171
|
-
`}${t}`}function
|
|
172
|
-
`)}else t=Hk(t,s,Va(l.level,l.id,l.title,l.body))}r.push(...ol(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:ol(a)})}let n=Ut(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:Rr(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function ih(e){let t=Jt(e.baselineMarkdown);if(Rr(t.text)!==e.delta.base_hash)throw new Gt([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);Mk(e.delta,t),Bk(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&rh(r,t)||Lk(r,t);return Fk({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}var cl,al,Xp,Rk,Qp,_k,Up,P,Gt,fl=S(()=>{"use strict";cl=mt(Ze(),1),al="comet.native.delta.v1",Xp="delta.yaml",Rk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Qp=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,_k=/^[a-f0-9]{64}$/iu,Up=512,P=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},Gt=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var Fe,Ve,qe,Bi=S(()=>{"use strict";Fe="comet.native.v3",Ve="comet.native.v2",qe="comet.native.v1"});import Vk from"node:path";function Vi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function sh(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 qi(e){if(!oh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ch(e){if(!oh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function lh(e,t){if(e.length===0||Vk.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Yk(e,t){let r=Vi(e,`spec_changes[${t}]`);if(sh(r,zk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(ch(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"&&lh(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"||!hl.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"||!hl.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 Xk(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 ml(e,t){if(sh(e,t,nt),typeof e.name!="string")throw new Error("Native change name is required");if(qi(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"||!Gk.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&&!Jk.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(Yk),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"||!Uk.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"&&lh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Xk(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 _r(e){let t=Vi(e,nt);if(t.schema!==qe)throw new Error(`Expected ${qe}`);return{schema:qe,...ml(t,qk)}}function Fi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pl(e,t,r){if(e===null)return null;let i=typeof e=="string"?Kk.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 Qk(e){if(e==null)return null;if(typeof e!="string"||!hl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Zk(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 Ar(e){let t=Vi(e,nt);if(t.schema!==Ve)throw new Error(`Expected ${Ve}`);if(Fi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ve} minimum_runtime_version must be 2`);return{schema:Ve,minimum_runtime_version:2,revision:Fi(t.revision,"Native v2 revision"),...ml(t,ah)}}function Kt(e){let t=Vi(e,nt);if(t.schema!==Fe){if(t.schema===qe||t.schema===Ve){let o=t.schema===qe?_r(t):Ar(t);throw new Mi(o.name,o.schema)}throw new We(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Fi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new We(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Fi(t.revision,"Native revision"),n=ml(t,Wk),a=Qk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Fe,minimum_runtime_version:3,revision:i,verification_protocol:Zk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:pl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:pl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:pl(t.partial_allowance,"Native partial_allowance","allowances")}}function vl(e){let t=Vi(e,nt);if(t.schema===qe){let n=_r(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Fe}`}}if(t.schema===Ve){let n=Ar(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Fe}`}}if(t.schema!==Fe){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 We(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Fi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new We(t.schema,r).message};let i=Kt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var nh,qk,ah,Wk,zk,Gk,Jk,Uk,nt,hl,oh,Kk,Mi,We,Wa=S(()=>{"use strict";Bi();nh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],qk=new Set(nh),ah=new Set([...nh,"minimum_runtime_version","revision"]),Wk=new Set([...ah,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),zk=new Set(["capability","operation","source","base_hash"]),Gk=new Set(["shape","build","verify","archive"]),Jk=new Set(["implicit","confirmed"]),Uk=new Set(["pending","pass","fail"]),nt="comet-state.yaml",hl=/^[a-f0-9]{64}$/u,oh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Kk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Mi=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"},We=class extends Error{constructor(r,i){super(r!==Fe||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"}});function fh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function uh(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function dh(e){return e.includes("-->")||e.includes("--!>")}function*za(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
184
|
+
`}${t}`}function cm(e,t){if(e.operation==="add"||e.operation==="modify"){let a=t.requirements.get(e.id);if(!a)return!1;let o=Eo(e,e.operation==="modify"?a:void 0);return a.raw===So(o.level,o.id,o.title,o.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),i=t.requirements.get(e.id);if(!r||i)return!1;let n=Eo(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===So(n.level,n.id,n.title,n.body)}function gE(e,t){let r=t.requirements.get(e.id);if(e.operation==="add"){if(r)throw new R(`Add target already exists: ${e.id}`);return}if(!r)throw new R(`Native delta target does not exist: ${e.id}`);if(e.expected_hash!==Xl(r.raw))throw new R(`Native delta ${e.operation} expected_hash does not match ${e.id}`);if(e.operation==="rename"&&t.requirements.has(e.to_id))throw new R(`Rename destination already exists: ${e.to_id}`)}function wE(e,t){if(e.base_requirements===void 0)return;let r=e.base_requirements,i=t.requirements;if(Object.keys(r).length!==i.size)throw new R("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==Xl(a.raw))throw new R(`Native delta base_requirements does not match requirement ${n}`)}function yE(e,t){let r=om(t.text);if(r!==Jr("")&&e.legacy_hash!==r)throw new R("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function bE(e){let t=or(e.baselineMarkdown),r=[],i=[];for(let a of e.delta.operations){let o=ar(t),s=o.requirements.get(a.id);if(e.allowAlreadyApplied&&cm(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:Gl(a)});continue}if(a.operation==="add"){if(s)throw new nr([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let l=Eo(a,void 0);t=vE(t,So(l.level,l.id,l.title,l.body))}else{if(!s)throw new nr([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==Xl(s.raw))throw new nr([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let l=Eo(a,s);if(a.operation==="rename"&&ar(t).requirements.has(a.to_id))throw new nr([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let c=[...ar(t).lines];c.splice(s.startLine,s.endLine-s.startLine),t=c.join(`
|
|
185
|
+
`)}else t=mE(t,s,So(l.level,l.id,l.title,l.body))}r.push(...Gl(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:Gl(a)})}let n=or(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:Jr(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function lm(e){let t=ar(e.baselineMarkdown);if(Jr(t.text)!==e.delta.base_hash)throw new nr([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);yE(e.delta,t),wE(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&cm(r,t)||gE(r,t);return bE({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}var Ul,zl,im,sE,nm,cE,em,R,nr,Ql=S(()=>{"use strict";Ul=Ct(ut(),1),zl="comet.native.delta.v1",im="delta.yaml",sE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nm=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,cE=/^[a-f0-9]{64}$/iu,em=512,R=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},nr=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var Ye,Xe,Qe,fn=S(()=>{"use strict";Ye="comet.native.v3",Xe="comet.native.v2",Qe="comet.native.v1"});import NE from"node:path";function mn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function pm(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 vn(e){if(!fm.test(e))throw new Error(`Invalid Native change name: ${e}`)}function hm(e){if(!fm.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function mm(e,t){if(e.length===0||NE.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function _E(e,t){let r=mn(e,`spec_changes[${t}]`);if(pm(r,EE,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(hm(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"&&mm(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"||!eu.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"||!eu.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 AE(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 tu(e,t){if(pm(e,t,mt),typeof e.name!="string")throw new Error("Native change name is required");if(vn(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"||!xE.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&&!CE.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(_E),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"||!PE.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"&&mm(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!AE(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 Ur(e){let t=mn(e,mt);if(t.schema!==Qe)throw new Error(`Expected ${Qe}`);return{schema:Qe,...tu(t,kE)}}function hn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zl(e,t,r){if(e===null)return null;let i=typeof e=="string"?RE.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 IE(e){if(e==null)return null;if(typeof e!="string"||!eu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function TE(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 Kr(e){let t=mn(e,mt);if(t.schema!==Xe)throw new Error(`Expected ${Xe}`);if(hn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Xe} minimum_runtime_version must be 2`);return{schema:Xe,minimum_runtime_version:2,revision:hn(t.revision,"Native v2 revision"),...tu(t,dm)}}function sr(e){let t=mn(e,mt);if(t.schema!==Ye){if(t.schema===Qe||t.schema===Xe){let o=t.schema===Qe?Ur(t):Kr(t);throw new pn(o.name,o.schema)}throw new Ze(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=hn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Ze(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=hn(t.revision,"Native revision"),n=tu(t,SE),a=IE(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:i,verification_protocol:TE(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Zl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Zl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Zl(t.partial_allowance,"Native partial_allowance","allowances")}}function ru(e){let t=mn(e,mt);if(t.schema===Qe){let n=Ur(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema===Xe){let n=Kr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema!==Ye){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Ze(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=hn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Ze(t.schema,r).message};let i=sr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var um,kE,dm,SE,EE,xE,CE,PE,mt,eu,fm,RE,pn,Ze,xo=S(()=>{"use strict";fn();um=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],kE=new Set(um),dm=new Set([...um,"minimum_runtime_version","revision"]),SE=new Set([...dm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),EE=new Set(["capability","operation","source","base_hash"]),xE=new Set(["shape","build","verify","archive"]),CE=new Set(["implicit","confirmed"]),PE=new Set(["pending","pass","fail"]),mt="comet-state.yaml",eu=/^[a-f0-9]{64}$/u,fm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,RE=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,pn=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"},Ze=class extends Error{constructor(r,i){super(r!==Ye||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"}});function wm(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function vm(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function gm(e){return e.includes("-->")||e.includes("--!>")}function*Co(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
173
186
|
`),o=0,s=0;for(;o<=a.length;){let l=a.indexOf(`
|
|
174
|
-
`,o),c=l===-1?a.slice(o):a.slice(o,l);if(yield{line:c,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=
|
|
175
|
-
`),[],i)),"Brief",i)}function
|
|
176
|
-
`),o.context,i)),o=null}};for(let{line:l,body:c}of za(e)){let u=c?fh(l):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=Wi(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(l);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&c&&o.body.push(l)}return s(),hh(n,"Specification",i)}var eS,$A,Ga,Ja=S(()=>{"use strict";Vt();J();eS="comet.native.acceptance.v1",$A=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ga=Object.freeze({maxCriteria:1024})});import mh from"node:path";function vh(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||mh.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||mh.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function iS(e,t){return e.localeCompare(t,"en")}function Ua(e){let t=vh(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>iS(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=gl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=vh(a.source,`Native spec source for ${a.capability}`);i.push(...wl(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Wi(a.text);let o=a.text;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function gh(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!rS.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function yl(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var rS,Ka=S(()=>{"use strict";Ja();rS=/^A[1-9]\d*$/u});import{promises as nS}from"node:fs";function te(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function re(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 U(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 bl(e,t){return e===null?null:U(e,t)}function kl(e,t){let r=U(e,t);if(!cS.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Ir(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function D(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 uS(e,t){return e===null?null:D(e,t,Number.MIN_SAFE_INTEGER)}function V(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function ze(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function eo(e,t){return ze(e,t,(r,i)=>U(r,`${t}[${i}]`))}function Yt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Tr(e,t){let r=U(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Qa(e,t,r=!1){let i=U(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 ve(e,t){let r=te(e,t);return re(r,new Set(["text","truncated"]),t),{text:U(r.text,`${t}.text`,{empty:!0}),truncated:Ir(r.truncated,`${t}.truncated`)}}function dS(e,t){let r=`Native spec_changes[${t}]`,i=te(e,r);re(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=U(i.capability,`${r}.capability`);if(!oS.test(n))throw new Error(`${r}.capability is invalid`);let a=V(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Qa(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Qa(i.delta_source,`${r}.delta_source`),l=i.base_hash===void 0?void 0:i.base_hash===null?null:kl(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&&l==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(l!==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},...l===void 0?{}:{base_hash:l}}}function fS(e){let t="Native workspace",r=te(e,t);re(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=V(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=bl(r.change_branch,`${t}.change_branch`),a=bl(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:V(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 pS(e){let t="Native loop",r=te(e,t);re(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=eo(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Yt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:V(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:V(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:D(r.goal_cycle,`${t}.goal_cycle`,1),iteration:D(r.iteration,`${t}.iteration`),attempt:D(r.attempt,`${t}.attempt`),retry_epoch:D(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:D(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:D(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:D(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:bl(r.next_action,`${t}.next_action`)}}function hS(e,t){let r=`Native acceptance[${t}]`,i=te(e,r);re(i,new Set(["id","source","text","result","reason"]),r);let n=U(i.id,`${r}.id`);if(!sS.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Qa(i.source,`${r}.source`),text:U(i.text,`${r}.text`),result:V(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ve(i.reason,`${r}.reason`)}}function mS(e,t){let r=`Native builder_handoff.checks[${t}]`,i=te(e,r);return re(i,new Set(["name","result","note"]),r),{name:ve(i.name,`${r}.name`),result:V(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ve(i.note,`${r}.note`)}}function vS(e){let t="Native builder_handoff",r=te(e,t);re(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=eo(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Yt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:te(r.review,`${t}.review`);return n&&re(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:U(r.candidate_id,`${t}.candidate_id`),identity_provider:U(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:U(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:D(r.iteration,`${t}.iteration`,1),summary:ve(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:ze(r.checks,`${t}.checks`,mS),checks_truncated:Ir(r.checks_truncated,`${t}.checks_truncated`),known_limits:ze(r.known_limits,`${t}.known_limits`,(a,o)=>ve(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Ir(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:V(n.status,["passed"],`${t}.review.status`),summary:ve(n.summary,`${t}.review.summary`),reviewer_execution_ref:U(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Tr(r.submitted_at,`${t}.submitted_at`)}}function gS(e,t){let r=`Native blockers[${t}]`,i=te(e,r);re(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=eo(i.acceptance_ids,`${r}.acceptance_ids`);return Yt(n,`${r}.acceptance_ids`),{owner:V(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ve(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:V(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function wS(e,t){let r=`Native verification.checks[${t}]`,i=te(e,r);return re(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:U(i.id,`${r}.id`),name:ve(i.name,`${r}.name`),argv_display:ze(i.argv_display,`${r}.argv_display`,(n,a)=>ve(n,`${r}.argv_display[${a}]`)),argv_truncated:Ir(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Qa(i.cwd_ref,`${r}.cwd_ref`,!0),status:V(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:uS(i.exit_code,`${r}.exit_code`),duration_ms:D(i.duration_ms,`${r}.duration_ms`)}}function yS(e){let t="Native verification",r=te(e,t);re(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=ze(r.checks,`${t}.checks`,wS);Yt(i.map(a=>a.id),`${t}.checks IDs`);let n=U(r.identity_provider,`${t}.identity_provider`);return{candidate_id:U(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:U(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:D(r.iteration,`${t}.iteration`,1),attempt:D(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":V(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:V(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ve(r.summary,`${t}.summary`),risks:ze(r.risks,`${t}.risks`,(a,o)=>ve(a,`${t}.risks[${o}]`)),risks_truncated:Ir(r.risks_truncated,`${t}.risks_truncated`),completed_at:Tr(r.completed_at,`${t}.completed_at`)}}function wh(e,t){let r=`Native history[${t}]`,i=te(e,r);re(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=eo(i.unresolved_ids,`${r}.unresolved_ids`);return Yt(n,`${r}.unresolved_ids`),{goal_cycle:D(i.goal_cycle,`${r}.goal_cycle`,1),iteration:D(i.iteration,`${r}.iteration`),attempt:D(i.attempt,`${r}.attempt`),outcome:V(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ve(i.summary,`${r}.summary`),completed_at:Tr(i.completed_at,`${r}.completed_at`)}}function NS(e){let t="Native history_overflow.outcome_counts",r=te(e,t),i=["pass","fail","blocked","execution-error","recovery"];return re(r,new Set(i),t),{pass:D(r.pass,`${t}.pass`),fail:D(r.fail,`${t}.fail`),blocked:D(r.blocked,`${t}.blocked`),"execution-error":D(r["execution-error"],`${t}.execution-error`),recovery:D(r.recovery,`${t}.recovery`)}}function bS(e){let t="Native history_overflow",r=te(e,t);re(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=D(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Tr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Tr(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=NS(r.outcome_counts);if(Object.values(o).reduce((l,c)=>l+c,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 kS(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 SS(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 ge(e){let t=te(e,"Native portable state");if(re(t,lS,"Native portable state"),t.schema!==cr)throw new Error(`Native portable state schema must be ${cr}`);let r=U(t.name,"Native state name");if(!aS.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=ze(t.spec_changes,"Native spec_changes",dS);Yt(i.map(s=>s.capability),"Native spec change capabilities");let n=ze(t.acceptance,"Native acceptance",hS);Yt(n.map(s=>s.id),"Native acceptance IDs");let a=ze(t.history,"Native history",wh);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:cr,name:r,language:V(t.language,["en","zh-CN"],"Native state language"),phase:V(t.phase,["shape","build","verify","archive"],"Native state phase"),status:V(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:D(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:kl(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:kl(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:V(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:fS(t.workspace),loop:pS(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:vS(t.builder_handoff),blockers:ze(t.blockers,"Native blockers",gS),verification:t.verification===null?null:yS(t.verification),history:a,history_overflow:bS(t.history_overflow),verification_result:V(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:V(t.verification_report,["verification.md"],"Native verification_report"),archived:Ir(t.archived,"Native archived"),created_at:Tr(t.created_at,"Native created_at")};return kS(o),SS(o),o}function Xt(e,t){let r=ge(e),i=wh(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ge({...r,history:n,history_overflow:a})}function ES(e,t){let r=(0,Za.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 at(e){let t=await nS.readFile(e,"utf8");return ge(ES(t,"Native portable state"))}async function to(e,t,r={}){let i=ge(t);await ue(e,(0,Za.stringify)(i),r)}async function xS(e,t){let r=Ya.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Ya.set(e,a),await r;try{return await t()}finally{i(),Ya.get(e)===a&&Ya.delete(e)}}async function yh(e){return xS(e.file,async()=>{let t=D(e.expectedStateVersion,"Native expected state version",1),r=ge(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await at(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Xa(t,i.state_version);return await to(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await at(e.file);if(n.state_version!==t)throw new Xa(t,n.state_version)}}),r})}var Za,aS,oS,sS,cS,lS,Xa,Ya,ot=S(()=>{"use strict";Za=mt(Ze(),1);L();Jr();aS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sS=/^A[1-9][0-9]*$/u,cS=/^[a-f0-9]{64}$/u,lS=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"]),Xa=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Ya=new Map});function CS(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function je(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(CS(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Qt=S(()=>{"use strict"});import PS from"node:path";function jS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $S(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function OS(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 HS(e){return e.schema===qe?_r(e):e.schema===Ve?Ar(e):Kt(e)}function DS(e){return PS.posix.normalize(e.replaceAll("\\","/"))}function LS(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:DS(t.source)})}function BS(e){return e==="shape"?"shape":"build"}function MS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function FS(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function Nh(e){let t=HS(e.state);gh(e.acceptance);let r=BS(t.phase),i=r==="shape"?0:1,n=$S(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return ge({schema:cr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:LS(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:MS(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:je(FS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Bo(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Sl(e){let t=jS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!RS.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==ro)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!AS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!_S.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!TS.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!IS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:ro,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:OS(t.createdAt,"Native portable migration transaction createdAt")}}function bh(e){switch(Sl(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var ro,RS,_S,AS,IS,TS,El=S(()=>{"use strict";Wa();Ka();ot();Qt();Jr();Bi();ro="comet.native.portable-migration.v1",RS=new Set(["schema","id","change","fromSchema","status","createdAt"]),_S=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AS=/^[a-z0-9][a-z0-9-]{7,127}$/u,IS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),TS=new Set([qe,Ve,Fe])});import Cl from"node:path";function Ch(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ph(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 xl(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 Sh(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function KS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Ch(e,r);if(Ph(i,US,r),typeof i.capability!="string"||!xh.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=xl(i.base_hash,`${r}.base_hash`),s=Sh(i.delta_content,`${r}.delta_content`),l=Sh(i.source_content,`${r}.source_content`),c=xl(i.expected_target_hash,`${r}.expected_target_hash`),u=xl(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||l===void 0||l===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||l!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=Li(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(rt(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(rt(l)!==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||l!==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},...c===void 0?{}:{expected_target_hash:c}}}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||rt(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},...l===void 0?{}:{source_content:l},...c===void 0?{}:{expected_target_hash:c},...u===void 0?{}:{result_hash:u}}}function YS(e){let t=Ch(e,"Native portable Archive transaction");if(Ph(t,JS,"Native portable Archive transaction"),t.schema!==kh)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!WS.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!xh.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"||!zS.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"||!GS.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(KS);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:kh,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 io(e){let t=VS.exec(e);if(t)return{kind:"archive",change:t[1]};let r=qS.exec(e);return r?{kind:"migration",change:r[1]}:null}function no(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=io(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Cl.join(e.transactionsDir,r)}async function Pl(e,t){let r=io(t);if(!r)return null;let i=await T({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Cl.join(e.transactionsDir,t);if(r.kind==="archive"){let s=YS(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=Sl(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}}async function Rl(e,t){let r=no(e,t);try{return await Pl(e,Cl.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Rh(e){return e.kind==="archive"||e.journal.status!=="committed"}var kh,Eh,VS,qS,WS,zS,GS,JS,US,xh,ao=S(()=>{"use strict";fe();fl();El();kh="comet.native.archive-transaction.v4",Eh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",VS=new RegExp(`^portable-archive-(${Eh})\\.json$`,"u"),qS=new RegExp(`^portable-migration-(${Eh})\\.json$`,"u"),WS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,zS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),JS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),US=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),xh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as XS}from"node:crypto";import{constants as oo,promises as $e}from"node:fs";import Oe from"node:path";function co(e,t){let r=Oe.relative(e,t);return r===""||!Oe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Oe.sep}`)}function QS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function ZS(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function eE(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function so(e,t){return j({...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 _l(e,t){let r=await $e.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await $e.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function tE(e,t,r){let i=Oe.resolve(e),n=Oe.resolve(t);if(!co(i,n))throw new Error(`${r} is outside its managed root`);let a=[await _l(i,r)],o=i;for(let s of Oe.relative(i,n).split(Oe.sep).filter(Boolean)){await Zt(a,r),o=Oe.join(o,s);let l=await _l(o,r);if(!co(a[0].realPath,l.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(l)}return await Zt(a,r),a}async function Zt(e,t){for(let r of e){let i=await $e.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!ZS(r,i)||await $e.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function rE(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 zi(e){let t=e.maxBytes===null?null:QS(e.maxBytes),r=Oe.resolve(e.file),i=await tE(e.root,Oe.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>_l(Oe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Zt(i,e.label);let a=await $e.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=eE(a),s=await $e.realpath(r);if(!co(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>co(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let l=process.platform==="win32"?oo.O_RDONLY:oo.O_RDONLY|oo.O_NOFOLLOW|oo.O_NONBLOCK,c=await $e.open(r,l);try{let u=await c.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([$e.lstat(r),$e.realpath(r)]);if(await Zt(i,e.label),await Zt(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!so(o,u)||!so(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await rE(c,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([c.stat(),$e.lstat(r),$e.realpath(r)]);if(await Zt(i,e.label),await Zt(n,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!so(o,m)||!so(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:XS("sha256").update(h).digest("hex"),size:h.length}}finally{await c.close()}}var Ge=S(()=>{"use strict";L();Le()});import st from"path";import{TextDecoder as nE}from"util";function uo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fo(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 Th(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Al(e,t){if(typeof e!="string"||e.length===0||st.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function lo(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function _h(e,t){if(Al(e,t),e.includes("\\")||e!==st.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function uE(e,t){let r=uo(e,`transaction operations[${t}]`);if(fo(r,oE,`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`);Al(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Al(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 jh(e){let t=uo(e,"Native Archive transaction journal");if(fo(t,sE,"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"||!Ih.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(!Th(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(lo(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,l)=>{let c=uo(s,`Archive transaction operations[${l}]`);if(fo(c,cE,`Archive transaction operations[${l}]`),typeof c.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(c.id))throw new Error(`Archive transaction operations[${l}].id is invalid`);if(c.type!=="write"&&c.type!=="remove"&&c.type!=="move")throw new Error(`Archive transaction operation ${c.id} has an invalid type`);_h(c.target,`Archive transaction operation ${c.id} target`);for(let u of["source","staged","backup"])c[u]!==void 0&&_h(c[u],`Archive transaction operation ${c.id} ${u}`);if(c.expectedTargetHash!==null&&lo(c.expectedTargetHash,`Archive transaction operation ${c.id} expectedTargetHash`),c.type==="write"){if(c.staged===void 0||c.source!==void 0||c.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${c.id} requires staged and forbids source`);if(lo(c.stagedHash,`Archive write operation ${c.id} stagedHash`),c.expectedTargetHash===null!=(c.backup===void 0))throw new Error(`Archive write operation ${c.id} backup must match target existence`)}else if(c.type==="remove"){if(c.source!==void 0||c.staged!==void 0||c.stagedHash!==void 0||c.expectedSourceHash!==void 0||c.backup===void 0||c.expectedTargetHash===null)throw new Error(`Archive remove operation ${c.id} requires a bound target and backup`)}else{if(c.source===void 0||c.staged!==void 0||c.stagedHash!==void 0||c.backup!==void 0||c.expectedTargetHash!==null)throw new Error(`Archive move operation ${c.id} requires source and an absent target`);lo(c.expectedSourceHash,`Archive move operation ${c.id} expectedSourceHash`)}return c}),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 dE(e){let t=uo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return jh(t);if(fo(t,aE,"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"||!Ih.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!st.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!st.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Th(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(uE),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 fE(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return st.join(e.transactionsDir,t)}function $h(e,t){let r=fE(e,t);return{directory:r,journal:st.join(r,"transaction.json"),events:st.join(r,"events.jsonl"),staged:st.join(r,"staged"),backups:st.join(r,"backups")}}async function Tl(e,t){let r=$h(e,t);return await Promise.all(Object.values(r).map(i=>I(e.runtimeDir,i))),r}async function jl(e,t,r={}){let i=await Tl(e,t),n=await zi({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(lE.decode(n.bytes)),o=dE(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var aE,oE,sE,cE,Ih,lE,po=S(()=>{"use strict";L();H();Ge();aE=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),oE=new Set(["id","type","source","target","staged","backup"]),sE=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),cE=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Ih=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),lE=new nE("utf-8",{fatal:!0})});import{promises as pE}from"fs";import hE from"path";async function mE(e,t,r){let i;try{i=await pE.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 jl(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(io(n.name))try{let a=await Pl(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Rh(a))return!0}catch{return!0}return!1}async function vE(e,t){let r=Date.now()+5e3,i=hE.join(e.locksDir,"root-move.lock");for(;;)try{return await Ba(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Gp(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Jp(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 B(e,t,r,i){let n=await vE(e,t);try{if(await Aa(e.projectRoot),await mE(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Ma(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
|
|
177
|
-
`)}}}var K=S(()=>{"use strict";he();Di();ao();po()});import{createHash as gE}from"crypto";function we(e){return gE("sha256").update(e).digest("hex")}var Je=S(()=>{"use strict"});var DI,LI,BI,MI,FI,VI,Gi=S(()=>{"use strict";L();he();Je();Le();H();Ge();Xr();DI={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},LI=64*1024,BI=64*1024,MI={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},FI={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024},VI=(1n<<256n)-1n});var qh=S(()=>{"use strict"});var y$,ct=S(()=>{"use strict";qh();y$=8*1024*1024});import{promises as ax}from"node:fs";import ox from"node:path";function bo(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function No(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function em(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function fx(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function tm(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(l=>!i.has(l));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function am(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===ql&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=o.filter(c=>!a.includes(c));let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of o){let u=s.get(c),d=e.acceptance_index[c];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(c)}let l=new Set(o);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(u=>!l.has(u)));return i.uncovered=o.filter(c=>!rm(e.children,c)),im(i)?i:null}if(e.schema===tr&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!rm(e.children,a)),im(i)?i:null}return null}function rm(e,t){return e.some(r=>r.covers.includes(t))}function im(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function ir(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function px(e){let t=bo(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=bo(n,`Native children acceptance_index.${i}`);if(No(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function hx(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(c=>!(c in e)),s=a.filter(c=>!n.includes(c));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let l=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of a){let u=l.get(c);if(!u)continue;let d=e[c];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function om(e,t,r={}){let i=(0,nm.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=bo(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==tr&&a!==rr)throw No(n,Zh,"Native children contract"),new Error(`Native children schema must be ${tr} or ${rr}`);let o=a===tr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(No(n,o==="indexed-v2"?cx:Zh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let l=n.children.map((f,h)=>{let m=bo(f,`Native child ${h}`);if(No(m,o==="indexed-v2"?dx:o==="summary-v2"?ux:lx,`Native ${s} child fields (child ${h})`),typeof m.name!="string"||!sx.test(m.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:p?m.summary:null,depends_on:em(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?em(m.covers,`Native child ${m.name} covers`):[]}}),c=l.map(({name:f})=>f);if(new Set(c).size!==c.length)throw new Error("Native child names must be unique");let u=new Set(c);for(let f of l){let h=f.depends_on.filter(m=>!u.has(m));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}fx(l);let d=r.policy==="advisory";if(a===ql){if(o==="indexed-v2"){let f=px(n.acceptance_index);d||hx(f,t,r);let h=Object.keys(f);return d||tm(l,h,h),{schema:rr,acceptance_index:f,children:l}}return{schema:rr,children:l}}return t&&!d&&tm(l,t),{schema:tr,children:l}}async function nr(e){let t=ox.join(e.changeDir,Vl);try{await ax.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await T({root:e.changeDir,ref:Vl}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=om(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?am(a,e.acceptanceIds,e.validation??{}):null}}var nm,Vl,tr,rr,ql,sx,Zh,cx,lx,ux,dx,ko=S(()=>{"use strict";nm=mt(Ze(),1);fe();Vl="children.yaml",tr="comet.native.children.v1",rr="comet.native.children.v2",ql=rr,sx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Zh=new Set(["schema","children"]),cx=new Set(["schema","acceptance_index","children"]),lx=new Set(["name","depends_on","covers"]),ux=new Set(["name","summary","depends_on"]),dx=new Set(["name","depends_on","covers"])});var Tt=S(()=>{"use strict";L();J();ko();H();$t()});var Wl=S(()=>{"use strict"});var ar=S(()=>{"use strict"});var So=S(()=>{"use strict";Ia();Wl();ar()});var sm=S(()=>{"use strict";ct();So();J()});var zl=S(()=>{"use strict";ct();L()});var pm,Mr=S(()=>{"use strict";J();Gi();pm=1024*1024});var Co=S(()=>{"use strict";J();ar();Xr();Mr()});var mm,Bx,Mx,Fx,lH,Vx,uH,Jl=S(()=>{"use strict";J();mm="scoped-text-safety",Bx=1,Mx=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Fx="comet.native.checker-policy.v1",lH=O(Fx,{policy:mm,version:Bx,limits:Mx,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Vx=["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"],uH=new Set(Vx)});var Po=S(()=>{"use strict";J();Jl();ar()});import{createHash as wm}from"node:crypto";import{promises as se}from"node:fs";import Ye from"node:path";function Ul(e,t){let r=Ye.relative(e,t);return r===""||!Ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ye.sep}`)}function Wx(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function rn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Se(r,i)?j(r,i):j(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function vm(e){let t=await se.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await se.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zx(e,t){let r=Ye.resolve(e),i=Ye.resolve(t);if(!Ul(r,i))throw new Error("Native evidence path is outside its change");let n=[await vm(r)],a=r;for(let o of Ye.relative(r,i).split(Ye.sep).filter(Boolean)){a=Ye.join(a,o);let s=await vm(a);if(!Ul(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function gm(e){for(let t of e){let r=await se.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Wx(t,r)||await se.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function Gx(e,t,r={}){let i=await zx(t,Ye.dirname(e));await r.afterParentChainCaptured?.();let n=await se.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await se.realpath(e);if(!Ul(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await se.open(e,"r");try{let[s,l,c]=await Promise.all([o.stat(),se.lstat(e),se.realpath(e)]);if(await gm(i),!s.isFile()||!l.isFile()||l.isSymbolicLink()||c!==a||!rn(s,n)||!rn(s,l))throw new Error("Native evidence document changed while opening");if(s.size>dt)throw new Error(`Native evidence document exceeds ${dt} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=dt+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>dt)throw new Error(`Native evidence document exceeds ${dt} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),se.lstat(e),se.realpath(e)]);if(await gm(i),!m.isFile()||m.isSymbolicLink()||p!==a||!rn(s,h)||!rn(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Ro(e,t){if(!ym.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function Yl(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>dt||wm("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ux({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Nm(e){let t=Xl(e.paths,e.name,"reports",e.hash),r=ce(e.paths,t);await I(r,t);let i=await se.lstat(t);if(await Jx(e.paths,e.name,e.hash),await I(r,t),!rn(i,await se.lstat(t)))throw new Error("Native report evidence changed before rollback");await se.unlink(t)}async function Jx(e,t,r,i,n){if(!ym.test(r))throw new Error("Native report evidence hash is invalid");let a=await Kl({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||wm("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Xl(e,t,r,i,n){let a=Ro(r,i);return n?Ye.join(n,...a.split("/")):Kc(Ae(e,t),a)}async function Kl(e){let t=Xl(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??ce(e.paths,t);return await I(r,t),Gx(t,r,e.hooks)}async function Ux(e){Kx(e.value);let t=Xl(e.paths,e.name,e.kind,e.hash),r=ce(e.paths,t);await I(r,t);try{let n=await Kl(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Ro(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await Q(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Kl(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Ro(e.kind,e.hash)}function Kx(e){if(Yx(e)>dt)throw new Error(`Native evidence document exceeds ${dt} bytes`)}function Yx(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
178
|
-
`,"utf8")}var ym,dt,AH,Fr=S(()=>{"use strict";L();H();Le();Mr();Co();Po();ym=/^[a-f0-9]{64}$/u,dt=pm,AH=3*dt});Jr();$t();function Z(e,t,r){return e.language==="zh-CN"?r:t}function gv(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:Z(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:Z(e,"Reply A or B","回复 A 或 B"),agentInstruction:Z(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(Z(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(Z(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:Z(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:Z(e,"Accept the result","接受结果"),agentInstruction:Z(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:l})=>l==="blocked")??!1,a=r?.children.some(({status:l})=>l==="needs-reverify")??!1,o=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,s=r?.children.some(({status:l,builderFailureCount:c})=>l==="blocked"&&(c??0)>=un)??!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(Z(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(Z(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 wv(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 yv(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:Z(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Z(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function yu(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ot(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function vu(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function Nv(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function gu(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function bv(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function kv(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 vt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:yu({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ot("summary","--summary"),Nv(e.name,e.flag)]}}function wu(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:Z(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function Sv(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function dn(e){return[vt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),vt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Ev(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 fn(e,t,r={}){let i=bv(t)&&e.coordination_mode===void 0,n=gv(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:[Ot("summary","--summary")],commandAlternatives:[vt({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:[Ot("summary","--summary")],commandAlternatives:[vt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...dn({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:[Ot("summary","--summary")],commandAlternatives:[vt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),vt({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:[Ot("summary","--summary")],commandAlternatives:[vt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...dn({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:[Ot("summary","--summary")],commandAlternatives:dn({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:dn({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:l})=>l==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?yu({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:kv({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?[gu("coordination-mode","--coordination-mode",mu)]:[]],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:[vu()],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 l=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),c=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)>=un)??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:Z(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},h=l&&!c&&!u&&f===null;return{...a,disposition:h?"blocked":"continue",action:"advance-children",commandArgs:h?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:h?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:h?[]:f!==null?[f]:[Ot("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",l=!!e.children_contract_hash,c=vu();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&&l?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Z(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:Ev([{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:[c]}},{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]})):l?[c]:[]}}]),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",c=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=wu(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>Sv(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:wu(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return c?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[gu("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...yv(e)],userCommunication:wv(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[vt({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 nv}from"node:fs";import uP from"node:path";import{randomUUID as fC}from"node:crypto";import{promises as nn}from"node:fs";import pC from"node:path";import{execFileSync as xv}from"child_process";import Cv from"fs";import qo from"path";function pn(e,t){return xv("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Wo(e,t){return Nu(e)===Nu(t)}function Nu(e){let t=qo.resolve(e);try{let r=Cv.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ke(e){try{let t=qo.resolve(pn(e,["rev-parse","--show-toplevel"])),i=pn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?qo.resolve(i.slice(9)):t,a=null;try{a=pn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Wo(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function bu(e){try{return pn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}L();fe();var Ol=mt(Ze(),1);import Ki from"path";fe();L();Vt();he();K();H();Ge();Gi();K();H();Er();_t();var EE=mt(Ze(),1);Er();_t();It();It();Sr();zc();Er();It();var nT=4*1024*1024;var xE=null;function CE(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Oh(e,t){return(...r)=>{let i=xE;if(i===null)return t(...r);let n=CE(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}Sr();var lT=Oh("hookWritePolicy",async e=>(await Fc(e))?.hook??{allow_paths:[]});Ti();var PE=16*1024;Vc();Kr();var dj=Number.MAX_SAFE_INTEGER;L();Le();var Ej={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 jr from"node:path";L();fe();K();H();var Ji=/^[a-f0-9]{64}$/u,Dh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,$E=16*1024,Bj=process.platform;function OE(e,t){let r=jr.relative(e,t);return jr.isAbsolute(r)||r===".."||r.startsWith(`..${jr.sep}`)?null:r.replaceAll("\\","/")||"."}function Bh(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Mh(e,t){if(e.length===0||Bh(e)||e.includes("\\")||jr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=jr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function HE(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function $l(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Bh(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function DE(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if($l(e.changeBranch,"Native workspace change branch"),$l(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function LE(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Dh.test(t.baseCommit)||typeof t.targetCommit!="string"||!Dh.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");$l(t.targetBranch,"Native workspace Git target branch")}function BE(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Ji.test(String(t.projectRootId))||!Ji.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");HE(t.capturedAt),Mh(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Ji.test(String(t.projectRootPathId))||a&&!Ji.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ji.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&LE(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(DE(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function ME(e,t){return jr.join(Ae(e,t),"workspace.json")}function FE(e,t){let r=ME(e,t),i=ce(e,r),n=OE(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Mh(n,"Native workspace file ref")}}async function VE(e,t){try{let r=FE(e,t),i=await T({root:r.root,ref:r.ref,maxBytes:$E});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ui(e,t){let r=await VE(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(BE(r),r)}Bi();Wa();Wa();var mo=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"},Yi=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"},vo=class extends Error{constructor(r,i,n,a,o,s=null,l=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=l;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},p$=va("en");function Ue(e,t){qi(t);let r=Ki.join(e.changesDir,t);if(!X(e.changesDir,r))throw new Error("Native change path escaped");return r}async function zE(e,t=Ki.dirname(e)){let r=Ki.relative(t,e).split(Ki.sep).join("/"),i=await T({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Ol.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Vh(e,t){let r=Ki.join(Ue(e,t),nt);await I(e.nativeRoot,r);let i=vl(await zE(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}K();El();ao();Ka();import{promises as Gh}from"node:fs";import wo from"node:path";ct();L();Jr();import{promises as GE}from"node:fs";import JE from"node:os";import Zi from"node:path";function Xi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qi(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 ie(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 $r(e,t){return e===null?null:ie(e,t)}function Or(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 UE(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 KE(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Hr(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Hl(e,t){if(e===null)return null;let r=ie(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function YE(e,t){let r=ie(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Dl(e,t){let r=ie(e,t);if(!Zi.isAbsolute(r))throw new Error(`${t} must be absolute`);return Zi.resolve(r)}function XE(e,t){let r=`Native local checks[${t}]`,i=Xi(e,r);if(Qi(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)=>ie(u,`${r}.argv[${d}]`,!0)),a=Hr(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Hl(i.startedAt,`${r}.startedAt`),s=Hl(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 l=Or(i.timeoutMs,`${r}.timeoutMs`);if(l<1)throw new Error(`${r}.timeoutMs must be positive`);let c;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)c=null;else{let u=Xi(i.activeProcess,`${r}.activeProcess`),d=Hr(u.status,["starting","running"],`${r}.activeProcess.status`);if(Qi(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`);c={status:"starting"}}else c={status:"running",pid:Or(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:ie(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:ie(i.id,`${r}.id`),name:ie(i.name,`${r}.name`),operationId:ie(i.operationId,`${r}.operationId`),status:a,repeatable:KE(i.repeatable,`${r}.repeatable`),timeoutMs:l,executionCount:Or(i.executionCount,`${r}.executionCount`),argv:n,cwd:Dl(i.cwd,`${r}.cwd`),exitCode:UE(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:ie(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:c}:{},...Object.hasOwn(i,"evidence")?{evidence:Hr(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:ie(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function Wh(e){let t="Native local execution state",r=Xi(e,t);if(Qi(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Gr)throw new Error(`Native local execution schema must be ${Gr}`);let i=Xi(r.workspace,"Native local workspace");Qi(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Xi(r.execution,"Native local execution");Qi(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Hl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:ie(o.operationId,"Native local execution.operationId"),stage:Hr(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Hr(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:$r(o.executionId,"Native local execution.executionId"),status:Hr(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Or(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:YE(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Or(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:ie(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(XE);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:Gr,change:ie(r.change,"Native local change"),basedOnStateVersion:Or(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:$r(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:$r(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:$r(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:$r(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Dl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Dl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:$r(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:ie(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function He(e){return Wh({schema:Gr,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:Zi.resolve(e.projectRoot),worktreeRoot:Zi.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:JE.hostname()},execution:null,checks:[]})}async function De(e,t,r={}){let i=Wh(t);await GE.mkdir(Zi.dirname(e),{recursive:!0}),await Q(e,i,r)}ot();H();var en=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Jh="comet-state.yaml",Uh="state.json";function le(e,t){if(!en.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=wo.join(e.changesDir,t);if(!X(e.changesDir,r))throw new Error("Native change path escaped");return r}function Ke(e,t){return wo.join(le(e,t),Jh)}function ye(e,t){return wo.join(_e(e,t),Uh)}async function er(e,t){try{let r=await Gh.readFile(Ke(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function lt(e){return bu(e)}async function Ne(e,t){return at(Ke(e,t))}async function ut(e){let t=await yh({file:Ke(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=wo.join(le(e.paths,t.name),"verification.md");await I(e.paths.nativeRoot,r),await Gh.rm(r,{force:!0})}return t}L();import{createHash as sC}from"node:crypto";import{promises as Vr}from"node:fs";import ft from"node:path";Vt();fe();Je();H();var Yh=["outcome","scope","nonGoals","acceptanceExamples"],Kh=[...Yh,"constraints","decisions","openQuestions","verificationExpectations"];var ex=new Set(["nonGoals","decisions","openQuestions"]),tx={maxFileBytes:Zo};function rx(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
179
|
-
`).
|
|
180
|
-
`)
|
|
187
|
+
`,o),c=l===-1?a.slice(o):a.slice(o,l);if(yield{line:c,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=vm(c,t);else if(r)gm(c)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(c)&&(i=null);else{let d=vm(c,null);if(d!==null)t=d;else{let f=c.trimStart();if(f.startsWith("<!--")&&!gm(f))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);m&&n.has(m[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(f)&&(i=m[1])}}}if(l===-1)break;o=l+1}}function gn(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function ym(e,t,r,i=[],n="content-hash"){let a=gn(r),o=t.replaceAll("\\","/").trim(),s=i.map(gn);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${D($E,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function bm(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function jE(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Co(e)){n=s+1;let l=o?wm(a):null;l?.level===1&&(Ya(l.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function iu(e,t="brief.md",r=Po.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=jE(e);if(n===null)return[];let a=null;for(let{line:c,body:u,index:d}of Co(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(f===null)continue;let m=f[1].length;a=a===null?m:Math.min(a,m)}let o=[],s=null,l=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:c,body:u,index:d}of Co(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;f&&f[1].length===a?(l(),s=[f[2]]):s!==null&&s.push(c)}return l(),bm(o.map(c=>ym("brief-example",t,c.join(`
|
|
188
|
+
`),[],i)),"Brief",i)}function nu(e,t="spec.md",r=Po.maxCriteria,i="content-hash",n={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let a=[],o=[],s=null,l=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let c=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(c.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(c.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...ym("spec-scenario",t,[s.title,...s.body].join(`
|
|
189
|
+
`),s.context,i),...c[0]===void 0?{}:{briefAcceptanceRef:c[0]}}),s=null};for(let{line:c,body:u}of Co(e)){let d=u?wm(c):null,f=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(f){for(l();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let m=gn(f[1]);if(m.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:m,body:[],context:o.map(h=>h.text)}}else if(d){for(s!==null&&d.level<=s.level?l():s!==null&&s.body.push(c);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(c)}return l(),bm(a,"Specification",i)}var $E,_$,Po,Ro=S(()=>{"use strict";er();K();$E="comet.native.acceptance.v1",_$=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Po=Object.freeze({maxCriteria:1024})});import Nm from"node:path";function km(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Nm.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Nm.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function HE(e,t){return e.localeCompare(t,"en")}function _o(e){let t=km(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((o,s)=>HE(o.capability,s.capability));if(new Set(r.map(o=>o.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=iu(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:o,text:s})=>({source:o,text:s})),n=i.length;for(let o of r){let s=km(o.source,`Native spec source for ${o.capability}`);for(let l of nu(o.markdown,s,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(l.briefAcceptanceRef!==void 0){let c=Number(l.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(c)||c<0||c>=n)throw new Error(`Native Spec references unknown brief acceptance ${l.briefAcceptanceRef}: ${s}`);continue}i.push({source:s,text:l.text})}}let a=new Set;for(let o of i){o.text=gn(o.text);let s=o.text;if(a.has(s))throw new Error(`Native acceptance contains a duplicate criterion: ${o.text}`);a.add(s)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((o,s)=>({id:`A${s+1}`,source:o.source,text:o.text}))}function Sm(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!OE.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function au(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var OE,Ao=S(()=>{"use strict";Ro();OE=/^A[1-9]\d*$/u});function ou(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function su(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let i=t,n=`Native Builder acceptance_review[${r}]`;Rs(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:ou(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>ou(o,`${n}.evidence`)),note:ou(i.note,`${n}.note`)}})}function cu(e,t){if(!t)throw new Yr(e.map(({id:l})=>l),[]);let r=new Set(e.map(({id:l})=>l)),i=t.map(({id:l})=>l),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(l=>!r.has(l));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:l})=>!n.has(l)).map(({id:l})=>l),s=t.filter(l=>l.status!=="implemented-with-evidence"||l.evidence.length===0).map(({id:l})=>l);if(o.length||s.length)throw new Yr(o,s)}var Yr,Io=S(()=>{"use strict";Bn();Yr=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 DE}from"node:fs";function ne(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ae(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 X(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 uu(e,t){return e===null?null:X(e,t)}function du(e,t){let r=X(e,t);if(!FE.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Xr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function M(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 VE(e,t){return e===null?null:M(e,t,Number.MIN_SAFE_INTEGER)}function W(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function et(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ho(e,t){return et(e,t,(r,i)=>X(r,`${t}[${i}]`))}function cr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Qr(e,t){let r=X(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function jo(e,t,r=!1){let i=X(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 Se(e,t){let r=ne(e,t);return ae(r,new Set(["text","truncated"]),t),{text:X(r.text,`${t}.text`,{empty:!0}),truncated:Xr(r.truncated,`${t}.truncated`)}}function WE(e,t){let r=`Native spec_changes[${t}]`,i=ne(e,r);ae(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=X(i.capability,`${r}.capability`);if(!BE.test(n))throw new Error(`${r}.capability is invalid`);let a=W(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:jo(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:jo(i.delta_source,`${r}.delta_source`),l=i.base_hash===void 0?void 0:i.base_hash===null?null:du(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&&l==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(l!==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},...l===void 0?{}:{base_hash:l}}}function zE(e){let t="Native workspace",r=ne(e,t);ae(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=W(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=uu(r.change_branch,`${t}.change_branch`),a=uu(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:W(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 GE(e){let t="Native loop",r=ne(e,t);ae(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=Ho(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);cr(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:W(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:W(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:M(r.goal_cycle,`${t}.goal_cycle`,1),iteration:M(r.iteration,`${t}.iteration`),attempt:M(r.attempt,`${t}.attempt`),retry_epoch:M(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:M(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:M(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:M(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:uu(r.next_action,`${t}.next_action`)}}function JE(e,t){let r=`Native acceptance[${t}]`,i=ne(e,r);ae(i,new Set(["id","source","text","result","reason"]),r);let n=X(i.id,`${r}.id`);if(!ME.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:jo(i.source,`${r}.source`),text:X(i.text,`${r}.text`),result:W(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Se(i.reason,`${r}.reason`)}}function UE(e,t){let r=`Native builder_handoff.checks[${t}]`,i=ne(e,r);return ae(i,new Set(["name","result","note"]),r),{name:Se(i.name,`${r}.name`),result:W(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Se(i.note,`${r}.note`)}}function KE(e){let t="Native builder_handoff",r=ne(e,t);ae(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Ho(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);cr(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:ne(r.review,`${t}.review`);return n&&ae(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:X(r.candidate_id,`${t}.candidate_id`),identity_provider:X(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:X(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:M(r.iteration,`${t}.iteration`,1),summary:Se(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:su(r.acceptance_review)},checks:et(r.checks,`${t}.checks`,UE),checks_truncated:Xr(r.checks_truncated,`${t}.checks_truncated`),known_limits:et(r.known_limits,`${t}.known_limits`,(a,o)=>Se(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Xr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:W(n.status,["passed"],`${t}.review.status`),summary:Se(n.summary,`${t}.review.summary`),reviewer_execution_ref:X(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Qr(r.submitted_at,`${t}.submitted_at`)}}function YE(e,t){let r=`Native blockers[${t}]`,i=ne(e,r);ae(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ho(i.acceptance_ids,`${r}.acceptance_ids`);return cr(n,`${r}.acceptance_ids`),{owner:W(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Se(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:W(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function XE(e,t){let r=`Native verification.checks[${t}]`,i=ne(e,r);return ae(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:X(i.id,`${r}.id`),name:Se(i.name,`${r}.name`),argv_display:et(i.argv_display,`${r}.argv_display`,(n,a)=>Se(n,`${r}.argv_display[${a}]`)),argv_truncated:Xr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:jo(i.cwd_ref,`${r}.cwd_ref`,!0),status:W(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:VE(i.exit_code,`${r}.exit_code`),duration_ms:M(i.duration_ms,`${r}.duration_ms`)}}function QE(e){let t="Native verification",r=ne(e,t);ae(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=et(r.checks,`${t}.checks`,XE);cr(i.map(a=>a.id),`${t}.checks IDs`);let n=X(r.identity_provider,`${t}.identity_provider`);return{candidate_id:X(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:X(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:M(r.iteration,`${t}.iteration`,1),attempt:M(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":W(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:W(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Se(r.summary,`${t}.summary`),risks:et(r.risks,`${t}.risks`,(a,o)=>Se(a,`${t}.risks[${o}]`)),risks_truncated:Xr(r.risks_truncated,`${t}.risks_truncated`),completed_at:Qr(r.completed_at,`${t}.completed_at`)}}function Em(e,t){let r=`Native history[${t}]`,i=ne(e,r);ae(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ho(i.unresolved_ids,`${r}.unresolved_ids`);return cr(n,`${r}.unresolved_ids`),{goal_cycle:M(i.goal_cycle,`${r}.goal_cycle`,1),iteration:M(i.iteration,`${r}.iteration`),attempt:M(i.attempt,`${r}.attempt`),outcome:W(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Se(i.summary,`${r}.summary`),completed_at:Qr(i.completed_at,`${r}.completed_at`)}}function ZE(e){let t="Native history_overflow.outcome_counts",r=ne(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ae(r,new Set(i),t),{pass:M(r.pass,`${t}.pass`),fail:M(r.fail,`${t}.fail`),blocked:M(r.blocked,`${t}.blocked`),"execution-error":M(r["execution-error"],`${t}.execution-error`),recovery:M(r.recovery,`${t}.recovery`)}}function ex(e){let t="Native history_overflow",r=ne(e,t);ae(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=M(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Qr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Qr(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=ZE(r.outcome_counts);if(Object.values(o).reduce((l,c)=>l+c,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 tx(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&cu(e.acceptance,e.builder_handoff.acceptance_review);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 rx(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 Ee(e){let t=ne(e,"Native portable state");if(ae(t,qE,"Native portable state"),t.schema!==Er)throw new Error(`Native portable state schema must be ${Er}`);let r=X(t.name,"Native state name");if(!LE.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=et(t.spec_changes,"Native spec_changes",WE);cr(i.map(s=>s.capability),"Native spec change capabilities");let n=et(t.acceptance,"Native acceptance",JE);cr(n.map(s=>s.id),"Native acceptance IDs");let a=et(t.history,"Native history",Em);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Er,name:r,language:W(t.language,["en","zh-CN"],"Native state language"),phase:W(t.phase,["shape","build","verify","archive"],"Native state phase"),status:W(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:M(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1 or 2")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:du(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:du(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:W(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:zE(t.workspace),loop:GE(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:KE(t.builder_handoff),blockers:et(t.blockers,"Native blockers",YE),verification:t.verification===null?null:QE(t.verification),history:a,history_overflow:ex(t.history_overflow),verification_result:W(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:W(t.verification_report,["verification.md"],"Native verification_report"),archived:Xr(t.archived,"Native archived"),created_at:Qr(t.created_at,"Native created_at")};return tx(o),rx(o),o}function lr(e,t){let r=Ee(e),i=Em(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return Ee({...r,history:n,history_overflow:a})}function ix(e,t){let r=(0,Oo.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 vt(e){let t=await DE.readFile(e,"utf8");return Ee(ix(t,"Native portable state"))}async function Do(e,t,r={}){let i=Ee(t);await ve(e,(0,Oo.stringify)(i),r)}async function nx(e,t){let r=To.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);To.set(e,a),await r;try{return await t()}finally{i(),To.get(e)===a&&To.delete(e)}}async function xm(e){return nx(e.file,async()=>{let t=M(e.expectedStateVersion,"Native expected state version",1),r=Ee(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await vt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new $o(t,i.state_version);return await Do(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await vt(e.file);if(n.state_version!==t)throw new $o(t,n.state_version)}}),r})}var Oo,LE,BE,ME,FE,qE,$o,To,gt=S(()=>{"use strict";Io();Oo=Ct(ut(),1);B();hi();LE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ME=/^A[1-9][0-9]*$/u,FE=/^[a-f0-9]{64}$/u,qE=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"]),$o=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};To=new Map});function ax(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Be(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(ax(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var ur=S(()=>{"use strict"});import ox from"node:path";function fx(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function px(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function hx(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 mx(e){return e.schema===Qe?Ur(e):e.schema===Xe?Kr(e):sr(e)}function vx(e){return ox.posix.normalize(e.replaceAll("\\","/"))}function gx(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:vx(t.source)})}function wx(e){return e==="shape"?"shape":"build"}function yx(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function bx(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function Cm(e){let t=mx(e.state);Sm(e.acceptance);let r=wx(t.phase),i=r==="shape"?0:1,n=px(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return Ee({schema:Er,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:gx(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:yx(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:Be(bx(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:xs(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function fu(e){let t=fx(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!sx.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Lo)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!lx.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!cx.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!dx.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!ux.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Lo,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:hx(t.createdAt,"Native portable migration transaction createdAt")}}function Pm(e){switch(fu(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Lo,sx,cx,lx,ux,dx,pu=S(()=>{"use strict";xo();Ao();gt();ur();hi();fn();Lo="comet.native.portable-migration.v1",sx=new Set(["schema","id","change","fromSchema","status","createdAt"]),cx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lx=/^[a-z0-9][a-z0-9-]{7,127}$/u,ux=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),dx=new Set([Qe,Xe,Ye])});import mu from"node:path";function Tm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $m(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 hu(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 _m(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function Rx(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Tm(e,r);if($m(i,Px,r),typeof i.capability!="string"||!Im.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=hu(i.base_hash,`${r}.base_hash`),s=_m(i.delta_content,`${r}.delta_content`),l=_m(i.source_content,`${r}.source_content`),c=hu(i.expected_target_hash,`${r}.expected_target_hash`),u=hu(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||l===void 0||l===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||l!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=dn(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(pt(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(pt(l)!==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||l!==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},...c===void 0?{}:{expected_target_hash:c}}}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||pt(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},...l===void 0?{}:{source_content:l},...c===void 0?{}:{expected_target_hash:c},...u===void 0?{}:{result_hash:u}}}function _x(e){let t=Tm(e,"Native portable Archive transaction");if($m(t,Cx,"Native portable Archive transaction"),t.schema!==Rm)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Sx.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Im.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"||!Ex.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"||!xx.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(Rx);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:Rm,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 Bo(e){let t=Nx.exec(e);if(t)return{kind:"archive",change:t[1]};let r=kx.exec(e);return r?{kind:"migration",change:r[1]}:null}function Mo(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Bo(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return mu.join(e.transactionsDir,r)}async function vu(e,t){let r=Bo(t);if(!r)return null;let i=await $({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=mu.join(e.transactionsDir,t);if(r.kind==="archive"){let s=_x(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=fu(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}}async function gu(e,t){let r=Mo(e,t);try{return await vu(e,mu.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function jm(e){return e.kind==="archive"||e.journal.status!=="committed"}var Rm,Am,Nx,kx,Sx,Ex,xx,Cx,Px,Im,Fo=S(()=>{"use strict";we();Ql();pu();Rm="comet.native.archive-transaction.v4",Am="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Nx=new RegExp(`^portable-archive-(${Am})\\.json$`,"u"),kx=new RegExp(`^portable-migration-(${Am})\\.json$`,"u"),Sx=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ex=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xx=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Cx=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Px=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Im=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as Ax}from"node:crypto";import{constants as qo,promises as Me}from"node:fs";import Fe from"node:path";function Wo(e,t){let r=Fe.relative(e,t);return r===""||!Fe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Fe.sep}`)}function Ix(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Tx(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function $x(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Vo(e,t){return j({...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 wu(e,t){let r=await Me.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Me.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function jx(e,t,r){let i=Fe.resolve(e),n=Fe.resolve(t);if(!Wo(i,n))throw new Error(`${r} is outside its managed root`);let a=[await wu(i,r)],o=i;for(let s of Fe.relative(i,n).split(Fe.sep).filter(Boolean)){await dr(a,r),o=Fe.join(o,s);let l=await wu(o,r);if(!Wo(a[0].realPath,l.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(l)}return await dr(a,r),a}async function dr(e,t){for(let r of e){let i=await Me.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Tx(r,i)||await Me.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Ox(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 wn(e){let t=e.maxBytes===null?null:Ix(e.maxBytes),r=Fe.resolve(e.file),i=await jx(e.root,Fe.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>wu(Fe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await dr(i,e.label);let a=await Me.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=$x(a),s=await Me.realpath(r);if(!Wo(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Wo(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let l=process.platform==="win32"?qo.O_RDONLY:qo.O_RDONLY|qo.O_NOFOLLOW|qo.O_NONBLOCK,c=await Me.open(r,l);try{let u=await c.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Me.lstat(r),Me.realpath(r)]);if(await dr(i,e.label),await dr(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Vo(o,u)||!Vo(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await Ox(c,t,e.label);await e.hooks?.beforeFinalCheck?.();let[h,p,v]=await Promise.all([c.stat(),Me.lstat(r),Me.realpath(r)]);if(await dr(i,e.label),await dr(n,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Vo(o,h)||!Vo(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:Ax("sha256").update(m).digest("hex"),size:m.length}}finally{await c.close()}}var tt=S(()=>{"use strict";B();Ge()});import wt from"path";import{TextDecoder as Dx}from"util";function Go(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jo(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 Lm(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function yu(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 zo(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Om(e,t){if(yu(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 Vx(e,t){let r=Go(e,`transaction operations[${t}]`);if(Jo(r,Bx,`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`);yu(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&yu(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 Bm(e){let t=Go(e,"Native Archive transaction journal");if(Jo(t,Mx,"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"||!Dm.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(!Lm(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(zo(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,l)=>{let c=Go(s,`Archive transaction operations[${l}]`);if(Jo(c,Fx,`Archive transaction operations[${l}]`),typeof c.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(c.id))throw new Error(`Archive transaction operations[${l}].id is invalid`);if(c.type!=="write"&&c.type!=="remove"&&c.type!=="move")throw new Error(`Archive transaction operation ${c.id} has an invalid type`);Om(c.target,`Archive transaction operation ${c.id} target`);for(let u of["source","staged","backup"])c[u]!==void 0&&Om(c[u],`Archive transaction operation ${c.id} ${u}`);if(c.expectedTargetHash!==null&&zo(c.expectedTargetHash,`Archive transaction operation ${c.id} expectedTargetHash`),c.type==="write"){if(c.staged===void 0||c.source!==void 0||c.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${c.id} requires staged and forbids source`);if(zo(c.stagedHash,`Archive write operation ${c.id} stagedHash`),c.expectedTargetHash===null!=(c.backup===void 0))throw new Error(`Archive write operation ${c.id} backup must match target existence`)}else if(c.type==="remove"){if(c.source!==void 0||c.staged!==void 0||c.stagedHash!==void 0||c.expectedSourceHash!==void 0||c.backup===void 0||c.expectedTargetHash===null)throw new Error(`Archive remove operation ${c.id} requires a bound target and backup`)}else{if(c.source===void 0||c.staged!==void 0||c.stagedHash!==void 0||c.backup!==void 0||c.expectedTargetHash!==null)throw new Error(`Archive move operation ${c.id} requires source and an absent target`);zo(c.expectedSourceHash,`Archive move operation ${c.id} expectedSourceHash`)}return c}),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 Wx(e){let t=Go(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bm(t);if(Jo(t,Lx,"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"||!Dm.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(!Lm(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(Vx),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 zx(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 Mm(e,t){let r=zx(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 Nu(e,t){let r=Mm(e,t);return await Promise.all(Object.values(r).map(i=>T(e.runtimeDir,i))),r}async function ku(e,t,r={}){let i=await Nu(e,t),n=await wn({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(qx.decode(n.bytes)),o=Wx(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var Lx,Bx,Mx,Fx,Dm,qx,Uo=S(()=>{"use strict";B();L();tt();Lx=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Bx=new Set(["id","type","source","target","staged","backup"]),Mx=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Fx=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Dm=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),qx=new Dx("utf-8",{fatal:!0})});import{promises as Gx}from"fs";import Jx from"path";async function Ux(e,t,r){let i;try{i=await Gx.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 ku(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(Bo(n.name))try{let a=await vu(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(jm(a))return!0}catch{return!0}return!1}async function Kx(e,t){let r=Date.now()+5e3,i=Jx.join(e.locksDir,"root-move.lock");for(;;)try{return await bo(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Qh(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Zh(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 F(e,t,r,i){let n=await Kx(e,t);try{if(await fo(e.projectRoot),await Ux(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await No(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
|
|
190
|
+
`)}}}var Q=S(()=>{"use strict";be();un();Fo();Uo()});import{createHash as Yx}from"crypto";function xe(e){return Yx("sha256").update(e).digest("hex")}var rt=S(()=>{"use strict"});var Hj,Dj,Lj,Bj,Mj,Fj,yn=S(()=>{"use strict";xr();B();be();rt();Ge();L();tt();Si();Hj={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Dj=64*1024,Lj=64*1024,Bj={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Mj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024},Fj=(1n<<256n)-1n});var gH,nt=S(()=>{"use strict";xr();gH=8*1024*1024});import{promises as DP}from"node:fs";import LP from"node:path";function ss(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function os(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Nv(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function WP(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function kv(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(l=>!i.has(l));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Cv(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Wu&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=o.filter(c=>!a.includes(c));let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of o){let u=s.get(c),d=e.acceptance_index[c];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(c)}let l=new Set(o);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(u=>!l.has(u)));return i.uncovered=o.filter(c=>!Sv(e.children,c)),Ev(i)?i:null}if(e.schema===vr&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!Sv(e.children,a)),Ev(i)?i:null}return null}function Sv(e,t){return e.some(r=>r.covers.includes(t))}function Ev(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function wr(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function zP(e){let t=ss(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=ss(n,`Native children acceptance_index.${i}`);if(os(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function GP(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(c=>!(c in e)),s=a.filter(c=>!n.includes(c));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let l=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of a){let u=l.get(c);if(!u)continue;let d=e[c];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(m=>d[m]!==u[m]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function Pv(e,t,r={}){let i=(0,xv.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ss(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==vr&&a!==gr)throw os(n,bv,"Native children contract"),new Error(`Native children schema must be ${vr} or ${gr}`);let o=a===vr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(os(n,o==="indexed-v2"?MP:bv,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let l=n.children.map((f,m)=>{let h=ss(f,`Native child ${m}`);if(os(h,o==="indexed-v2"?VP:o==="summary-v2"?qP:FP,`Native ${s} child fields (child ${m})`),typeof h.name!="string"||!BP.test(h.name))throw new Error(`Native child ${m} name is invalid`);let p=o==="summary-v2";if(p){if(typeof h.summary!="string"||h.summary.trim().length===0)throw new Error(`Native child ${h.name} summary must be a non-empty string`);if(h.summary.length>2e3)throw new Error(`Native child ${h.name} summary exceeds 2000 characters`)}return{name:h.name,summary:p?h.summary:null,depends_on:Nv(h.depends_on,`Native child ${h.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Nv(h.covers,`Native child ${h.name} covers`):[]}}),c=l.map(({name:f})=>f);if(new Set(c).size!==c.length)throw new Error("Native child names must be unique");let u=new Set(c);for(let f of l){let m=f.depends_on.filter(h=>!u.has(h));if(m.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${m.join(", ")}`)}WP(l);let d=r.policy==="advisory";if(a===Wu){if(o==="indexed-v2"){let f=zP(n.acceptance_index);d||GP(f,t,r);let m=Object.keys(f);return d||kv(l,m,m),{schema:gr,acceptance_index:f,children:l}}return{schema:gr,children:l}}return t&&!d&&kv(l,t),{schema:vr,children:l}}async function yr(e){let t=LP.join(e.changeDir,Vu);try{await DP.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await $({root:e.changeDir,ref:Vu}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Pv(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Cv(a,e.acceptanceIds,e.validation??{}):null}}var xv,Vu,vr,gr,Wu,BP,bv,MP,FP,qP,VP,cs=S(()=>{"use strict";xv=Ct(ut(),1);we();Vu="children.yaml",vr="comet.native.children.v1",gr="comet.native.children.v2",Wu=gr,BP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bv=new Set(["schema","children"]),MP=new Set(["schema","acceptance_index","children"]),FP=new Set(["name","depends_on","covers"]),qP=new Set(["name","summary","depends_on"]),VP=new Set(["name","depends_on","covers"])});var Vt=S(()=>{"use strict";B();K();cs();L();zt()});var zu=S(()=>{"use strict"});var br=S(()=>{"use strict"});var ls=S(()=>{"use strict";wi();zu();br()});var Rv=S(()=>{"use strict";nt();ls();K()});var Gu=S(()=>{"use strict";nt();B()});var jv,si=S(()=>{"use strict";K();yn();jv=1024*1024});var fs=S(()=>{"use strict";K();br();Si();si()});var Hv,gR,wR,yR,bB,bR,NB,Uu=S(()=>{"use strict";K();Hv="scoped-text-safety",gR=1,wR=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),yR="comet.native.checker-policy.v1",bB=D(yR,{policy:Hv,version:gR,limits:wR,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),bR=["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"],NB=new Set(bR)});var ps=S(()=>{"use strict";K();Uu();br()});import{createHash as Bv}from"node:crypto";import{promises as de}from"node:fs";import st from"node:path";function Ku(e,t){let r=st.relative(e,t);return r===""||!st.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${st.sep}`)}function kR(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function jn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ae(r,i)?j(r,i):j(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Dv(e){let t=await de.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await de.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function SR(e,t){let r=st.resolve(e),i=st.resolve(t);if(!Ku(r,i))throw new Error("Native evidence path is outside its change");let n=[await Dv(r)],a=r;for(let o of st.relative(r,i).split(st.sep).filter(Boolean)){a=st.join(a,o);let s=await Dv(a);if(!Ku(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Lv(e){for(let t of e){let r=await de.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!kR(t,r)||await de.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function ER(e,t,r={}){let i=await SR(t,st.dirname(e));await r.afterParentChainCaptured?.();let n=await de.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await de.realpath(e);if(!Ku(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await de.open(e,"r");try{let[s,l,c]=await Promise.all([o.stat(),de.lstat(e),de.realpath(e)]);if(await Lv(i),!s.isFile()||!l.isFile()||l.isSymbolicLink()||c!==a||!jn(s,n)||!jn(s,l))throw new Error("Native evidence document changed while opening");if(s.size>kt)throw new Error(`Native evidence document exceeds ${kt} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=kt+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>kt)throw new Error(`Native evidence document exceeds ${kt} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[m,h,p]=await Promise.all([o.stat(),de.lstat(e),de.realpath(e)]);if(await Lv(i),!h.isFile()||h.isSymbolicLink()||p!==a||!jn(s,m)||!jn(s,h))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function hs(e,t){if(!Mv.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function Xu(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>kt||Bv("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return CR({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Fv(e){let t=Qu(e.paths,e.name,"reports",e.hash),r=fe(e.paths,t);await T(r,t);let i=await de.lstat(t);if(await xR(e.paths,e.name,e.hash),await T(r,t),!jn(i,await de.lstat(t)))throw new Error("Native report evidence changed before rollback");await de.unlink(t)}async function xR(e,t,r,i,n){if(!Mv.test(r))throw new Error("Native report evidence hash is invalid");let a=await Yu({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||Bv("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Qu(e,t,r,i,n){let a=hs(r,i);return n?st.join(n,...a.split("/")):Hl(De(e,t),a)}async function Yu(e){let t=Qu(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??fe(e.paths,t);return await T(r,t),ER(t,r,e.hooks)}async function CR(e){PR(e.value);let t=Qu(e.paths,e.name,e.kind,e.hash),r=fe(e.paths,t);await T(r,t);try{let n=await Yu(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return hs(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await Z(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Yu(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return hs(e.kind,e.hash)}function PR(e){if(RR(e)>kt)throw new Error(`Native evidence document exceeds ${kt} bytes`)}function RR(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
191
|
+
`,"utf8")}var Mv,kt,FB,ci=S(()=>{"use strict";B();L();Ge();si();fs();ps();Mv=/^[a-f0-9]{64}$/u,kt=jv,FB=3*kt});hi();zt();function Y(e,t,r){return e.language==="zh-CN"?r:t}function Bg(e,t,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:Y(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Y(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Y(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(Y(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(Y(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"){let a=i==="confirmed"?Y(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Y(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return n(`${a} ${Y(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",l=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:l,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:Y(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:Y(e,"Accept the result","接受结果"),agentInstruction:Y(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:c})=>c==="blocked")??!1,o=r?.children.some(({status:c})=>c==="needs-reverify")??!1,s=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,l=r?.children.some(({status:c,builderFailureCount:u})=>c==="blocked"&&(u??0)>=Fn)??!1;return a&&!o&&!s&&!l?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."}:n(Y(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(Y(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 Mg(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function Fg(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",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",i,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:Y(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Y(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function bd(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Gt(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function gd(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function qg(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function wd(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function Vg(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function Wg(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function ze(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:bd({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Gt("summary","--summary"),qg(e.name,e.flag)]}}function yd(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:Y(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function zg(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function qn(e){return[ze({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),ze({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Gg(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 Vn(e,t,r={}){let i=Vg(t)&&e.coordination_mode===void 0,n=Bg(e,i,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision: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",...i?["coordination-choice"]:[]],inputOptions:[Gt("summary","--summary")],commandAlternatives:i?vd.map(s=>{let l=ze({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...l,commandArgs:[...l.commandArgs,"--coordination-mode",s],requiredInputs:[...l.requiredInputs,"coordination-choice"],inputOptions:[...l.inputOptions,wd("coordination-mode","--coordination-mode",[s])]}}):[ze({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:[Gt("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let l=ze({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...l,commandArgs:[...l.commandArgs,"--finish",s]}}):[],ze({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...qn({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:[Gt("summary","--summary")],commandAlternatives:[ze({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),ze({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:[Gt("summary","--summary")],commandAlternatives:[ze({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...qn({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:[Gt("summary","--summary")],commandAlternatives:qn({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:qn({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:l})=>l==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?bd({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:Wg({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:h})=>h),acceptance_review:e.acceptance.map(({id:h})=>({id:h,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[gd()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:h})=>h==="verified");if(s){let h=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}],...h&&h.length>0?{retry_check_ids:[...h]}:{}}}],runnerAction:o("none")}}let l=t.children.some(({status:h})=>h==="blocked"||h==="needs-reverify"),c=t.children.some(({status:h})=>h==="needs-reverify"),u=t.children.some(({status:h})=>h==="ready"||h==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(h=>h.status==="blocked"&&(h.builderFailureCount??0)>=Fn)??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:Y(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},m=l&&!c&&!u&&f===null;return{...a,disposition:m?"blocked":"continue",action:"advance-children",commandArgs:m?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:m?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:m?[]:f!==null?[f]:[Gt("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let l=e.builder_handoff?.acceptance_review?.find(c=>c.id===s);return l?{...l,evidence:[...l.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",l=!!e.children_contract_hash,c=gd();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&&l?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Y(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:Gg([{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:[c]}},{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]})):l?[c]:[]}}]),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",c=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=yd(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>zg(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:yd(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return c?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[wd("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Fg(e)],userCommunication:Mg(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[ze({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 Cg}from"node:fs";import q_ from"node:path";import{randomUUID as WR}from"node:crypto";import{promises as On}from"node:fs";import zR from"node:path";xr();Jn();import{execFileSync as aw}from"child_process";import ow from"fs";import Jt from"path";import{AsyncLocalStorage as Ed}from"node:async_hooks";wi();var Cr=new Ed,sw=new Ed;function xd(e){return Cr.getStore()?e():Cr.run(new Map,e)}function cw(e){let t=Cr.getStore();for(let r of e)t?.set(Pr(r.root),e);return e}function Un(e,t){return zn(()=>aw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function bi(e,t){return Pr(e)===Pr(t)}function Pr(e){let t=Jt.resolve(e);try{let r=ow.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function _e(e){try{let t=sw.getStore()?.get(Pr(e)),r=Cr.getStore()?.get(t??Pr(e));if(r){let l=Sd(t??e,r);if(l)return l;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Jt.resolve(Un(e,["rev-parse","--show-toplevel"])),n=Cr.getStore()?.get(Pr(i))??lw(e),a=Sd(i,n);if(Cr.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Un(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!bi(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function lw(e){let t=uw(Un(e,["worktree","list","--porcelain","-z"]));return cw(t),t.map(r=>({...r}))}function uw(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Jt.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 Sd(e,t){let r=t.find(a=>bi(Jt.resolve(a.root),Jt.resolve(e)));if(!r)return null;let i=Jt.resolve(t[0].root),n=Jt.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!bi(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Cd(e){try{return Un(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}B();we();var Eu=Ct(ut(),1);import kn from"path";we();B();er();be();Q();L();tt();yn();Q();L();Vr();Mt();var iC=Ct(ut(),1);Vr();Mt();ft();ft();qr();Tl();Vr();ft();var i0=4*1024*1024;import{AsyncLocalStorage as nC}from"node:async_hooks";var aC=new nC;function oC(){let e=aC.getStore();return e?.active?e:null}function sC(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Fm(e,t){return(...r)=>{let i=oC();if(i===null)return t(...r);let n=sC(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}qr();var l0=Fm("hookWritePolicy",async e=>(await Rl(e))?.hook??{allow_paths:[]});an();var cC=16*1024;_l();Ni();var dO=Number.MAX_SAFE_INTEGER;B();Ge();var EO={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 Zr from"node:path";B();we();Q();L();var bn=/^[a-f0-9]{64}$/u,Vm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,mC=16*1024,BO=process.platform;function vC(e,t){let r=Zr.relative(e,t);return Zr.isAbsolute(r)||r===".."||r.startsWith(`..${Zr.sep}`)?null:r.replaceAll("\\","/")||"."}function zm(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Gm(e,t){if(e.length===0||zm(e)||e.includes("\\")||Zr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Zr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function gC(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Su(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||zm(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function wC(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Su(e.changeBranch,"Native workspace change branch"),Su(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function yC(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Vm.test(t.baseCommit)||typeof t.targetCommit!="string"||!Vm.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Su(t.targetBranch,"Native workspace Git target branch")}function bC(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!bn.test(String(t.projectRootId))||!bn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");gC(t.capturedAt),Gm(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!bn.test(String(t.projectRootPathId))||a&&!bn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!bn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&yC(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(wC(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function NC(e,t){return Zr.join(De(e,t),"workspace.json")}function kC(e,t){let r=NC(e,t),i=fe(e,r),n=vC(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Gm(n,"Native workspace file ref")}}async function SC(e,t){try{let r=kC(e,t),i=await $({root:r.root,ref:r.ref,maxBytes:mC});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Nn(e,t){let r=await SC(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(bC(r),r)}fn();xo();xo();var Yo=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"},Sn=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"},Xo=class extends Error{constructor(r,i,n,a,o,s=null,l=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=l;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},pH=Xa("en");function it(e,t){vn(t);let r=kn.join(e.changesDir,t);if(!te(e.changesDir,r))throw new Error("Native change path escaped");return r}async function CC(e,t=kn.dirname(e)){let r=kn.relative(t,e).split(kn.sep).join("/"),i=await $({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Eu.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Um(e,t){let r=kn.join(it(e,t),mt);await T(e.nativeRoot,r);let i=ru(await CC(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}Q();pu();Fo();Ao();import{promises as Xm}from"node:fs";import Zo from"node:path";nt();B();hi();import{promises as PC}from"node:fs";import RC from"node:os";import Cn from"node:path";function En(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xn(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 oe(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 ei(e,t){return e===null?null:oe(e,t)}function ti(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 _C(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 AC(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ri(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function xu(e,t){if(e===null)return null;let r=oe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function IC(e,t){let r=oe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Cu(e,t){let r=oe(e,t);if(!Cn.isAbsolute(r))throw new Error(`${t} must be absolute`);return Cn.resolve(r)}function TC(e,t){let r=`Native local checks[${t}]`,i=En(e,r);if(xn(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)=>oe(u,`${r}.argv[${d}]`,!0)),a=ri(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 l=ti(i.timeoutMs,`${r}.timeoutMs`);if(l<1)throw new Error(`${r}.timeoutMs must be positive`);let c;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)c=null;else{let u=En(i.activeProcess,`${r}.activeProcess`),d=ri(u.status,["starting","running"],`${r}.activeProcess.status`);if(xn(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`);c={status:"starting"}}else c={status:"running",pid:ti(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:oe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:oe(i.id,`${r}.id`),name:oe(i.name,`${r}.name`),operationId:oe(i.operationId,`${r}.operationId`),status:a,repeatable:AC(i.repeatable,`${r}.repeatable`),timeoutMs:l,executionCount:ti(i.executionCount,`${r}.executionCount`),argv:n,cwd:Cu(i.cwd,`${r}.cwd`),exitCode:_C(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:oe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:c}:{},...Object.hasOwn(i,"evidence")?{evidence:ri(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:oe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function Km(e){let t="Native local execution state",r=En(e,t);if(xn(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==pi)throw new Error(`Native local execution schema must be ${pi}`);let i=En(r.workspace,"Native local workspace");xn(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=En(r.execution,"Native local execution");xn(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:oe(o.operationId,"Native local execution.operationId"),stage:ri(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ri(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ei(o.executionId,"Native local execution.executionId"),status:ri(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ti(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:IC(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:ti(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:oe(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(TC);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:pi,change:oe(r.change,"Native local change"),basedOnStateVersion:ti(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:ei(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:ei(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:ei(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:ei(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Cu(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Cu(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ei(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:oe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function qe(e){return Km({schema:pi,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:Cn.resolve(e.projectRoot),worktreeRoot:Cn.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:RC.hostname()},execution:null,checks:[]})}async function Ve(e,t,r={}){let i=Km(t);await PC.mkdir(Cn.dirname(e),{recursive:!0}),await Z(e,i,r)}gt();L();var Pn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Qm="comet-state.yaml",Zm="state.json";function he(e,t){if(!Pn.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Zo.join(e.changesDir,t);if(!te(e.changesDir,r))throw new Error("Native change path escaped");return r}function at(e,t){return Zo.join(he(e,t),Qm)}function Ce(e,t){return Zo.join(He(e,t),Zm)}async function fr(e,t){try{let r=await Xm.readFile(at(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function yt(e){return Cd(e)}async function Pe(e,t){return vt(at(e,t))}async function bt(e){let t=await xm({file:at(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=Zo.join(he(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,r),await Xm.rm(r,{force:!0})}return t}import{createHash as BR}from"node:crypto";import{promises as li}from"node:fs";import St from"node:path";function Au(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var mr=Au();function sv(e){mr=e}var pr={exec:()=>null};function ii(e){let t=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=t[i];return n||(n=e(i),t[i]=n),n}}function P(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(re.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var jC=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),re={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:ii(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:ii(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:ii(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:ii(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:ii(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:ii(e=>new RegExp(`^ {0,${e}}>`))},OC=/^(?:[ \t]*(?:\n|$))+/,HC=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,DC=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,An=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,LC=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Iu=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,cv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lv=P(cv).replace(/bull/g,Iu).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(),BC=P(cv).replace(/bull/g,Iu).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(),Tu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,MC=/^[^\n]+/,$u=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,FC=P(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",$u).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),qC=P(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Iu).getRegex(),ns="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ju=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,VC=P("^ {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",ju).replace("tag",ns).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),uv=e=>P(Tu).replace("hr",An).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ns).getRegex(),WC=uv(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),zC=uv(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),GC=P(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",zC).getRegex(),Ou={blockquote:GC,code:HC,def:FC,fences:DC,heading:LC,hr:An,html:VC,lheading:lv,list:qC,newline:OC,paragraph:WC,table:pr,text:MC},ev=P("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",An).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ns).getRegex(),JC={...Ou,lheading:BC,table:ev,paragraph:P(Tu).replace("hr",An).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ev).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ns).getRegex()},UC={...Ou,html:P(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ju).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:pr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:P(Tu).replace("hr",An).replace("heading",` *#{1,6} *[^
|
|
192
|
+
]`).replace("lheading",lv).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},KC=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,YC=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,dv=/^( {2,}|\\)\n(?!\s*$)/,XC=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Nt=/[\p{P}\p{S}]/u,ni=/[\s\p{P}\p{S}]/u,In=/[^\s\p{P}\p{S}]/u,QC=P(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ni).getRegex(),ZC=/[\p{Pi}\p{Ps}"']/u,fv=/(?!~)[\p{P}\p{S}]/u,eP=/(?!~)[\s\p{P}\p{S}]/u,tP=/(?:[^\s\p{P}\p{S}]|~)/u,rP=P(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",jC?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),pv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,iP=P(pv,"u").replace(/punct/g,Nt).getRegex(),nP=P(pv,"u").replace(/punct/g,fv).getRegex(),aP=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,oP=P(aP,"u").replace(/openQuote/g,ZC).replace(/punct/g,Nt).getRegex(),hv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",sP=P(hv,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,ni).replace(/punct/g,Nt).getRegex(),cP=P(hv,"gu").replace(/notPunctSpace/g,tP).replace(/punctSpace/g,eP).replace(/punct/g,fv).getRegex(),lP="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",uP=P(lP,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,ni).replace(/punct/g,Nt).getRegex(),dP=P("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,ni).replace(/punct/g,Nt).getRegex(),fP="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",pP=P(fP,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,ni).replace(/punct/g,Nt).getRegex(),hP=P(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Nt).getRegex(),mP="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",vP=P(mP,"gu").replace(/notPunctSpace/g,In).replace(/punctSpace/g,ni).replace(/punct/g,Nt).getRegex(),gP=P(/\\(punct)/,"gu").replace(/punct/g,Nt).getRegex(),wP=P(/^<(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(),yP=P(ju).replace("(?:-->|$)","-->").getRegex(),bP=P("^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",yP).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ts=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,NP=P(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ts).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),mv=P(/^!?\[(label)\]\[(ref)\]/).replace("label",ts).replace("ref",$u).getRegex(),vv=P(/^!?\[(ref)\](?:\[\])?/).replace("ref",$u).getRegex(),kP=P("reflink|nolink(?!\\()","g").replace("reflink",mv).replace("nolink",vv).getRegex(),tv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Hu={_backpedal:pr,anyPunctuation:gP,autolink:wP,blockSkip:rP,br:dv,code:YC,del:pr,delLDelim:pr,delRDelim:pr,emStrongLDelim:iP,emStrongRDelimAst:sP,emStrongRDelimUnd:dP,escape:KC,link:NP,nolink:vv,punctuation:QC,reflink:mv,reflinkSearch:kP,tag:bP,text:XC,url:pr},SP={...Hu,emStrongLDelim:oP,emStrongRDelimAst:uP,emStrongRDelimUnd:pP,link:P(/^!?\[(label)\]\((.*?)\)/).replace("label",ts).getRegex(),reflink:P(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ts).getRegex()},Pu={...Hu,emStrongRDelimAst:cP,emStrongLDelim:nP,delLDelim:hP,delRDelim:vP,url:P(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",tv).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:P(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",tv).getRegex()},EP={...Pu,br:P(dv).replace("{2,}","*").getRegex(),text:P(Pu.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},es={normal:Ou,gfm:JC,pedantic:UC},Rn={normal:Hu,gfm:Pu,breaks:EP,pedantic:SP},xP={"&":"&","<":"<",">":">",'"':""","'":"'"},rv=e=>xP[e];function ot(e,t){if(t){if(re.escapeTest.test(e))return e.replace(re.escapeReplace,rv)}else if(re.escapeTestNoEncode.test(e))return e.replace(re.escapeReplaceNoEncode,rv);return e}function iv(e){try{e=encodeURI(e).replace(re.percentDecode,"%")}catch{return null}return e}function nv(e,t){let r=e.replace(re.findPipe,(a,o,s)=>{let l=!1,c=o;for(;--c>=0&&s[c]==="\\";)l=!l;return l?"|":" |"}),i=r.split(re.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(re.slashPipe,"|");return i}function qt(e,t,r){let i=e.length;if(i===0)return"";let n=0;for(;n<i;){let a=e.charAt(i-n-1);if(a===t&&!r)n++;else if(a!==t&&r)n++;else break}return e.slice(0,i-n)}function av(e){let t=e.split(`
|
|
193
|
+
`),r=t.length-1;for(;r>=0&&re.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
194
|
+
`)}function CP(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])r++;else if(e[i]===t[1]&&(r--,r<0))return i;return r>0?-2:-1}function PP(e,t=0){let r=t,i="";for(let n of e)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function ov(e,t,r,i,n){let a=t.href,o=t.title||null,s=e[1].replace(n.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!";i.state.inLink=!0;let c=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),f=i.state.linkEmitted;if(i.state.linkEmitted=c,i.state.inLink=!1,!l){if(f){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:l?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function RP(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
|
|
195
|
+
`).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(`
|
|
196
|
+
`)}var rs=class{options;rules;lexer;constructor(e){this.options=e||mr}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:av(t[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],i=RP(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let i=qt(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:qt(t[0],`
|
|
197
|
+
`),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:qt(t[0],`
|
|
198
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=qt(t[0],`
|
|
181
199
|
`).split(`
|
|
182
|
-
`);for(;
|
|
200
|
+
`),i="",n="",a=[];for(;r.length>0;){let o=!1,s=[],l;for(l=0;l<r.length;l++)if(this.rules.other.blockquoteStart.test(r[l]))s.push(r[l]),o=!0;else if(!o)s.push(r[l]);else break;r=r.slice(l);let c=s.join(`
|
|
201
|
+
`),u=c.replace(this.rules.other.blockquoteSetextReplace,`
|
|
202
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
203
|
+
${c}`:c,n=n?`${n}
|
|
204
|
+
${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=d,r.length===0)break;let f=a.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let m=f,h=r.join(`
|
|
205
|
+
`),p=m.raw+`
|
|
206
|
+
`+h.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(p);a[a.length-1]=v,i=`${i}
|
|
207
|
+
${h}`,n=n.substring(0,n.length-m.text.length)+v.text;break}else if(f?.type==="list"){let m=f,h=m.raw+`
|
|
208
|
+
`+r.join(`
|
|
209
|
+
`),p=this.list(h);a[a.length-1]=p,i=i.substring(0,i.length-f.raw.length)+p.raw,n=n.substring(0,n.length-m.raw.length)+p.raw,r=h.substring(a.at(-1).raw.length).split(`
|
|
210
|
+
`);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[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(;e;){let l=!1,c="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let d=PP(t[2].split(`
|
|
211
|
+
`,1)[0],t[1].length),f=e.split(`
|
|
212
|
+
`,1)[0],m=!d.trim(),h=0;if(this.options.pedantic?(h=2,u=d.trimStart()):m?h=t[1].length+1:(h=d.search(this.rules.other.nonSpaceChar),h=h>4?1:h,u=d.slice(h),h+=t[1].length),m&&this.rules.other.blankLine.test(f)&&(c+=f+`
|
|
213
|
+
`,e=e.substring(f.length+1),l=!0),!l){let p=this.rules.other.nextBulletRegex(h),v=this.rules.other.hrRegex(h),g=this.rules.other.fencesBeginRegex(h),w=this.rules.other.headingBeginRegex(h),b=this.rules.other.htmlBeginRegex(h),k=this.rules.other.blockquoteBeginRegex(h);for(;e;){let x=e.split(`
|
|
214
|
+
`,1)[0],E;if(f=x,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),E=f):E=f.replace(this.rules.other.tabCharGlobal," "),g.test(f)||w.test(f)||b.test(f)||k.test(f)||p.test(f)||v.test(f))break;if(E.search(this.rules.other.nonSpaceChar)>=h||!f.trim())u+=`
|
|
215
|
+
`+E.slice(h);else{if(m||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(d)||w.test(d)||v.test(d))break;u+=`
|
|
216
|
+
`+f}m=!f.trim(),c+=x+`
|
|
217
|
+
`,e=e.substring(x.length+1),d=E.slice(h)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=c}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 l of n.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!n.loose){let c=l.tokens.filter(d=>d.type==="space"),u=c.length>0&&c.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let l of n.items){let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.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(l.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=d.checked,n.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}else l.task&&(l.task=!1)}if(n.loose)for(let l of n.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=av(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:qt(t[0],`
|
|
218
|
+
`),href:i,title:n}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=nv(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
219
|
+
`):[],a={type:"table",raw:qt(t[0],`
|
|
220
|
+
`),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(nv(o,a.header.length).map((s,l)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[l]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:qt(t[0],`
|
|
221
|
+
`),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
|
|
222
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=qt(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=CP(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let i=t[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=t[3]?t[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)),ov(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return ov(r,n,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let i=this.rules.inline.emStrongLDelim.exec(e);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,l=0,c=i[0][0],u=r===c,d=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+n);(i=d.exec(t))!==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)){l+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+l);let f=[...i[0]][0].length,m=e.slice(0,n+i.index+f+o);if(Math.min(n,o)%2){let p=m.slice(1,-1);return{type:"em",raw:m,text:p,tokens:this.lexer.inlineTokens(p)}}let h=m.slice(2,-2);return{type:"strong",raw:m,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[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:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+n);(i=l.exec(t))!==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 c=[...i[0]][0].length,u=e.slice(0,n+i.index+c+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,i;return t[2]==="@"?(r=t[1],i="mailto:"+r):(r=t[1],i=r),{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let n;do n=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(n!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},me=class Ru{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||mr,this.options.tokenizer=this.options.tokenizer||new rs,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:re,block:es.normal,inline:Rn.normal};this.options.pedantic?(r.block=es.pedantic,r.inline=Rn.pedantic):this.options.gfm&&(r.block=es.gfm,this.options.breaks?r.inline=Rn.breaks:r.inline=Rn.gfm),this.tokenizer.rules=r}static get rules(){return{block:es,inline:Rn}}static lex(t,r){return new Ru(r).lex(t)}static lexInline(t,r){return new Ru(r).inlineTokens(t)}lex(t){t=t.replace(re.carriageReturn,`
|
|
223
|
+
`),this.blockTokens(t,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(t,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(re.tabCharGlobal," ").replace(re.spaceLine,""));let n=1/0;for(;t;){if(t.length<n)n=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},t,r))?(t=t.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
|
|
224
|
+
`:r.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
225
|
+
`)?"":`
|
|
226
|
+
`)+a.raw,s.text+=`
|
|
227
|
+
`+a.text,this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
228
|
+
`)?"":`
|
|
229
|
+
`)+a.raw,s.text+=`
|
|
230
|
+
`+a.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},r.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),r.push(a);continue}let o=t;if(this.options.extensions?.startBlock){let s=1/0,l=t.slice(1),c;this.options.extensions.startBlock.forEach(u=>{c=u.call({lexer:this},l),typeof c=="number"&&c>=0&&(s=Math.min(s,c))}),s<1/0&&s>=0&&(o=t.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);i&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
|
|
231
|
+
`)?"":`
|
|
232
|
+
`)+a.raw,s.text+=`
|
|
233
|
+
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),i=o.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
|
|
234
|
+
`)?"":`
|
|
235
|
+
`)+a.raw,s.text+=`
|
|
236
|
+
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&t.charAt(i.index-1)!=="!")return!0;for(let i of t.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(t,r=[]){this.tokenizer.lexer=this;let i=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,l=c=>{let u=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(u+1,-1)))return c;if(u>1&&c.charAt(0)!=="!"){let d=c.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,l)+"]["+"a".repeat(c.length-u-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};i=i.replace(s,l)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,l,c)=>{let u=c?c.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(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(c=>(s=c.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let c=r.at(-1);s.type==="text"&&c?.type==="text"?(c.raw+=s.raw,c.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let l=t;if(this.options.extensions?.startInline){let c=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(f=>{d=f.call({lexer:this},u),typeof d=="number"&&d>=0&&(c=Math.min(c,d))}),c<1/0&&c>=0&&(l=t.substring(0,c+1))}if(s=this.tokenizer.inlineText(l)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let c=r.at(-1);c?.type==="text"?(c.raw+=s.raw,c.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},is=class{options;parser;constructor(e){this.options=e||mr}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(re.notSpaceStart)?.[0],n=e.replace(re.endingNewline,"")+`
|
|
237
|
+
`;return i?'<pre><code class="language-'+ot(i)+'">'+(r?n:ot(n,!0))+`</code></pre>
|
|
238
|
+
`:"<pre><code>"+(r?n:ot(n,!0))+`</code></pre>
|
|
239
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
240
|
+
${this.parser.parse(e)}</blockquote>
|
|
241
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
242
|
+
`}hr(e){return`<hr>
|
|
243
|
+
`}list(e){let t=e.ordered,r=e.start,i="";for(let o=0;o<e.items.length;o++){let s=e.items[o];i+=this.listitem(s)}let n=t?"ol":"ul",a=t&&r!==1?' start="'+r+'"':"";return"<"+n+a+`>
|
|
244
|
+
`+i+"</"+n+`>
|
|
245
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
246
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
247
|
+
`}table(e){let t="",r="";for(let n=0;n<e.header.length;n++)r+=this.tablecell(e.header[n]);t+=this.tablerow({text:r});let i="";for(let n=0;n<e.rows.length;n++){let a=e.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>
|
|
248
|
+
<thead>
|
|
249
|
+
`+t+`</thead>
|
|
250
|
+
`+i+`</table>
|
|
251
|
+
`}tablerow({text:e}){return`<tr>
|
|
252
|
+
${e}</tr>
|
|
253
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
254
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${ot(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let i=this.parser.parseInline(r),n=iv(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+ot(t)+'"'),a+=">"+i+"</a>",a}image({href:e,title:t,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=iv(e);if(n===null)return ot(r);e=n;let a=`<img src="${e}" alt="${ot(r)}"`;return t&&(a+=` title="${ot(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:ot(e.text)}},Du=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},We=class _u{options;renderer;textRenderer;constructor(t){this.options=t||mr,this.options.renderer=this.options.renderer||new is,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Du}static parse(t,r){return new _u(r).parse(t)}static parseInline(t,r){return new _u(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let n=t[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(t,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<t.length;n++){let a=t[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(e){this.options=e||mr}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?me.lex:me.lexInline}provideParser(e=this.block){return e?We.parse:We.parseInline}},_P=class{defaults=Au();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=We;Renderer=is;TextRenderer=Du;Lexer=me;Tokenizer=rs;Hooks=_n;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let i of e)switch(r=r.concat(t.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,t));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,t));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,t))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.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=t.renderers[n.name];a?t.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:t.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=t[n.level];a?a.unshift(n.tokenizer):t[n.level]=[n.tokenizer],n.start&&(n.level==="block"?t.startBlock?t.startBlock.push(n.start):t.startBlock=[n.start]:n.level==="inline"&&(t.startInline?t.startInline.push(n.start):t.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(t.childTokens[n.name]=n.childTokens)}),i.extensions=t),r.renderer){let n=this.defaults.renderer||new is(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],l=n[o];n[o]=(...c)=>{let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new rs(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],l=n[o];n[o]=(...c)=>{let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),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],l=n[o];_n.passThroughHooks.has(a)?n[o]=c=>{if(this.defaults.async&&_n.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,c);return l.call(n,d)})();let u=s.call(n,c);return l.call(n,u)}:n[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,c);return d===!1&&(d=await l.apply(n,c)),d})();let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),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(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return me.lex(e,t??this.defaults)}parser(e,t){return We.parse(e,t??this.defaults)}parseMarkdown(e){return(t,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 t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=e),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(t):t,s=await(n.hooks?await n.hooks.provideLexer(e):e?me.lex:me.lexInline)(o,n),l=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(l,n.walkTokens));let c=await(n.hooks?await n.hooks.provideParser(e):e?We.parse:We.parseInline)(l,n);return n.hooks?await n.hooks.postprocess(c):c})().catch(a);try{n.hooks&&(t=n.hooks.preprocess(t));let o=(n.hooks?n.hooks.provideLexer(e):e?me.lex:me.lexInline)(t,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(e):e?We.parse:We.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(e,t){return r=>{if(r.message+=`
|
|
255
|
+
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+ot(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},hr=new _P;function O(e,t){return hr.parse(e,t)}O.options=O.setOptions=function(e){return hr.setOptions(e),O.defaults=hr.defaults,sv(O.defaults),O};O.getDefaults=Au;O.defaults=mr;function AP(...e){return hr.use(...e),O.defaults=hr.defaults,sv(O.defaults),O}O.use=AP;O.walkTokens=function(e,t){return hr.walkTokens(e,t)};O.parseInline=hr.parseInline;O.Parser=We;O.parser=We.parse;O.Renderer=is;O.TextRenderer=Du;O.Lexer=me;O.lexer=me.lex;O.Tokenizer=rs;O.Hooks=_n;O.parse=O;var $H=O.options,jH=O.setOptions,OH=O.walkTokens,HH=O.parseInline;var DH=We.parse,LH=me.lex;B();er();we();rt();L();var Lu=["outcome","scope","nonGoals","acceptanceExamples"],gv=[...Lu,"constraints","decisions","openQuestions","verificationExpectations"];var TP=new Set(["nonGoals","decisions","openQuestions"]),Tn=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},$P={maxFileBytes:Ms};function jP(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
256
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}function Bu(e){return{valid:e.length===0,findings:e}}function Mu(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function OP(e){return Mu(e).trim()}function as(e){let t=OP(e).split(/\r?\n/u),r=[],i=!1;for(let n of t){if(/^\s*(?:```|~~~)/u.test(n)){i=!i;continue}!i&&/^\s*#{1,6}\s*$/u.test(n)||!i&&/^\s*#{1,6}\s+/u.test(n)||!i&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n)}return r.join(`
|
|
257
|
+
`).trim()}function HP(e){let t=as(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function wv(e){let t=as(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function yv(e,t){let r=[];return as(e).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${t}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:t}):wv(e)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${t}. Replace it with complete target requirements.`,path:t}),Bu(r)}function Fu(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function qu(e,t,r={}){let i=[],n;try{n=(await $({root:e,ref:t,maxBytes:$P.maxFileBytes})).text}catch(s){return Bu([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,l]of jP(n))a.set(Ya(s)??s,l);for(let s of r.compact?Lu:gv)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?gv.filter(s=>!r.compact||a.has(s)):Lu;for(let s of o){let l=a.get(s)??"";as(l).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):wv(l)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!TP.has(s)&&HP(l)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return Fu(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Bu(i)}we();K();var dR=Ct(ut(),1);nt();we();K();be();L();gt();cs();cs();zt();Vt();nt();vo();B();K();ls();Q();L();Rv();zt();Vt();Gu();nt();be();Gu();un();L();var us=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};nt();be();Q();zt();Vt();function Ju(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}Io();gt();ur();vi();Mn();function $v(e){return e.state_version+1}function pR(e){return e.map(t=>({...t,result:"pending",reason:null}))}function hR(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:Be(e.summary),completed_at:e.completedAt}}function ds(e){let t=Ee(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=lr(t,hR({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),l=s.size===0?pR(t.acceptance):t.acceptance.map(c=>s.has(c.id)?{...c,result:"pending",reason:null}:c);return n?Ee({...o,phase:"verify",status:"await-user",state_version:$v(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:Be(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):Ee({...o,phase:"build",status:"active",state_version:$v(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:l,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}Q();Ao();Ql();gt();ur();B();er();vi();L();er();ci();be();var ed=Ct(ut(),1);ft();var VB=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(" "));var qv=5,_R=600,KB=256*1024,AR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IR=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var TR=/^[a-f0-9]{64}$/iu;function Vv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wt(e,t,r=4096){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string within the association limit`);return e}function Zu(e,t){let r=Wt(e,t).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a project-relative path`);return r}function $R(e,t){let r=Wt(e,t,64).toLowerCase();if(!TR.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function jR(e,t){let r=`Capability association evidence[${t}]`,i=Vv(e,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:Zu(i.source,`${r}.source`),kind:Wt(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:Wt(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:Wt(i.snippet,`${r}.snippet`,_R)}}}function Wv(e){let t=typeof e=="string"?(()=>{if(e.length>65536)throw new Error("Capability association exceeds the size limit");let c=(0,ed.parseDocument)(e,{uniqueKeys:!0});if(c.errors.length>0)throw new Error(c.errors[0].message);return c.toJS({mapAsMap:!1})})():e,r=Vv(t,"Capability association"),i=Object.keys(r).filter(c=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(c));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=OR(Wt(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((c,u)=>Zu(c,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>qv)throw new Error(`Capability association evidence must contain at most ${qv} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let l=r.confidence;if(l!=="high"&&l!=="medium"&&l!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:Zu(r.current_spec,"Capability association current_spec"),current_hash:$R(r.current_hash,"Capability association current_hash"),confidence:l,...r.query===void 0?{}:{query:Wt(r.query,"Capability association query")},reason:Wt(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(jR)}}function OR(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=t==="native"?AR:IR;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return i.join("/")}gt();ur();Vt();var MR=Xa("en",{compact:!0}),td="capability-association.yaml";function ms(e,t=!1){if(t){let i=n=>{if(Array.isArray(n))return n.filter(a=>a?.type!=="space").map(i);if(n&&typeof n=="object"){let a=n;return Object.fromEntries(Object.entries(a).filter(([o])=>o!=="raw"&&!(o==="text"&&Array.isArray(a.tokens))).map(([o,s])=>[o,o==="text"&&a.type==="text"&&typeof s=="string"?s.replace(/[\t ]*\n[\t ]*/gu," "):i(s)]))}return n};return JSON.stringify(i(me.lex(e.replace(/\r\n?/gu,`
|
|
258
|
+
`))))}let r=e.replace(/\r\n?/gu,`
|
|
259
|
+
`).split(`
|
|
260
|
+
`);for(;r.length>0&&r.at(-1)?.trim().length===0;)r.pop();return`${r.map(i=>i.replace(/[\t ]+$/gu,"")).join(`
|
|
183
261
|
`)}
|
|
184
|
-
`}function lC(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function uC(e){let t=[],r=!1;for(let i of Bl(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!lC(n[1]??"")})}async function xm(e){let t=le(e.paths,e.state.name),r=[...(await Fl(t,e.state.brief,{strict:!0})).findings],i="";try{i=(await T({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:c})=>c!=="remove"),o=e.state.spec_changes.filter(({operation:c})=>c!=="remove"),s=new Set(a.map(({capability:c})=>c));if(e.specChanges!==void 0)for(let c of o)s.has(c.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${c.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${c.capability}/spec.md`});let l=n.length>0&&n.every(({operation:c})=>c==="remove");a.length===0&&o.length===0&&!l&&!uC(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let c of a){let u=`specs/${c.capability}/spec.md`;if(c.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:c.source??u});continue}try{let d=(await T({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...Qh(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}function Ao(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Cm(e){let t=le(e.paths,e.state.name),r=ft.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Vr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,l)=>s.name.localeCompare(l.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!en.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,l=ft.join(t,...s.split("/")),c=await Vr.lstat(l);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=ft.join(e.paths.specsDir,o.name,"spec.md"),d="create",f=null;try{let v=await Vr.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",f=rt((await T({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let h=`specs/${o.name}/${Xp}`,m=ft.join(t,...h.split("/")),p={};try{let v=await Vr.lstat(m);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${h}`);let g=await T({root:t,ref:h,maxBytes:null,includeHash:!1}),w=Li(g.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let N=f??rt(""),k=e.state.spec_changes.find(E=>E.capability===o.name);if(k?.delta_source!==void 0){if(k.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==N)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);p={delta_source:h,base_hash:w.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:d,source:s,...p})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function ru(e){let t=le(e.paths,e.state.name),r=await T({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Ml(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await T({root:t,ref:o.source,maxBytes:null,includeHash:!1}),l=s.text,c=null;if(o.delta_source){let u=await T({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=Li(u.text);l=th(s.text,d);let f="";try{f=(await T({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(h){if(h.code!=="ENOENT")throw h}if(rt(f)===d.base_hash){let h=ih({baselineMarkdown:f,delta:d,allowAlreadyApplied:!0});if(rt(s.text)!==h.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}c=O("comet.native.shape-artifact-content.v1",_o(u.text))}i.push({capability:o.capability,source:s.ref,markdown:l}),n.push({...o,contentHash:O("comet.native.shape-artifact-content.v1",_o(s.text)),...c===null?{}:{deltaContentHash:c}})}let a=null;try{let o=await T({root:t,ref:eu,maxBytes:65536,includeHash:!1}),s=Sm(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let c=ft.relative(e.paths.projectRoot,ft.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(ft.sep,"/");if(s.current_spec!==c)throw new Error(`Native capability association points to ${s.current_spec}, expected ${c}`);a=O("comet.native.shape-artifact-content.v1",_o(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:Ua({briefMarkdown:r.text,specs:i}),formalHash:O("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:O("comet.native.shape-artifact-content.v1",_o(r.text))},specs:n,association:{source:eu,contentHash:a}})}}function iu(e){return O("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Pm(e){if(e.state.document_constraints_version===1){let c=await xm(e);if(!c.valid){let u=c.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Cm(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&c.delta_source===d.delta_source&&c.base_hash===d.base_hash&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await ru({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:c,text:u})=>({source:c,text:u}));if(!yl(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await nr({changeDir:le(e.paths,e.state.name),acceptanceIds:a.map(({id:c})=>c),validation:ir({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&iu({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Gl({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function qr(e){let t=await Pm(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Io({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function nu(e){return B(e.paths,`sync spec references ${e.name}`,async()=>{let t=await Ne(e.paths,e.name);if(t.state_version!==e.expectedStateVersion)throw new Error("Native spec sync state version is stale");if(t.archived||!["build","verify","archive"].includes(t.phase)||t.children_contract_hash)throw new Error("Native spec sync requires a confirmed ordinary active change; revise requirements in Shape otherwise");if(!en.test(e.capability)||!e.reason.trim()||!e.actor.trim())throw new Error("Native spec sync requires capability, actor and reason");await qr({paths:e.paths,state:t});let r=t.spec_changes.find(({capability:m,operation:p})=>m===e.capability&&p!=="remove");if(!r?.source)throw new Error("Stage this capability in the current change and confirm Shape before syncing references");let i=new Set(e.affectedAcceptanceIds);if(i.size===0||[...i].some(m=>!t.acceptance.some(p=>p.id===m))||t.acceptance.some(({source:m,id:p})=>m===r.source&&!i.has(p)))throw new Error("Native spec sync must cover the affected spec acceptance IDs");if(e.replacements.length===0||e.replacements.some(({from:m,to:p})=>!/^[A-Za-z0-9_./#%-]+$/u.test(m)||!/^[A-Za-z0-9_./#%-]+$/u.test(p)||m===p)||new Set(e.replacements.map(({from:m})=>m)).size!==e.replacements.length)throw new Error("Native spec sync only accepts unique local Markdown reference replacements");let n=le(e.paths,t.name),a=await T({root:n,ref:r.source,maxBytes:null,includeHash:!1}),o=new Map(e.replacements.map(({from:m,to:p})=>[m,p])),s=new Set,l=null,c=!1,u=a.text.split(/(?<=\n)/u).map(m=>{let p=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(m.trimEnd());return p?(l?p[1][0]===l.marker&&p[1].length>=l.length&&!p[2].trim()&&(l=null):l={marker:p[1][0],length:p[1].length},m):/^(?:\s|>|[-+*]\s|\d+[.)]\s)/u.test(m)?m:(m.includes("<!--")&&(c=!0),c?(m.includes("-->")&&(c=!1),m):l||/^(?: {4}|\t)/u.test(m)||m.includes("`")?m:m.replace(/(?<!!)\[([^\]\n]+)\]\(([^()\s]+)\)/gu,(v,g,w)=>{let N=o.get(w);return N?(s.add(w),`[${g}](${N})`):v}))}).join("");if(s.size!==o.size)throw new Error("Native spec sync replacement is not an existing prose Markdown reference; use revise-requirements for semantic changes");let d=ft.join(n,r.source);await ue(d,u,{containedRoot:e.paths.nativeRoot});let f=!1,h=null;try{let m=await ru({paths:e.paths,state:t,specChanges:t.spec_changes});if(!yl(t.acceptance,m.acceptance))throw new Error("Reference change affects acceptance; revise requirements in Shape");let p=x=>sC("sha256").update(x).digest("hex"),v=JSON.stringify({schema:"comet.native.spec-sync.v1",change:t.name,actor:e.actor,reason:e.reason,source:r.source,beforeHash:p(a.text),afterHash:p(u),replacements:e.replacements,affectedAcceptanceIds:[...i],requiresConfirmation:!1,at:new Date().toISOString()}),g=p(v),w=await Yl({paths:e.paths,name:t.name,hash:g,text:v,onCreated:()=>{h=g}}),N={...t,loop:{...t.loop,previous_unresolved_ids:[...new Set([...t.loop.previous_unresolved_ids,...i])]}},k=t.phase==="build"?{...N,state_version:t.state_version+1,acceptance:t.acceptance.map(x=>i.has(x.id)?{...x,result:"pending",reason:null}:x)}:xo({state:N,reason:`Spec reference sync: ${e.reason}`});k=Xt(k,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[...i],summary:je(`Spec reference sync by ${e.actor}: ${e.reason}; ${w}`),completed_at:new Date().toISOString()}),k.shape_confirmation_hash=iu({formalHash:m.formalHash,childrenHash:null,coordinationMode:t.coordination_mode});let E=await ut({paths:e.paths,previous:t,next:k});return f=!0,await De(ye(e.paths,t.name),He({portableState:E,projectRoot:e.paths.projectRoot,branch:lt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),E}catch(m){if(!f)try{(await Ne(e.paths,t.name)).state_version===t.state_version&&(await ue(d,a.text,{containedRoot:e.paths.nativeRoot}),h&&await Nm({paths:e.paths,name:t.name,hash:h}))}catch{}throw m}})}async function au(e){if(!en.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return B(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await Ne(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=t.spec_changes.filter(({capability:a})=>a!==e.capability),i={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...r,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await ut({paths:e.paths,previous:t,next:i});return await De(ye(e.paths,t.name),He({portableState:n,projectRoot:e.paths.projectRoot,branch:lt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function ou(e){return B(e.paths,`disassociate portable capability ${e.name}`,async()=>{let t=await Ne(e.paths,e.name);if(Ao({state:t,expected:e.expectedContinuation,action:"disassociate-capability"}),t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=ft.join(le(e.paths,e.name),eu),i;try{i=await Vr.lstat(r)}catch(n){if(n.code==="ENOENT")return t;throw n}if(!i.isFile()||i.isSymbolicLink())throw new Error("Native capability association must be a regular file");return await Vr.rm(r),Io({paths:e.paths,state:t,reason:"Capability association revoked through comet native spec disassociate"})})}async function Io(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Xt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:je(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await ut({paths:e.paths,previous:t,next:i});return await De(ye(e.paths,t.name),He({portableState:n,projectRoot:e.paths.projectRoot,branch:lt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}he();K();$t();Tt();ot();Qt();ct();$a();J();So();K();Qt();H();var oL=1024*1024*1024;K();ln();Ur();Tt();K();Tt();K();ao();ot();H();var _m=["evidence.md","repair.md","archive.md","checkpoint.md"],hC="verification.md";async function mC(e,t){let r=await Rl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Am(e,t){await nn.mkdir(e.transactionsDir,{recursive:!0}),await Q(no(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Im(e,t,r={}){let i=r.removeVerificationReport===!1?_m:[..._m,hC];await Promise.all([nn.rm(_e(e,t),{recursive:!0,force:!0}),nn.rm(Uc(e,t),{recursive:!0,force:!0}),...i.map(n=>nn.rm(pC.join(Ue(e,t),n),{force:!0}))])}async function Tm(e,t){await De(ye(e,t.name),He({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function jm(e,t){try{let r=await Ui(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function $m(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ke(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function vC(e){let t=Ue(e.paths,e.state.name),r=await T({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await T({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ua({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Om(e,t){let r=await Vh(e,t);if(r.status==="runtime-incompatible")throw new We(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Hm(e){return B(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await mC(e.paths,e.name),r=await er(e.paths,e.name)?await at(Ke(e.paths,e.name)):null;if(!t&&r)return await Im(e.paths,e.name,{removeVerificationReport:!1}),await Tm(e.paths,r),r;let i=null,n=null;for(t||(i=await Om(e.paths,e.name),n=await jm(e.paths,e.name),$m(e.paths,n),t={schema:ro,id:fC(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Am(e.paths,t));;){let a=bh(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Om(e.paths,e.name),n??=await jm(e.paths,e.name),$m(e.paths,n),r=Nh({state:i,acceptance:await vC({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await to(Ke(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Im(e.paths,e.name):a.action==="commit-transaction"&&(r??=await at(Ke(e.paths,e.name)),await Tm(e.paths,r)),t={...t,status:a.nextStatus},await Am(e.paths,t)}return await nn.rm(no(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??at(Ke(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}Ti();import on from"path";import{realpathSync as aP}from"fs";function Dm(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),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),l=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,c=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof c=="number"?c:null,workspace:{cwd:l},continuation:Object.keys(s).length?{...s,cwd:l}:null}}var pt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Lm(e){return e?e.command?`${pt.next} ${e.command}`:e.ask_user?`${pt.next} ${e.ask_user}`:null:null}function Bm(e,t){let r=[e.summary],i=Lm(e.next);return i&&r.push(i),e.user_message&&r.push("",pt.relay,e.user_message),t!==void 0&&r.push("",pt.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
262
|
+
`}function FR(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function qR(e){let t=[],r=!1;for(let i of Mu(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!FR(n[1]??"")})}async function Gv(e){let t=he(e.paths,e.state.name),r=[...(await qu(t,e.state.brief,{strict:!0,compact:e.state.document_constraints_version===2})).findings],i="";try{i=(await $({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:c})=>c!=="remove"),o=e.state.spec_changes.filter(({operation:c})=>c!=="remove"),s=new Set(a.map(({capability:c})=>c));if(e.specChanges!==void 0)for(let c of o)s.has(c.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${c.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${c.capability}/spec.md`});let l=n.length>0&&n.every(({operation:c})=>c==="remove");a.length===0&&o.length===0&&!l&&!qR(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let c of a){let u=`specs/${c.capability}/spec.md`;if(c.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:c.source??u});continue}try{let d=(await $({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...yv(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}function vs(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Jv(e){let t=he(e.paths,e.state.name),r=St.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await li.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,l)=>s.name.localeCompare(l.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Pn.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,l=St.join(t,...s.split("/")),c=await li.lstat(l);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=St.join(e.paths.specsDir,o.name,"spec.md"),d="create",f=null;try{let v=await li.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",f=pt((await $({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let m=`specs/${o.name}/${im}`,h=St.join(t,...m.split("/")),p={};try{let v=await li.lstat(h);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${m}`);let g=await $({root:t,ref:m,maxBytes:null,includeHash:!1}),w=dn(g.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let b=f??pt(""),k=e.state.spec_changes.find(x=>x.capability===o.name);if(k?.delta_source!==void 0){if(k.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==b)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);p={delta_source:m,base_hash:w.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:d,source:s,...p})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function id(e){let t=he(e.paths,e.state.name),r=await $({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Fu(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await $({root:t,ref:o.source,maxBytes:null,includeHash:!1}),l=s.text,c=null;if(o.delta_source){let u=await $({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=dn(u.text);l=sm(s.text,d);let f="";try{f=(await $({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(m){if(m.code!=="ENOENT")throw m}if(pt(f)===d.base_hash){let m=lm({baselineMarkdown:f,delta:d,allowAlreadyApplied:!0});if(pt(s.text)!==m.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}c=D("comet.native.shape-artifact-content.v1",ms(u.text))}i.push({capability:o.capability,source:s.ref,markdown:l}),n.push({...o,contentHash:D("comet.native.shape-artifact-content.v1",ms(s.text,e.state.document_constraints_version===2)),...c===null?{}:{deltaContentHash:c}})}let a=null;try{let o=await $({root:t,ref:td,maxBytes:65536,includeHash:!1}),s=Wv(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let c=St.relative(e.paths.projectRoot,St.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(St.sep,"/");if(s.current_spec!==c)throw new Error(`Native capability association points to ${s.current_spec}, expected ${c}`);a=D("comet.native.shape-artifact-content.v1",ms(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:_o({briefMarkdown:r.text,specs:i,resolveBriefReferences:e.state.document_constraints_version===2}),formalHash:D("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:D("comet.native.shape-artifact-content.v1",ms(r.text,e.state.document_constraints_version===2))},specs:n,association:{source:td,contentHash:a}})}}function nd(e){return D("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Uv(e){if(e.state.document_constraints_version!==void 0){let c=await Gv(e);if(!c.valid){let u=c.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Jv(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&c.delta_source===d.delta_source&&c.base_hash===d.base_hash&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await id({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:c,text:u})=>({source:c,text:u}));if(!au(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await yr({changeDir:he(e.paths,e.state.name),acceptanceIds:a.map(({id:c})=>c),validation:wr({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&nd({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Ju({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function ui(e){let t=await Uv(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await gs({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function ad(e){return F(e.paths,`sync spec references ${e.name}`,async()=>{let t=await Pe(e.paths,e.name);if(t.state_version!==e.expectedStateVersion)throw new Error("Native spec sync state version is stale");if(t.archived||!["build","verify","archive"].includes(t.phase)||t.children_contract_hash)throw new Error("Native spec sync requires a confirmed ordinary active change; revise requirements in Shape otherwise");if(!Pn.test(e.capability)||!e.reason.trim()||!e.actor.trim())throw new Error("Native spec sync requires capability, actor and reason");await ui({paths:e.paths,state:t});let r=t.spec_changes.find(({capability:h,operation:p})=>h===e.capability&&p!=="remove");if(!r?.source)throw new Error("Stage this capability in the current change and confirm Shape before syncing references");let i=new Set(e.affectedAcceptanceIds);if(i.size===0||[...i].some(h=>!t.acceptance.some(p=>p.id===h))||t.acceptance.some(({source:h,id:p})=>h===r.source&&!i.has(p)))throw new Error("Native spec sync must cover the affected spec acceptance IDs");if(e.replacements.length===0||e.replacements.some(({from:h,to:p})=>!/^[A-Za-z0-9_./#%-]+$/u.test(h)||!/^[A-Za-z0-9_./#%-]+$/u.test(p)||h===p)||new Set(e.replacements.map(({from:h})=>h)).size!==e.replacements.length)throw new Error("Native spec sync only accepts unique local Markdown reference replacements");let n=he(e.paths,t.name),a=await $({root:n,ref:r.source,maxBytes:null,includeHash:!1}),o=new Map(e.replacements.map(({from:h,to:p})=>[h,p])),s=new Set,l=null,c=!1,u=a.text.split(/(?<=\n)/u).map(h=>{let p=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(h.trimEnd());return p?(l?p[1][0]===l.marker&&p[1].length>=l.length&&!p[2].trim()&&(l=null):l={marker:p[1][0],length:p[1].length},h):/^(?:\s|>|[-+*]\s|\d+[.)]\s)/u.test(h)?h:(h.includes("<!--")&&(c=!0),c?(h.includes("-->")&&(c=!1),h):l||/^(?: {4}|\t)/u.test(h)||h.includes("`")?h:h.replace(/(?<!!)\[([^\]\n]+)\]\(([^()\s]+)\)/gu,(v,g,w)=>{let b=o.get(w);return b?(s.add(w),`[${g}](${b})`):v}))}).join("");if(s.size!==o.size)throw new Error("Native spec sync replacement is not an existing prose Markdown reference; use revise-requirements for semantic changes");let d=St.join(n,r.source);await ve(d,u,{containedRoot:e.paths.nativeRoot});let f=!1,m=null;try{let h=await id({paths:e.paths,state:t,specChanges:t.spec_changes});if(!au(t.acceptance,h.acceptance))throw new Error("Reference change affects acceptance; revise requirements in Shape");let p=E=>BR("sha256").update(E).digest("hex"),v=JSON.stringify({schema:"comet.native.spec-sync.v1",change:t.name,actor:e.actor,reason:e.reason,source:r.source,beforeHash:p(a.text),afterHash:p(u),replacements:e.replacements,affectedAcceptanceIds:[...i],requiresConfirmation:!1,at:new Date().toISOString()}),g=p(v),w=await Xu({paths:e.paths,name:t.name,hash:g,text:v,onCreated:()=>{m=g}}),b={...t,loop:{...t.loop,previous_unresolved_ids:[...new Set([...t.loop.previous_unresolved_ids,...i])]}},k=t.phase==="build"?{...b,state_version:t.state_version+1,acceptance:t.acceptance.map(E=>i.has(E.id)?{...E,result:"pending",reason:null}:E)}:ds({state:b,reason:`Spec reference sync: ${e.reason}`});k=lr(k,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[...i],summary:Be(`Spec reference sync by ${e.actor}: ${e.reason}; ${w}`),completed_at:new Date().toISOString()}),k.shape_confirmation_hash=nd({formalHash:h.formalHash,childrenHash:null,coordinationMode:t.coordination_mode});let x=await bt({paths:e.paths,previous:t,next:k});return f=!0,await Ve(Ce(e.paths,t.name),qe({portableState:x,projectRoot:e.paths.projectRoot,branch:yt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),x}catch(h){if(!f)try{(await Pe(e.paths,t.name)).state_version===t.state_version&&(await ve(d,a.text,{containedRoot:e.paths.nativeRoot}),m&&await Fv({paths:e.paths,name:t.name,hash:m}))}catch{}throw h}})}async function od(e){if(!Pn.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return F(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await Pe(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=t.spec_changes.filter(({capability:a})=>a!==e.capability),i={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...r,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await bt({paths:e.paths,previous:t,next:i});return await Ve(Ce(e.paths,t.name),qe({portableState:n,projectRoot:e.paths.projectRoot,branch:yt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function sd(e){return F(e.paths,`disassociate portable capability ${e.name}`,async()=>{let t=await Pe(e.paths,e.name);if(vs({state:t,expected:e.expectedContinuation,action:"disassociate-capability"}),t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=St.join(he(e.paths,e.name),td),i;try{i=await li.lstat(r)}catch(n){if(n.code==="ENOENT")return t;throw n}if(!i.isFile()||i.isSymbolicLink())throw new Error("Native capability association must be a regular file");return await li.rm(r),gs({paths:e.paths,state:t,reason:"Capability association revoked through comet native spec disassociate"})})}async function gs(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...lr(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Be(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await bt({paths:e.paths,previous:t,next:i});return await Ve(Ce(e.paths,t.name),qe({portableState:n,projectRoot:e.paths.projectRoot,branch:yt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}be();Q();zt();Vt();gt();ur();nt();vo();K();nt();ft();B();var rM=8*1024*1024;ls();Q();ur();L();var xM=1024*1024*1024;Q();Mn();vi();Vt();Q();Vt();Q();Fo();gt();L();var Yv=["evidence.md","repair.md","archive.md","checkpoint.md"],GR="verification.md";async function JR(e,t){let r=await gu(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Xv(e,t){await On.mkdir(e.transactionsDir,{recursive:!0}),await Z(Mo(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Qv(e,t,r={}){let i=r.removeVerificationReport===!1?Yv:[...Yv,GR];await Promise.all([On.rm(He(e,t),{recursive:!0,force:!0}),On.rm(Ol(e,t),{recursive:!0,force:!0}),...i.map(n=>On.rm(zR.join(it(e,t),n),{force:!0}))])}async function Zv(e,t){await Ve(Ce(e,t.name),qe({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function eg(e,t){try{let r=await Nn(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function tg(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=_e(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function UR(e){let t=it(e.paths,e.state.name),r=await $({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await $({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return _o({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function rg(e,t){let r=await Um(e,t);if(r.status==="runtime-incompatible")throw new Ze(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function ig(e){return F(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await JR(e.paths,e.name),r=await fr(e.paths,e.name)?await vt(at(e.paths,e.name)):null;if(!t&&r)return await Qv(e.paths,e.name,{removeVerificationReport:!1}),await Zv(e.paths,r),r;let i=null,n=null;for(t||(i=await rg(e.paths,e.name),n=await eg(e.paths,e.name),tg(e.paths,n),t={schema:Lo,id:WR(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Xv(e.paths,t));;){let a=Pm(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await rg(e.paths,e.name),n??=await eg(e.paths,e.name),tg(e.paths,n),r=Cm({state:i,acceptance:await UR({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Do(at(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Qv(e.paths,e.name):a.action==="commit-transaction"&&(r??=await vt(at(e.paths,e.name)),await Zv(e.paths,r)),t={...t,status:a.nextStatus},await Xv(e.paths,t)}return await On.rm(Mo(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??vt(at(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}an();import Dn from"path";import{realpathSync as D_}from"fs";function ng(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),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),l=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,c=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof c=="number"?c:null,workspace:{cwd:l},continuation:Object.keys(s).length?{...s,cwd:l}:null}}var Et={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function ag(e){return e?e.command?`${Et.next} ${e.command}`:e.ask_user?`${Et.next} ${e.ask_user}`:null:null}function og(e,t){let r=[e.summary],i=ag(e.next);return i&&r.push(i),e.user_message&&r.push("",Et.relay,e.user_message),t!==void 0&&r.push("",Et.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
185
263
|
`)}
|
|
186
|
-
`}function
|
|
187
|
-
`)}
|
|
188
|
-
`)}}let r=t.continuation;if(
|
|
264
|
+
`}function sg(e,t,r){let i=[e.summary],n=ag(e.next);return n&&i.push(n),e.user_message&&i.push("",Et.relay,e.user_message),i.push("",`${Et.detail} ${t}`),r!==void 0&&i.push("",Et.details,JSON.stringify(r,null,2)),i.join(`
|
|
265
|
+
`)}K();we();K();var KR=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});ci();tt();be();L();B();rt();un();Q();L();tt();br();K();K();fs();si();rt();var cg={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:[]},XR=xe("comet-native-runtime:v3:scope-reopen"),lV=[{skillVersion:"3",skillHash:xe("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:xe("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:xe("comet-native-runtime:v1")}];rt();rt();fn();var ug=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],VV=new Set(ug),n_=new Set([...ug,"minimum_runtime_version","revision"]),WV=new Set([...n_,"operation"]),a_=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),zV=new Set([...a_,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Ro();we();we();Ro();K();var YV={maxAcceptanceCriteria:Po.maxCriteria};ci();yn();si();fs();import{execFile as m_}from"node:child_process";xr();wi();zu();import{promisify as v_}from"node:util";B();rt();L();tt();Si();br();Q();B();Uu();L();Ge();ci();Q();br();var Hn=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};yn();ps();si();var ZW=64*1024;var ez=3600*1e3;var tz=v_(m_);ps();var ws=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};rt();tt();B();Ge();L();tt();Uo();B();er();ci();var Qz=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});rt();un();Q();L();tt();be();Q();var a2=16*1024;Uo();var ys=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"},bs=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();be();function C(e,t,r){return e==="zh-CN"?r:t}var cd={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function pg(e,t){return typeof e=="string"&&cd[e]?C(t,cd[e].en,cd[e].zh):typeof e=="string"?e:""}function ld(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function k_(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function hg(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function mg(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function ud(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function S_(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function E_(e,t,r){let i=ud(e),n=[];r&&n.push(r);let a=C(i,`Change ${e.change}`,`需求 ${e.change}`),o=pg(e.phase,i),s=S_(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(hg(t,i));let l=e.userCommunication,c=vg(e,i);return{summary:n.join("; "),...c?{next:c}:{},...l.required&&l.message?{user_message:l.message}:{}}}function vg(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:C(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function x_(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function C_(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=pg(e.phase,t),n=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=ld(e.acceptance)?`${C(t,", ",",")}${hg(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function P_(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function R_(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function __(e){if(e.healthy){let i=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=A_(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:C("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function A_(e){return mg(e)?vg(e,ud(e)):void 0}function gg(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(R_(t))return __(t);if(x_(t)){let i=P_(t.items);return{summary:[t.total===t.items.length?C(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>C_(a,i))].join(`
|
|
266
|
+
`)}}let r=t.continuation;if(mg(r)){let i=ud(r),n=E_(r,I_(t),$_(t,i));return T_(t)==="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 t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:C(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function I_(e){if(ld(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(ld(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return k_(r.acceptance)}return null}function T_(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function $_(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function wg(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:C("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:C("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Bn();Io();var yg=["--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."],dd=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:yg,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
|
|
189
267
|
comet native spec remove <change-name> <capability>
|
|
190
268
|
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>]
|
|
191
269
|
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>]
|
|
192
|
-
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
|
|
193
|
-
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
|
|
270
|
+
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>]
|
|
271
|
+
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 Ns(e,t){return`${e}:
|
|
194
272
|
${t.map(r=>` ${r}`).join(`
|
|
195
|
-
`)}`}function
|
|
196
|
-
${r.output}`),r.examples&&i.push("",
|
|
273
|
+
`)}`}function j_(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return dd[r]||t.length>1&&dd[t[0]]?.subcommands?r:t[0]}function O_(e=[]){let t=j_(e),r=dd[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",Ns("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",Ns("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...yg];return n&&n.length>0&&i.push("",Ns("Options",n)),i.push("",`Output:
|
|
274
|
+
${r.output}`),r.examples&&i.push("",Ns("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
197
275
|
`)}
|
|
198
|
-
`}}var
|
|
199
|
-
`}function
|
|
200
|
-
`}:e.error?{exitCode:e.exitCode,stderr:i?
|
|
201
|
-
${
|
|
276
|
+
`}}var H_=O_().usage;var mG=10*1024*1024,U=class extends Error{};function pd(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new U(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function fi(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new U(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new U(`${t} requires a value`);return e.splice(i,2),n}function ks(e){if(e.length>0)throw new U(`Unexpected argument: ${e[0]}`)}function kr(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new U(`${t} is required`);return r}function fd(e,t){let r=Dn.normalize(bg(e)),i=Dn.normalize(bg(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function bg(e){let t=Dn.resolve(e);try{return D_.native(t)}catch{return t}}function L_(e,t){let r=Dn.resolve(t,e),i=_e(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=_e(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!fd(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||fd(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:fd(t,i.currentWorktreeRoot)?Dn.resolve(t):i.currentWorktreeRoot}async function Ng(e,t=process.cwd()){return e?L_(e,t):lo(t)}function kg(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function Ss(e){let t=await Hh({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Sg(e){return JSON.stringify(e,null,2)+`
|
|
277
|
+
`}function Es(e,t,r){return{command:e,exitCode:0,data:t,text:r??Sg(t)}}function B_(e,t){if(t instanceof Tn)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof Yr)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof mi)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof U)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof ys)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof bs)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Yo)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Sn)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof us)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Xo)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof ws)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Hn)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Eg(e,t){let r=B_(e,t),i=r.error;if(!i)return r;let n=wg({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function M_(e,t,r=!1){let i=e.envelope??gg(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:ng(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
278
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?sg(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:og(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Sg(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
279
|
+
${Et.details}
|
|
202
280
|
${JSON.stringify(e.data,null,2)}
|
|
203
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function
|
|
204
|
-
`)}if(r==="disassociate"){let s=
|
|
205
|
-
`)}if(r!=="remove")throw new
|
|
206
|
-
`)}async function
|
|
281
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function F_(e,t,r=!1){let i=M_(e,t,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 xg(e,t,r=!1){return F_(e,t,r).output}async function Pg(e,t){let r=kr(e,"spec subcommand");if(r==="sync"){let s=fi(e,"--input"),l=kr(e,"change name"),c=kr(e,"capability");if(ks(e),!s)throw new U("spec sync requires --input <json-file>");let u=q_.resolve(t,s),d=await Cg.lstat(u).catch(()=>{throw new U(`Spec sync input file is unreadable: ${s}`)});if(!d.isFile()||d.isSymbolicLink()||d.size>1024*1024)throw new U("Spec sync input must be a bounded regular JSON file");let f;try{f=JSON.parse(await Cg.readFile(u,"utf8"))}catch{throw new U("Spec sync input must contain readable valid JSON")}if(!f||typeof f!="object"||Object.keys(f).sort().join(",")!=="actor,affectedAcceptanceIds,expectedStateVersion,reason,replacements"||typeof f.actor!="string"||typeof f.reason!="string"||!Number.isSafeInteger(f.expectedStateVersion)||!Array.isArray(f.affectedAcceptanceIds)||!f.affectedAcceptanceIds.every(p=>typeof p=="string")||!Array.isArray(f.replacements)||!f.replacements.every(p=>p&&typeof p=="object"&&Object.keys(p).sort().join(",")==="from,to"&&typeof p.from=="string"&&typeof p.to=="string"))throw new U("Spec sync input fields are invalid");let{paths:m}=await Ss(t),h=await ad({...f,paths:m,name:l,capability:c});return Es("spec sync",{...h,continuation:Vn(h)},`Synced Native spec references in ${l}
|
|
282
|
+
`)}if(r==="disassociate"){let s=kr(e,"change name"),l=fi(e,"--expected-state-version"),c=fi(e,"--expected-action");if(l===void 0||c===void 0)throw new U("--expected-state-version and --expected-action are required for spec disassociate");if(!/^[1-9]\d*$/u.test(l)||!Number.isSafeInteger(Number(l)))throw new U("--expected-state-version must be a positive integer");if(c!=="disassociate-capability")throw new U("--expected-action for spec disassociate must be disassociate-capability");ks(e);let{paths:u}=await Ss(t);if(!await fr(u,s))throw new U("spec disassociate requires a current portable Native change");let d=await sd({paths:u,name:s,expectedContinuation:{stateVersion:Number(l),action:"disassociate-capability"}});return Es("spec disassociate",{...d,continuation:Vn(d)},`Revoked Native capability association in ${s}
|
|
283
|
+
`)}if(r!=="remove")throw new U(`Unknown spec command: ${r}`);let i=kr(e,"change name"),n=kr(e,"capability");ks(e);let{paths:a}=await Ss(t);await fr(a,i)||await ig({paths:a,name:i});let o=await od({paths:a,name:i,capability:n});return Es("spec remove",{...o,continuation:Vn(o)},`Marked Native capability ${n} for removal in ${i}
|
|
284
|
+
`)}async function Rg(e,t,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"),l,c;try{pd(n,"--json"),pd(n,"--verbose"),l=fi(n,"--project-root");let d=[...n,...a],f=async()=>{let m=await Ng(l);return{executionCwd:m,...await t(d,m)}};c=kg(e,d)?await xd(f):await f()}catch(d){c=Eg(e,d)}let u=xg(c,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
207
285
|
`)?"":`
|
|
208
|
-
`)),u.exitCode}process.exitCode=await
|
|
286
|
+
`)),u.exitCode}process.exitCode=await Rg("spec",Pg);
|