@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,199 +1,276 @@
|
|
|
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
|
-
`)}};
|
|
7
|
-
`)?
|
|
4
|
+
var BE=Object.create;var gu=Object.defineProperty;var FE=Object.getOwnPropertyDescriptor;var LE=Object.getOwnPropertyNames;var qE=Object.getPrototypeOf,ME=Object.prototype.hasOwnProperty;var ns=(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 I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},VE=(e,t)=>{for(var r in t)gu(e,r,{get:t[r],enumerable:!0})},WE=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of LE(t))!ME.call(e,n)&&n!==r&&gu(e,n,{get:()=>t[n],enumerable:!(i=FE(t,n))||i.enumerable});return e};var ir=(e,t,r)=>(r=e!=null?BE(qE(e)):{},WE(t||!e||!e.__esModule?gu(r,"default",{value:e,enumerable:!0}):r,e));import{AsyncLocalStorage as zE}from"node:async_hooks";import{performance as as}from"node:perf_hooks";function os(e=0){GE+=1,JE+=e;let t=UE.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function Qn(e){let t=as.now();try{return e()}finally{os(as.now()-t)}}async function wu(e){let t=as.now();try{return await e()}finally{os(as.now()-t)}}var GE,JE,UE,Gi=I(()=>{"use strict";GE=0,JE=0,UE=new zE});import{existsSync as KE}from"node:fs";import Zn from"node:path";function Cm(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function XE(e){let t=(Cm(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function QE(e,t,r){let n=Zn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Cm(t,"PATH")??"").split(Zn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Zn.win32.extname(e)?[e]:XE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Zn.join(s,c):Zn.resolve(r,c)))}function ss(e,t,r){return QE(e,t,r).find(i=>KE(i))??e}function yu(e){if(e.some(t=>YE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var YE,dL,ea=I(()=>{"use strict";YE=/[&|<>()^%"!\r\n]/u,dL=["$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 ZE,execFileSync as hL}from"node:child_process";import Rm from"node:path";async function Er(e,t,r={}){let i=r.timeoutMs??ex,n=r.maxBufferBytes??tx;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Rm.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?ss(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&yu(t);let l=()=>new Promise((u,d)=>{let p=!1,f=ZE(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(g,b,k)=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),g?d(new ta(e,t,k.trim(),{cause:g,timedOut:rx(g)})):u(b))}),m=g=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),f.kill("SIGKILL"),f.stdin?.destroy(),f.stdout?.destroy(),f.stderr?.destroy(),f.unref(),d(new ta(e,t,"",{timedOut:g})))},h=()=>m(!1),v=setTimeout(()=>m(!0),i);r.signal?.addEventListener("abort",h,{once:!0}),r.signal?.aborted&&h(),f.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Rm.win32.basename(e))?wu(l):l()}function rx(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var ex,tx,ta,Ji=I(()=>{"use strict";Gi();ea();ex=6e4,tx=8*1024*1024;ta=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{createHash as sx}from"crypto";function wt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function cx(e,t){t.has(e)&&wt("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)||wt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&wt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&wt("symbol properties are not supported"),`[${e.map(i=>Nu(i,t)).join(",")}]`}finally{t.delete(e)}}function lx(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&wt("only plain objects are supported"),t.has(e)&&wt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&wt("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))&&wt("accessor properties are not supported"),`${JSON.stringify(o)}:${Nu(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Nu(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)||wt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?cx(e,t):lx(e,t);case"bigint":case"function":case"symbol":case"undefined":return wt(`${typeof e} values are not supported`)}return wt("unsupported value type")}function aa(e){return Nu(e,new Set)}function j(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 sx("sha256").update(`${e}
|
|
5
|
+
${aa(t)}`).digest("hex")}var de=I(()=>{"use strict"});var z=R(Ee=>{"use strict";var bu=Symbol.for("yaml.alias"),Tm=Symbol.for("yaml.document"),ls=Symbol.for("yaml.map"),jm=Symbol.for("yaml.pair"),ku=Symbol.for("yaml.scalar"),us=Symbol.for("yaml.seq"),ar=Symbol.for("yaml.node.type"),ux=e=>!!e&&typeof e=="object"&&e[ar]===bu,dx=e=>!!e&&typeof e=="object"&&e[ar]===Tm,px=e=>!!e&&typeof e=="object"&&e[ar]===ls,fx=e=>!!e&&typeof e=="object"&&e[ar]===jm,$m=e=>!!e&&typeof e=="object"&&e[ar]===ku,hx=e=>!!e&&typeof e=="object"&&e[ar]===us;function Om(e){if(e&&typeof e=="object")switch(e[ar]){case ls:case us:return!0}return!1}function mx(e){if(e&&typeof e=="object")switch(e[ar]){case bu:case ls:case ku:case us:return!0}return!1}var vx=e=>($m(e)||Om(e))&&!!e.anchor;Ee.ALIAS=bu;Ee.DOC=Tm;Ee.MAP=ls;Ee.NODE_TYPE=ar;Ee.PAIR=jm;Ee.SCALAR=ku;Ee.SEQ=us;Ee.hasAnchor=vx;Ee.isAlias=ux;Ee.isCollection=Om;Ee.isDocument=dx;Ee.isMap=px;Ee.isNode=mx;Ee.isPair=fx;Ee.isScalar=$m;Ee.isSeq=hx});var oa=R(Su=>{"use strict";var ye=z(),qe=Symbol("break visit"),Hm=Symbol("skip children"),Ht=Symbol("remove node");function ds(e,t){let r=Dm(t);ye.isDocument(e)?Ui(null,e.contents,r,Object.freeze([e]))===Ht&&(e.contents=null):Ui(null,e,r,Object.freeze([]))}ds.BREAK=qe;ds.SKIP=Hm;ds.REMOVE=Ht;function Ui(e,t,r,i){let n=Bm(e,t,r,i);if(ye.isNode(n)||ye.isPair(n))return Fm(e,i,n),Ui(e,n,r,i);if(typeof n!="symbol"){if(ye.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Ui(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===qe)return qe;o===Ht&&(t.items.splice(a,1),a-=1)}}}else if(ye.isPair(t)){i=Object.freeze(i.concat(t));let a=Ui("key",t.key,r,i);if(a===qe)return qe;a===Ht&&(t.key=null);let o=Ui("value",t.value,r,i);if(o===qe)return qe;o===Ht&&(t.value=null)}}return n}async function ps(e,t){let r=Dm(t);ye.isDocument(e)?await Ki(null,e.contents,r,Object.freeze([e]))===Ht&&(e.contents=null):await Ki(null,e,r,Object.freeze([]))}ps.BREAK=qe;ps.SKIP=Hm;ps.REMOVE=Ht;async function Ki(e,t,r,i){let n=await Bm(e,t,r,i);if(ye.isNode(n)||ye.isPair(n))return Fm(e,i,n),Ki(e,n,r,i);if(typeof n!="symbol"){if(ye.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Ki(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===qe)return qe;o===Ht&&(t.items.splice(a,1),a-=1)}}}else if(ye.isPair(t)){i=Object.freeze(i.concat(t));let a=await Ki("key",t.key,r,i);if(a===qe)return qe;a===Ht&&(t.key=null);let o=await Ki("value",t.value,r,i);if(o===qe)return qe;o===Ht&&(t.value=null)}}return n}function Dm(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 Bm(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ye.isMap(t))return r.Map?.(e,t,i);if(ye.isSeq(t))return r.Seq?.(e,t,i);if(ye.isPair(t))return r.Pair?.(e,t,i);if(ye.isScalar(t))return r.Scalar?.(e,t,i);if(ye.isAlias(t))return r.Alias?.(e,t,i)}function Fm(e,t,r){let i=t[t.length-1];if(ye.isCollection(i))i.items[e]=r;else if(ye.isPair(i))e==="key"?i.key=r:i.value=r;else if(ye.isDocument(i))i.contents=r;else{let n=ye.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Su.visit=ds;Su.visitAsync=ps});var Eu=R(qm=>{"use strict";var Lm=z(),gx=oa(),wx={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},yx=e=>e.replace(/[!,[\]{}]/g,t=>wx[t]),sa=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+yx(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&&Lm.isNode(t.contents)){let a={};gx.visit(t.contents,(o,s)=>{Lm.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(`
|
|
6
|
+
`)}};sa.defaultYaml={explicit:!1,version:"1.2"};sa.defaultTags={"!!":"tag:yaml.org,2002:"};qm.Directives=sa});var fs=R(ca=>{"use strict";var Mm=z(),Nx=oa();function bx(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 Vm(e){let t=new Set;return Nx.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Wm(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function kx(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Vm(e));let o=Wm(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Mm.isScalar(o.node)||Mm.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}}ca.anchorIsValid=bx;ca.anchorNames=Vm;ca.createNodeAnchors=kx;ca.findNewAnchor=Wm});var xu=R(zm=>{"use strict";function la(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=la(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=la(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=la(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=la(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}zm.applyReviver=la});var Rr=R(Jm=>{"use strict";var Sx=z();function Gm(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Gm(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Sx.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}Jm.toJS=Gm});var hs=R(Km=>{"use strict";var Ex=xu(),Um=z(),xx=Rr(),Cu=class{constructor(t){Object.defineProperty(this,Um.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(!Um.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=xx.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Ex.applyReviver(a,{"":s},"",s):s}};Km.NodeBase=Cu});var ua=R(Ym=>{"use strict";var Cx=fs(),Rx=oa(),Yi=z(),Px=hs(),_x=Rr(),Ru=class extends Px.NodeBase{constructor(t){super(Yi.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=[],Rx.visit(t,{Node:(a,o)=>{(Yi.isAlias(o)||Yi.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 c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(_x.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ms(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Cx.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 ms(e,t,r){if(Yi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Yi.isCollection(t)){let i=0;for(let n of t.items){let a=ms(e,n,r);a>i&&(i=a)}return i}else if(Yi.isPair(t)){let i=ms(e,t.key,r),n=ms(e,t.value,r);return Math.max(i,n)}return 1}Ym.Alias=Ru});var pe=R(Pu=>{"use strict";var Ax=z(),Ix=hs(),Tx=Rr(),jx=e=>!e||typeof e!="function"&&typeof e!="object",Pr=class extends Ix.NodeBase{constructor(t){super(Ax.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Tx.toJS(this.value,t,r)}toString(){return String(this.value)}};Pr.BLOCK_FOLDED="BLOCK_FOLDED";Pr.BLOCK_LITERAL="BLOCK_LITERAL";Pr.PLAIN="PLAIN";Pr.QUOTE_DOUBLE="QUOTE_DOUBLE";Pr.QUOTE_SINGLE="QUOTE_SINGLE";Pu.Scalar=Pr;Pu.isScalarValue=jx});var da=R(Qm=>{"use strict";var $x=ua(),fi=z(),Xm=pe(),Ox="tag:yaml.org,2002:";function Hx(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 Dx(e,t,r){if(fi.isDocument(e)&&(e=e.contents),fi.isNode(e))return e;if(fi.isPair(e)){let d=r.schema[fi.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,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new $x.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Ox+t.slice(2));let l=Hx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Xm.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[fi.MAP]:Symbol.iterator in Object(e)?o[fi.SEQ]:o[fi.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Xm.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Qm.createNode=Dx});var gs=R(vs=>{"use strict";var Bx=da(),Dt=z(),Fx=hs();function _u(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 Bx.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 Zm=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Au=class extends Fx.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=>Dt.isNode(i)||Dt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Zm(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Dt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,_u(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(Dt.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&&Dt.isScalar(a)?a.value:a:Dt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Dt.isPair(r))return!1;let i=r.value;return i==null||t&&Dt.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 Dt.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(Dt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,_u(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};vs.Collection=Au;vs.collectionFromPath=_u;vs.isEmptyPath=Zm});var pa=R(ws=>{"use strict";var Lx=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Iu(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var qx=(e,t,r)=>e.endsWith(`
|
|
7
|
+
`)?Iu(r,t):r.includes(`
|
|
8
8
|
`)?`
|
|
9
|
-
`+
|
|
10
|
-
`)r===
|
|
11
|
-
`&&
|
|
12
|
-
`&&N!==" "&&(
|
|
13
|
-
${t}${e.slice(0,x)}`:(r===
|
|
14
|
-
${t}${e.slice(N+1,x)}`)}return b}function
|
|
15
|
-
`);i=t,n=t+1,a=e[n]}return i}
|
|
16
|
-
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function
|
|
9
|
+
`+Iu(r,t):(e.endsWith(" ")?"":" ")+r;ws.indentComment=Iu;ws.lineComment=qx;ws.stringifyComment=Lx});var tv=R(fa=>{"use strict";var Mx="flow",Tu="block",ys="quoted";function Vx(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 c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let p,f,m=!1,h=-1,v=-1,g=-1;r===Tu&&(h=ev(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===ys&&k==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(k===`
|
|
10
|
+
`)r===Tu&&(h=ev(e,h,t.length)),d=h+t.length+c,p=void 0;else{if(k===" "&&f&&f!==" "&&f!==`
|
|
11
|
+
`&&f!==" "){let N=e[h+1];N&&N!==" "&&N!==`
|
|
12
|
+
`&&N!==" "&&(p=h)}if(h>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===ys){for(;f===" "||f===" ";)f=k,k=e[h+=1],m=!0;let N=h>g+1?h-2:v-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,p=void 0}else m=!0}f=k}if(m&&s&&s(),l.length===0)return e;o&&o();let b=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let N=l[k],x=l[k+1]||e.length;N===0?b=`
|
|
13
|
+
${t}${e.slice(0,x)}`:(r===ys&&u[N]&&(b+=`${e[N]}\\`),b+=`
|
|
14
|
+
${t}${e.slice(N+1,x)}`)}return b}function ev(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!==`
|
|
15
|
+
`);i=t,n=t+1,a=e[n]}return i}fa.FOLD_BLOCK=Tu;fa.FOLD_FLOW=Mx;fa.FOLD_QUOTED=ys;fa.foldFlowLines=Vx});var ma=R(rv=>{"use strict";var yt=pe(),_r=tv(),bs=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ks=e=>/^(%|---|\.\.\.)/m.test(e);function Wx(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]===`
|
|
16
|
+
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function ha(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(ks(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
|
|
17
17
|
|
|
18
18
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
19
|
-
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:
|
|
20
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
21
|
-
${r}`)+"'";return t.implicitKey?i:
|
|
19
|
+
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:_r.foldFlowLines(o,a,_r.FOLD_QUOTED,bs(t,!1))}function ju(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
20
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return ha(e,t);let r=t.indent||(ks(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
21
|
+
${r}`)+"'";return t.implicitKey?i:_r.foldFlowLines(i,r,_r.FOLD_FLOW,bs(t,!1))}function Xi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=ha;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=ju:a&&!n?i=ha:i=r?ju:ha}return i(e,t)}var $u;try{$u=new RegExp(`(^|(?<!
|
|
22
22
|
))
|
|
23
23
|
+(?!
|
|
24
|
-
|$)`,"g")}catch{
|
|
24
|
+
|$)`,"g")}catch{$u=/\n+(?!\n|$)/g}function Ns({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Xi(r,i);let l=i.indent||(i.forceBlockIndent||ks(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===yt.Scalar.BLOCK_FOLDED?!1:t===yt.Scalar.BLOCK_LITERAL?!0:!Wx(r,c,l.length);if(!r)return u?`|
|
|
25
25
|
`:`>
|
|
26
|
-
`;let d,
|
|
27
|
-
`&&x!==" "&&x!==" ")break}let
|
|
28
|
-
`);m===-1?d="-":r===
|
|
29
|
-
`&&(
|
|
26
|
+
`;let d,p;for(p=r.length;p>0;--p){let x=r[p-1];if(x!==`
|
|
27
|
+
`&&x!==" "&&x!==" ")break}let f=r.substring(p),m=f.indexOf(`
|
|
28
|
+
`);m===-1?d="-":r===f||m!==f.length-1?(d="+",a&&a()):d="",f&&(r=r.slice(0,-f.length),f[f.length-1]===`
|
|
29
|
+
`&&(f=f.slice(0,-1)),f=f.replace($u,`$&${l}`));let h=!1,v,g=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
|
|
30
30
|
`)g=v;else break}let b=r.substring(0,g<v?g+1:v);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+d;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let x=r.replace(/\n+/g,`
|
|
31
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,
|
|
31
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,S=bs(i,!0);o!=="folded"&&t!==yt.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{w=!0});let E=_r.foldFlowLines(`${b}${x}${f}`,l,_r.FOLD_BLOCK,S);if(!w)return`>${N}
|
|
32
32
|
${l}${E}`}return r=r.replace(/\n+/g,`$&${l}`),`|${N}
|
|
33
|
-
${l}${b}${r}${
|
|
34
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
35
|
-
`)
|
|
36
|
-
`))return
|
|
37
|
-
${c}`);if(o){let
|
|
38
|
-
${t.indent}${s}`:s}
|
|
39
|
-
${s}:`):(v=`${v}:`,
|
|
40
|
-
`:"",b){let
|
|
41
|
-
${
|
|
42
|
-
`&&
|
|
33
|
+
${l}${b}${r}${f}`}function zx(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
34
|
+
`)||u&&/[[\]{},]/.test(a))return Xi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
35
|
+
`)?Xi(a,t):Ns(e,t,r,i);if(!s&&!u&&n!==yt.Scalar.PLAIN&&a.includes(`
|
|
36
|
+
`))return Ns(e,t,r,i);if(ks(a)){if(c==="")return t.forceBlockIndent=!0,Ns(e,t,r,i);if(s&&c===l)return Xi(a,t)}let d=a.replace(/\n+/g,`$&
|
|
37
|
+
${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:f,tags:m}=t.doc.schema;if(m.some(p)||f?.some(p))return Xi(a,t)}return s?d:_r.foldFlowLines(d,c,_r.FOLD_FLOW,bs(t,!1))}function Gx(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!==yt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=yt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case yt.Scalar.BLOCK_FOLDED:case yt.Scalar.BLOCK_LITERAL:return n||a?Xi(o.value,t):Ns(o,t,r,i);case yt.Scalar.QUOTE_DOUBLE:return ha(o.value,t);case yt.Scalar.QUOTE_SINGLE:return ju(o.value,t);case yt.Scalar.PLAIN:return zx(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,p=n&&u||d;if(l=c(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}rv.stringifyString=Gx});var va=R(Ou=>{"use strict";var Jx=fs(),Ar=z(),Ux=pa(),Kx=ma();function Yx(e,t){let r=Object.assign({blockQuote:!0,commentString:Ux.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 Xx(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(Ar.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 Qx(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Ar.isScalar(e)||Ar.isCollection(e))&&e.anchor;a&&Jx.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 Zx(e,t,r,i){if(Ar.isPair(e))return e.toString(t,r,i);if(Ar.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=Ar.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Xx(t.doc.schema.tags,a));let o=Qx(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):Ar.isScalar(a)?Kx.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Ar.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
38
|
+
${t.indent}${s}`:s}Ou.createStringifyContext=Yx;Ou.stringify=Zx});var ov=R(av=>{"use strict";var or=z(),iv=pe(),nv=va(),ga=pa();function eC({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,p=or.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(or.isCollection(e)||!or.isNode(e)&&typeof e=="object"){let S="With simple keys, collection cannot be used as a key value";throw new Error(S)}}let f=!d&&(!e||p&&t==null&&!r.inFlow||or.isCollection(e)||(or.isScalar(e)?e.type===iv.Scalar.BLOCK_FOLDED||e.type===iv.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(d||!a),indent:s+c});let m=!1,h=!1,v=nv.stringify(e,r,()=>m=!0,()=>h=!0);if(!f&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(r.inFlow){if(a||t==null)return m&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!d||t==null&&f)return v=`? ${v}`,p&&!m?v+=ga.lineComment(v,r.indent,l(p)):h&&n&&n(),v;m&&(p=null),f?(p&&(v+=ga.lineComment(v,r.indent,l(p))),v=`? ${v}
|
|
39
|
+
${s}:`):(v=`${v}:`,p&&(v+=ga.lineComment(v,r.indent,l(p))));let g,b,k;or.isNode(t)?(g=!!t.spaceBefore,b=t.commentBefore,k=t.comment):(g=!1,b=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!f&&!p&&or.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!f&&or.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,x=nv.stringify(t,r,()=>N=!0,()=>h=!0),w=" ";if(p||g||b){if(w=g?`
|
|
40
|
+
`:"",b){let S=l(b);w+=`
|
|
41
|
+
${ga.indentComment(S,r.indent)}`}x===""&&!r.inFlow?w===`
|
|
42
|
+
`&&k&&(w=`
|
|
43
43
|
|
|
44
44
|
`):w+=`
|
|
45
|
-
${r.indent}`}else if(!
|
|
46
|
-
`),y=E!==-1,C=r.inFlow??t.flow??t.items.length===0;if(y||!C){let O=!1;if(y&&(
|
|
45
|
+
${r.indent}`}else if(!f&&or.isCollection(t)){let S=x[0],E=x.indexOf(`
|
|
46
|
+
`),y=E!==-1,C=r.inFlow??t.flow??t.items.length===0;if(y||!C){let O=!1;if(y&&(S==="&"||S==="!")){let T=x.indexOf(" ");S==="&"&&T!==-1&&T<E&&x[T+1]==="!"&&(T=x.indexOf(" ",T+1)),(T===-1||E<T)&&(O=!0)}O||(w=`
|
|
47
47
|
${r.indent}`)}}else(x===""||x[0]===`
|
|
48
|
-
`)&&(w="");return v+=w+x,r.inFlow?N&&i&&i():
|
|
48
|
+
`)&&(w="");return v+=w+x,r.inFlow?N&&i&&i():k&&!N?v+=ga.lineComment(v,r.indent,l(k)):h&&n&&n(),v}av.stringifyPair=eC});var Du=R(Hu=>{"use strict";var sv=ns("process");function tC(e,...t){e==="debug"&&console.log(...t)}function rC(e,t){(e==="debug"||e==="warn")&&(typeof sv.emitWarning=="function"?sv.emitWarning(t):console.warn(t))}Hu.debug=tC;Hu.warn=rC});var Rs=R(Cs=>{"use strict";var xs=z(),cv=pe(),Ss="<<",Es={identify:e=>e===Ss||typeof e=="symbol"&&e.description===Ss,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new cv.Scalar(Symbol(Ss)),{addToJSMap:lv}),stringify:()=>Ss},iC=(e,t)=>(Es.identify(t)||xs.isScalar(t)&&(!t.type||t.type===cv.Scalar.PLAIN)&&Es.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Es.tag&&r.default);function lv(e,t,r){let i=uv(e,r);if(xs.isSeq(i))for(let n of i.items)Bu(e,t,n);else if(Array.isArray(i))for(let n of i)Bu(e,t,n);else Bu(e,t,i)}function Bu(e,t,r){let i=uv(e,r);if(!xs.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 uv(e,t){return e&&xs.isAlias(t)?t.resolve(e.doc,e):t}Cs.addMergeToJSMap=lv;Cs.isMergeKey=iC;Cs.merge=Es});var Lu=R(fv=>{"use strict";var nC=Du(),dv=Rs(),aC=va(),pv=z(),Fu=Rr();function oC(e,t,{key:r,value:i}){if(pv.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(dv.isMergeKey(e,r))dv.addMergeToJSMap(e,t,i);else{let n=Fu.toJS(r,"",e);if(t instanceof Map)t.set(n,Fu.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=sC(r,n,e),o=Fu.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 sC(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(pv.isNode(e)&&r?.doc){let i=aC.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)+'..."'),nC.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)}fv.addPairToJSMap=oC});var Ir=R(qu=>{"use strict";var hv=da(),cC=ov(),lC=Lu(),Ps=z();function uC(e,t,r){let i=hv.createNode(e,void 0,r),n=hv.createNode(t,void 0,r);return new _s(i,n)}var _s=class e{constructor(t,r=null){Object.defineProperty(this,Ps.NODE_TYPE,{value:Ps.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return Ps.isNode(r)&&(r=r.clone(t)),Ps.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return lC.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?cC.stringifyPair(this,t,r,i):JSON.stringify(this)}};qu.Pair=_s;qu.createPair=uC});var Mu=R(vv=>{"use strict";var hi=z(),mv=va(),As=pa();function dC(e,t,r){return(t.inFlow??e.flow?fC:pC)(e,t,r)}function pC({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(hi.isNode(h))!d&&h.spaceBefore&&p.push(""),Is(r,p,h.commentBefore,d),h.comment&&(v=h.comment);else if(hi.isPair(h)){let b=hi.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&p.push(""),Is(r,p,b.commentBefore,d))}d=!1;let g=mv.stringify(h,u,()=>v=null,()=>d=!0);v&&(g+=As.lineComment(g,a,l(v))),d&&v&&(d=!1),p.push(i+g)}let f;if(p.length===0)f=n.start+n.end;else{f=p[0];for(let m=1;m<p.length;++m){let h=p[m];f+=h?`
|
|
49
49
|
${c}${h}`:`
|
|
50
|
-
`}}return e?(
|
|
51
|
-
`+
|
|
52
|
-
`)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((b,
|
|
50
|
+
`}}return e?(f+=`
|
|
51
|
+
`+As.indentComment(l(e),c),s&&s()):d&&o&&o(),f}function fC({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(hi.isNode(h))h.spaceBefore&&d.push(""),Is(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(hi.isPair(h)){let b=hi.isNode(h.key)?h.key:null;b&&(b.spaceBefore&&d.push(""),Is(t,d,b.commentBefore,!1),b.comment&&(l=!0));let k=hi.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&b?.comment&&(v=b.comment)}v&&(l=!0);let g=mv.stringify(h,c,()=>v=null);l||(l=d.length>u||g.includes(`
|
|
52
|
+
`)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((b,k)=>b+k.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=As.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:p,end:f}=r;if(d.length===0)return p+f;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=p;for(let h of d)m+=h?`
|
|
53
53
|
${a}${n}${h}`:`
|
|
54
54
|
`;return`${m}
|
|
55
|
-
${n}${
|
|
56
|
-
`:" ")}return
|
|
55
|
+
${n}${f}`}else return`${p}${o}${d.join(" ")}${o}${f}`}function Is({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=As.indentComment(t(i),e);r.push(a.trimStart())}}vv.stringifyCollection=dC});var jr=R(Wu=>{"use strict";var hC=Mu(),mC=Lu(),vC=gs(),Tr=z(),Ts=Ir(),gC=pe();function wa(e,t){let r=Tr.isScalar(t)?t.value:t;for(let i of e)if(Tr.isPair(i)&&(i.key===t||i.key===r||Tr.isScalar(i.key)&&i.key.value===r))return i}var Vu=class extends vC.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Tr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ts.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Tr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Ts.Pair(t,t?.value):i=new Ts.Pair(t.key,t.value);let n=wa(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Tr.isScalar(n.value)&&gC.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=wa(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=wa(this.items,t)?.value;return(!r&&Tr.isScalar(n)?n.value:n)??void 0}has(t){return!!wa(this.items,t)}set(t,r){this.add(new Ts.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)mC.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Tr.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})),hC.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Wu.YAMLMap=Vu;Wu.findPair=wa});var Qi=R(wv=>{"use strict";var wC=z(),gv=jr(),yC={collection:"map",default:!0,nodeClass:gv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return wC.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>gv.YAMLMap.from(e,t,r)};wv.map=yC});var $r=R(yv=>{"use strict";var NC=da(),bC=Mu(),kC=gs(),$s=z(),SC=pe(),EC=Rr(),zu=class extends kC.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super($s.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=js(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=js(t);if(typeof i!="number")return;let n=this.items[i];return!r&&$s.isScalar(n)?n.value:n}has(t){let r=js(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=js(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];$s.isScalar(n)&&SC.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(EC.toJS(a,String(n++),r));return i}toString(t,r,i){return t?bC.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 c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(NC.createNode(s,void 0,i))}}return a}};function js(e){let t=$s.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}yv.YAMLSeq=zu});var Zi=R(bv=>{"use strict";var xC=z(),Nv=$r(),CC={collection:"seq",default:!0,nodeClass:Nv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return xC.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Nv.YAMLSeq.from(e,t,r)};bv.seq=CC});var ya=R(kv=>{"use strict";var RC=ma(),PC={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),RC.stringifyString(e,t,r,i)}};kv.string=PC});var Os=R(xv=>{"use strict";var Sv=pe(),Ev={identify:e=>e==null,createNode:()=>new Sv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Sv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Ev.test.test(e)?e:t.options.nullStr};xv.nullTag=Ev});var Gu=R(Rv=>{"use strict";var _C=pe(),Cv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new _C.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Cv.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Rv.boolTag=Cv});var en=R(Pv=>{"use strict";function AC({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}Pv.stringifyNumber=AC});var Uu=R(Hs=>{"use strict";var IC=pe(),Ju=en(),TC={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:Ju.stringifyNumber},jC={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():Ju.stringifyNumber(e)}},$C={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 IC.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Ju.stringifyNumber};Hs.float=$C;Hs.floatExp=jC;Hs.floatNaN=TC});var Yu=R(Bs=>{"use strict";var _v=en(),Ds=e=>typeof e=="bigint"||Number.isInteger(e),Ku=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Av(e,t,r){let{value:i}=e;return Ds(i)&&i>=0?r+i.toString(t):_v.stringifyNumber(e)}var OC={identify:e=>Ds(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Ku(e,2,8,r),stringify:e=>Av(e,8,"0o")},HC={identify:Ds,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Ku(e,0,10,r),stringify:_v.stringifyNumber},DC={identify:e=>Ds(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Ku(e,2,16,r),stringify:e=>Av(e,16,"0x")};Bs.int=HC;Bs.intHex=DC;Bs.intOct=OC});var Tv=R(Iv=>{"use strict";var BC=Qi(),FC=Os(),LC=Zi(),qC=ya(),MC=Gu(),Xu=Uu(),Qu=Yu(),VC=[BC.map,LC.seq,qC.string,FC.nullTag,MC.boolTag,Qu.intOct,Qu.int,Qu.intHex,Xu.floatNaN,Xu.floatExp,Xu.float];Iv.schema=VC});var Ov=R($v=>{"use strict";var WC=pe(),zC=Qi(),GC=Zi();function jv(e){return typeof e=="bigint"||Number.isInteger(e)}var Fs=({value:e})=>JSON.stringify(e),JC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Fs},{identify:e=>e==null,createNode:()=>new WC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fs},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Fs},{identify:jv,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})=>jv(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:Fs}],UC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},KC=[zC.map,GC.seq].concat(JC,UC);$v.schema=KC});var ed=R(Hv=>{"use strict";var Na=ns("buffer"),Zu=pe(),YC=ma(),XC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Na.Buffer=="function")return Na.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 Na.Buffer=="function")s=o instanceof Na.Buffer?o.toString("base64"):Na.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Zu.Scalar.BLOCK_LITERAL),t!==Zu.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,p=0;d<l;++d,p+=c)u[d]=s.substr(p,c);s=u.join(t===Zu.Scalar.BLOCK_LITERAL?`
|
|
56
|
+
`:" ")}return YC.stringifyString({comment:e,type:t,value:s},i,n,a)}};Hv.binary=XC});var Ms=R(qs=>{"use strict";var Ls=z(),td=Ir(),QC=pe(),ZC=$r();function Dv(e,t){if(Ls.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Ls.isPair(i)){if(Ls.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new td.Pair(new QC.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
|
|
57
57
|
${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
|
|
58
|
-
${a.comment}`:i.comment}i=n}e.items[r]=ns.isPair(i)?i:new fu.Pair(i)}}else t("Expected a sequence for this tag");return e}function _m(e,t,r){let{replacer:i}=r,n=new px.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(fu.createPair(s,c,r))}return n}var hx={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Rm,createNode:_m};as.createPairs=_m;as.pairs=hx;as.resolvePairs=Rm});var mu=P(hu=>{"use strict";var Am=W(),pu=mr(),Kn=br(),mx=kr(),Im=os(),ri=class e extends mx.YAMLSeq{constructor(){super(),this.add=Kn.YAMLMap.prototype.add.bind(this),this.delete=Kn.YAMLMap.prototype.delete.bind(this),this.get=Kn.YAMLMap.prototype.get.bind(this),this.has=Kn.YAMLMap.prototype.has.bind(this),this.set=Kn.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(Am.isPair(n)?(a=pu.toJS(n.key,"",r),o=pu.toJS(n.value,a,r)):a=pu.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=Im.createPairs(t,r,i),a=new this;return a.items=n.items,a}};ri.tag="tag:yaml.org,2002:omap";var vx={collection:"seq",identify:e=>e instanceof Map,nodeClass:ri,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Im.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Am.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new ri,r)},createNode:(e,t,r)=>ri.from(e,t,r)};hu.YAMLOMap=ri;hu.omap=vx});var Hm=P(vu=>{"use strict";var jm=ue();function Tm({value:e,source:t},r){return t&&(e?$m:Om).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var $m={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 jm.Scalar(!0),stringify:Tm},Om={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 jm.Scalar(!1),stringify:Tm};vu.falseTag=Om;vu.trueTag=$m});var Dm=P(ss=>{"use strict";var gx=ue(),gu=Di(),wx={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:gu.stringifyNumber},yx={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():gu.stringifyNumber(e)}},Nx={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 gx.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:gu.stringifyNumber};ss.float=Nx;ss.floatExp=yx;ss.floatNaN=wx});var Fm=P(Xn=>{"use strict";var qm=Di(),Yn=e=>typeof e=="bigint"||Number.isInteger(e);function cs(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 wu(e,t,r){let{value:i}=e;if(Yn(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return qm.stringifyNumber(e)}var bx={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>cs(e,2,2,r),stringify:e=>wu(e,2,"0b")},kx={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>cs(e,1,8,r),stringify:e=>wu(e,8,"0")},Sx={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>cs(e,0,10,r),stringify:qm.stringifyNumber},Ex={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>cs(e,2,16,r),stringify:e=>wu(e,16,"0x")};Xn.int=Sx;Xn.intBin=bx;Xn.intHex=Ex;Xn.intOct=kx});var Nu=P(yu=>{"use strict";var ds=W(),ls=yr(),us=br(),ii=class e extends us.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;ds.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new ls.Pair(t.key,null):r=new ls.Pair(t,null),us.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=us.findPair(this.items,t);return!r&&ds.isPair(i)?ds.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=us.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new ls.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(ls.createPair(o,null,i));return a}};ii.tag="tag:yaml.org,2002:set";var xx={collection:"map",identify:e=>e instanceof Set,nodeClass:ii,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>ii.from(e,t,r),resolve(e,t){if(ds.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ii,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};yu.YAMLSet=ii;yu.set=xx});var ku=P(fs=>{"use strict";var Cx=Di();function bu(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 Lm(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Cx.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 Px={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})=>bu(e,r),stringify:Lm},Rx={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=>bu(e,!1),stringify:Lm},Bm={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(Bm.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=bu(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};fs.floatTime=Rx;fs.intTime=Px;fs.timestamp=Bm});var Wm=P(Mm=>{"use strict";var _x=Oi(),Ax=Zo(),Ix=Hi(),jx=Gn(),Tx=du(),Vm=Hm(),Su=Dm(),ps=Fm(),$x=zo(),Ox=mu(),Hx=os(),Dx=Nu(),Eu=ku(),qx=[_x.map,Ix.seq,jx.string,Ax.nullTag,Vm.trueTag,Vm.falseTag,ps.intBin,ps.intOct,ps.int,ps.intHex,Su.floatNaN,Su.floatExp,Su.float,Tx.binary,$x.merge,Ox.omap,Hx.pairs,Dx.set,Eu.intTime,Eu.floatTime,Eu.timestamp];Mm.schema=qx});var ev=P(Pu=>{"use strict";var Um=Oi(),Fx=Zo(),Km=Hi(),Lx=Gn(),Bx=iu(),xu=au(),Cu=su(),Vx=Sm(),Mx=Cm(),Ym=du(),Qn=zo(),Xm=mu(),Qm=os(),zm=Wm(),Zm=Nu(),hs=ku(),Jm=new Map([["core",Vx.schema],["failsafe",[Um.map,Km.seq,Lx.string]],["json",Mx.schema],["yaml11",zm.schema],["yaml-1.1",zm.schema]]),Gm={binary:Ym.binary,bool:Bx.boolTag,float:xu.float,floatExp:xu.floatExp,floatNaN:xu.floatNaN,floatTime:hs.floatTime,int:Cu.int,intHex:Cu.intHex,intOct:Cu.intOct,intTime:hs.intTime,map:Um.map,merge:Qn.merge,null:Fx.nullTag,omap:Xm.omap,pairs:Qm.pairs,seq:Km.seq,set:Zm.set,timestamp:hs.timestamp},Wx={"tag:yaml.org,2002:binary":Ym.binary,"tag:yaml.org,2002:merge":Qn.merge,"tag:yaml.org,2002:omap":Xm.omap,"tag:yaml.org,2002:pairs":Qm.pairs,"tag:yaml.org,2002:set":Zm.set,"tag:yaml.org,2002:timestamp":hs.timestamp};function zx(e,t,r){let i=Jm.get(t);if(i&&!e)return r&&!i.includes(Qn.merge)?i.concat(Qn.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Jm.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(Qn.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Gm[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Gm).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Pu.coreKnownTags=Wx;Pu.getTags=zx});var Au=P(tv=>{"use strict";var Ru=W(),Jx=Oi(),Gx=Hi(),Ux=Gn(),ms=ev(),Kx=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,_u=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ms.getTags(t,"compat"):t?ms.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?ms.coreKnownTags:{},this.tags=ms.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Ru.MAP,{value:Jx.map}),Object.defineProperty(this,Ru.SCALAR,{value:Ux.string}),Object.defineProperty(this,Ru.SEQ,{value:Gx.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Kx:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};tv.Schema=_u});var iv=P(rv=>{"use strict";var Yx=W(),Iu=Wn(),Zn=Ln();function Xx(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Iu.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Zn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Yx.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Zn.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Iu.stringify(e.contents,n,()=>s=null,c);s&&(l+=Zn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Iu.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
59
|
-
`)?(r.push("..."),r.push(
|
|
58
|
+
${a.comment}`:i.comment}i=n}e.items[r]=Ls.isPair(i)?i:new td.Pair(i)}}else t("Expected a sequence for this tag");return e}function Bv(e,t,r){let{replacer:i}=r,n=new ZC.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(td.createPair(s,c,r))}return n}var eR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Dv,createNode:Bv};qs.createPairs=Bv;qs.pairs=eR;qs.resolvePairs=Dv});var nd=R(id=>{"use strict";var Fv=z(),rd=Rr(),ba=jr(),tR=$r(),Lv=Ms(),mi=class e extends tR.YAMLSeq{constructor(){super(),this.add=ba.YAMLMap.prototype.add.bind(this),this.delete=ba.YAMLMap.prototype.delete.bind(this),this.get=ba.YAMLMap.prototype.get.bind(this),this.has=ba.YAMLMap.prototype.has.bind(this),this.set=ba.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(Fv.isPair(n)?(a=rd.toJS(n.key,"",r),o=rd.toJS(n.value,a,r)):a=rd.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=Lv.createPairs(t,r,i),a=new this;return a.items=n.items,a}};mi.tag="tag:yaml.org,2002:omap";var rR={collection:"seq",identify:e=>e instanceof Map,nodeClass:mi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Lv.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Fv.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new mi,r)},createNode:(e,t,r)=>mi.from(e,t,r)};id.YAMLOMap=mi;id.omap=rR});var zv=R(ad=>{"use strict";var qv=pe();function Mv({value:e,source:t},r){return t&&(e?Vv:Wv).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Vv={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 qv.Scalar(!0),stringify:Mv},Wv={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 qv.Scalar(!1),stringify:Mv};ad.falseTag=Wv;ad.trueTag=Vv});var Gv=R(Vs=>{"use strict";var iR=pe(),od=en(),nR={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:od.stringifyNumber},aR={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():od.stringifyNumber(e)}},oR={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 iR.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:od.stringifyNumber};Vs.float=oR;Vs.floatExp=aR;Vs.floatNaN=nR});var Uv=R(Sa=>{"use strict";var Jv=en(),ka=e=>typeof e=="bigint"||Number.isInteger(e);function Ws(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 sd(e,t,r){let{value:i}=e;if(ka(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Jv.stringifyNumber(e)}var sR={identify:ka,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Ws(e,2,2,r),stringify:e=>sd(e,2,"0b")},cR={identify:ka,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Ws(e,1,8,r),stringify:e=>sd(e,8,"0")},lR={identify:ka,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Ws(e,0,10,r),stringify:Jv.stringifyNumber},uR={identify:ka,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Ws(e,2,16,r),stringify:e=>sd(e,16,"0x")};Sa.int=lR;Sa.intBin=sR;Sa.intHex=uR;Sa.intOct=cR});var ld=R(cd=>{"use strict";var Js=z(),zs=Ir(),Gs=jr(),vi=class e extends Gs.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Js.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new zs.Pair(t.key,null):r=new zs.Pair(t,null),Gs.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Gs.findPair(this.items,t);return!r&&Js.isPair(i)?Js.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=Gs.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new zs.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(zs.createPair(o,null,i));return a}};vi.tag="tag:yaml.org,2002:set";var dR={collection:"map",identify:e=>e instanceof Set,nodeClass:vi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>vi.from(e,t,r),resolve(e,t){if(Js.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new vi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};cd.YAMLSet=vi;cd.set=dR});var dd=R(Us=>{"use strict";var pR=en();function ud(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 Kv(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return pR.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 fR={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})=>ud(e,r),stringify:Kv},hR={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=>ud(e,!1),stringify:Kv},Yv={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(Yv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=ud(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Us.floatTime=hR;Us.intTime=fR;Us.timestamp=Yv});var Zv=R(Qv=>{"use strict";var mR=Qi(),vR=Os(),gR=Zi(),wR=ya(),yR=ed(),Xv=zv(),pd=Gv(),Ks=Uv(),NR=Rs(),bR=nd(),kR=Ms(),SR=ld(),fd=dd(),ER=[mR.map,gR.seq,wR.string,vR.nullTag,Xv.trueTag,Xv.falseTag,Ks.intBin,Ks.intOct,Ks.int,Ks.intHex,pd.floatNaN,pd.floatExp,pd.float,yR.binary,NR.merge,bR.omap,kR.pairs,SR.set,fd.intTime,fd.floatTime,fd.timestamp];Qv.schema=ER});var lg=R(vd=>{"use strict";var ig=Qi(),xR=Os(),ng=Zi(),CR=ya(),RR=Gu(),hd=Uu(),md=Yu(),PR=Tv(),_R=Ov(),ag=ed(),Ea=Rs(),og=nd(),sg=Ms(),eg=Zv(),cg=ld(),Ys=dd(),tg=new Map([["core",PR.schema],["failsafe",[ig.map,ng.seq,CR.string]],["json",_R.schema],["yaml11",eg.schema],["yaml-1.1",eg.schema]]),rg={binary:ag.binary,bool:RR.boolTag,float:hd.float,floatExp:hd.floatExp,floatNaN:hd.floatNaN,floatTime:Ys.floatTime,int:md.int,intHex:md.intHex,intOct:md.intOct,intTime:Ys.intTime,map:ig.map,merge:Ea.merge,null:xR.nullTag,omap:og.omap,pairs:sg.pairs,seq:ng.seq,set:cg.set,timestamp:Ys.timestamp},AR={"tag:yaml.org,2002:binary":ag.binary,"tag:yaml.org,2002:merge":Ea.merge,"tag:yaml.org,2002:omap":og.omap,"tag:yaml.org,2002:pairs":sg.pairs,"tag:yaml.org,2002:set":cg.set,"tag:yaml.org,2002:timestamp":Ys.timestamp};function IR(e,t,r){let i=tg.get(t);if(i&&!e)return r&&!i.includes(Ea.merge)?i.concat(Ea.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(tg.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(Ea.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?rg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(rg).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}vd.coreKnownTags=AR;vd.getTags=IR});var yd=R(ug=>{"use strict";var gd=z(),TR=Qi(),jR=Zi(),$R=ya(),Xs=lg(),OR=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,wd=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Xs.getTags(t,"compat"):t?Xs.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Xs.coreKnownTags:{},this.tags=Xs.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,gd.MAP,{value:TR.map}),Object.defineProperty(this,gd.SCALAR,{value:$R.string}),Object.defineProperty(this,gd.SEQ,{value:jR.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?OR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};ug.Schema=wd});var pg=R(dg=>{"use strict";var HR=z(),Nd=va(),xa=pa();function DR(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Nd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(xa.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(HR.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(xa.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Nd.stringify(e.contents,n,()=>s=null,c);s&&(l+=xa.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Nd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
59
|
+
`)?(r.push("..."),r.push(xa.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(xa.indentComment(a(c),"")))}return r.join(`
|
|
60
60
|
`)+`
|
|
61
|
-
`}
|
|
61
|
+
`}dg.stringifyDocument=DR});var Ca=R(fg=>{"use strict";var BR=ua(),tn=gs(),it=z(),FR=Ir(),LR=Rr(),qR=yd(),MR=pg(),bd=fs(),VR=xu(),WR=da(),kd=Eu(),Sd=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,it.NODE_TYPE,{value:it.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 kd.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,{[it.NODE_TYPE]:{value:it.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=it.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){rn(this.contents)&&this.contents.add(t)}addIn(t,r){rn(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=bd.anchorNames(this);t.anchor=!r||i.has(r)?bd.findNewAnchor(r||"a",i):r}return new BR.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=b=>typeof b=="number"||b instanceof String||b 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:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:f}=bd.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},h=WR.createNode(t,u,m);return s&&it.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new FR.Pair(n,a)}delete(t){return rn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return tn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):rn(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return it.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return tn.isEmptyPath(t)?!r&&it.isScalar(this.contents)?this.contents.value:this.contents:it.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return it.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return tn.isEmptyPath(t)?this.contents!==void 0:it.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=tn.collectionFromPath(this.schema,[t],r):rn(this.contents)&&this.contents.set(t,r)}setIn(t,r){tn.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=tn.collectionFromPath(this.schema,Array.from(t),r):rn(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 kd.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 kd.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 qR.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},c=LR.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?VR.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return MR.stringifyDocument(this,t)}};function rn(e){if(it.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}fg.Document=Sd});var _a=R(Pa=>{"use strict";var Ra=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Ed=class extends Ra{constructor(t,r,i){super("YAMLParseError",t,r,i)}},xd=class extends Ra{constructor(t,r,i){super("YAMLWarning",t,r,i)}},zR=(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)+`…
|
|
62
62
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
63
63
|
|
|
64
64
|
${o}
|
|
65
65
|
${l}
|
|
66
|
-
`}};
|
|
67
|
-
`))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(
|
|
68
|
-
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||
|
|
69
|
-
`+
|
|
70
|
-
`+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&
|
|
71
|
-
`+
|
|
72
|
-
`+y.comment:E.comment=y.comment);let O=new
|
|
73
|
-
`+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}
|
|
74
|
-
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,g]=o[h];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",
|
|
75
|
-
`;for(let h=u;h<s;++h){let[v,g]=o[h];l+=v.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&v.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(b?2:1),"BAD_INDENT",N),v=""}a===
|
|
76
|
-
`):v.length>c||g[0]===" "?(
|
|
77
|
-
`:!p
|
|
78
|
-
`&&(
|
|
66
|
+
`}};Pa.YAMLError=Ra;Pa.YAMLParseError=Ed;Pa.YAMLWarning=xd;Pa.prettifyError=zR});var Aa=R(hg=>{"use strict";function GR(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",p="",f=!1,m=!1,h=null,v=null,g=null,b=null,k=null,N=null,x=null;for(let E of e)switch(m&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&a(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&E.type!=="comment"&&E.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),u=!0;break;case"comment":{u||a(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";d?d+=p+y:d=y,p="",l=!1;break}case"newline":l?d?d+=E.source:(!N||r!=="seq-item-ind")&&(c=!0):p+=E.source,l=!0,f=!0,(v||g)&&(b=E),u=!0;break;case"anchor":v&&a(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&a(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=E,x??(x=E.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(E,"MULTIPLE_TAGS","A node can have at most one tag"),g=E,x??(x=E.offset),l=!1,u=!1,m=!0;break}case r:(v||g)&&a(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),N&&a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),N=E,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=E,l=!1,u=!1;break}default:a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,u=!1}let w=e[e.length-1],S=w?w.offset+w.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:N,spaceBefore:c,comment:d,hasNewline:f,anchor:v,tag:g,newlineAfterProp:b,end:S,start:x??S}}hg.resolveProps=GR});var Qs=R(mg=>{"use strict";function Cd(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
67
|
+
`))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(Cd(t.key)||Cd(t.value))return!0}return!1;default:return!0}}mg.containsNewline=Cd});var Rd=R(vg=>{"use strict";var JR=Qs();function UR(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&JR.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}vg.flowIndentCheck=UR});var Pd=R(wg=>{"use strict";var gg=z();function KR(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||gg.isScalar(a)&&gg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}wg.mapIncludes=KR});var Eg=R(Sg=>{"use strict";var yg=Ir(),YR=jr(),Ng=Aa(),XR=Qs(),bg=Rd(),QR=Pd(),kg="All mapping items must start at the same column";function ZR({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??YR.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:p,sep:f,value:m}=u,h=Ng.resolveProps(d,{indicator:"explicit-key-ind",next:p??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(p&&(p.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==i.indent&&n(c,"BAD_INDENT",kg)),!h.anchor&&!h.tag&&!f){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
68
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||XR.containsNewline(p))&&n(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",kg);r.atKey=!0;let g=h.end,b=p?e(r,p,h,n):t(r,g,d,null,h,n);r.schema.compat&&bg.flowIndentCheck(i.indent,p,n),r.atKey=!1,QR.mapIncludes(r,s.items,b)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let k=Ng.resolveProps(f??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=m?e(r,m,k,n):t(r,c,f,null,k,n);r.schema.compat&&bg.flowIndentCheck(i.indent,m,n),c=N.range[2];let x=new yg.Pair(b,N);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
|
|
69
|
+
`+k.comment:b.comment=k.comment);let N=new yg.Pair(b);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Sg.resolveBlockMap=ZR});var Cg=R(xg=>{"use strict";var eP=$r(),tP=Aa(),rP=Rd();function iP({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??eP.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let p=tP.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?n(p.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(s.comment=p.comment);continue}let f=d?e(r,d,p,n):t(r,p.end,u,null,p,n);r.schema.compat&&rP.flowIndentCheck(i.indent,d,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}xg.resolveBlockSeq=iP});var nn=R(Rg=>{"use strict";function nP(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Rg.resolveEnd=nP});var Ig=R(Ag=>{"use strict";var aP=z(),oP=Ir(),Pg=jr(),sP=$r(),cP=nn(),_g=Aa(),lP=Qs(),uP=Pd(),_d="Block collections are not allowed within flow collections",Ad=e=>e&&(e.type==="block-map"||e.type==="block-seq");function dP({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Pg.YAMLMap:sP.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:b,key:k,sep:N,value:x}=g,w=_g.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:k??N?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!N&&!x){v===0&&w.comma?n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),w.comment&&(l.comment?l.comment+=`
|
|
70
|
+
`+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&lP.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)w.comma&&n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(w.comma||n(w.start,"MISSING_CHAR",`Missing , between ${s} items`),w.comment){let S="";e:for(let E of b)switch(E.type){case"comma":case"space":break;case"comment":S=E.source.substring(1);break e;default:break e}if(S){let E=l.items[l.items.length-1];aP.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
|
|
71
|
+
`+S:E.comment=S,w.comment=w.comment.substring(S.length+1)}}if(!o&&!N&&!w.found){let S=x?e(r,x,w,n):t(r,w.end,N,null,w,n);l.items.push(S),d=S.range[2],Ad(x)&&n(S.range,"BLOCK_IN_FLOW",_d)}else{r.atKey=!0;let S=w.end,E=k?e(r,k,w,n):t(r,S,b,null,w,n);Ad(k)&&n(E.range,"BLOCK_IN_FLOW",_d),r.atKey=!1;let y=_g.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:x,offset:E.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(y.found){if(!o&&!w.found&&r.options.strict){if(N)for(let T of N){if(T===y.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<y.found.offset-1024&&n(y.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(y.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=x?e(r,x,y,n):y.found?t(r,y.end,N,null,y,n):null;C?Ad(x)&&n(C.range,"BLOCK_IN_FLOW",_d):y.comment&&(E.comment?E.comment+=`
|
|
72
|
+
`+y.comment:E.comment=y.comment);let O=new oP.Pair(E,C);if(r.options.keepSourceTokens&&(O.srcToken=g),o){let T=l;uP.mapIncludes(r,T.items,E)&&n(S,"DUPLICATE_KEY","Map keys must be unique"),T.items.push(O)}else{let T=new Pg.YAMLMap(r.schema);T.flow=!0,T.items.push(O);let Q=(C??E).range;T.range=[E.range[0],Q[1],Q[2]],l.items.push(T)}d=C?C.range[2]:y.end}}let p=o?"}":"]",[f,...m]=i.end,h=d;if(f?.source===p)h=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${p}`:`${v} in block collection must be sufficiently indented and end with a ${p}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",g),f&&f.source.length!==1&&m.unshift(f)}if(m.length>0){let v=cP.resolveEnd(m,h,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
|
|
73
|
+
`+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}Ag.resolveFlowCollection=dP});var jg=R(Tg=>{"use strict";var pP=z(),fP=pe(),hP=jr(),mP=$r(),vP=Eg(),gP=Cg(),wP=Ig();function Id(e,t,r,i,n,a){let o=r.type==="block-map"?vP.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?gP.resolveBlockSeq(e,t,r,i,a):wP.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 yP(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,p=>n(a,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:f}=i,m=p&&a?p.offset>a.offset?p:a:p??a;m&&(!f||f.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===hP.YAMLMap.tagName&&s==="map"||o===mP.YAMLSeq.tagName&&s==="seq")return Id(e,t,r,n,o);let c=t.schema.tags.find(p=>p.tag===o&&p.collection===s);if(!c){let p=t.schema.knownTags[o];if(p?.collection===s)t.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?n(a,"BAD_COLLECTION_TYPE",`${p.tag} used for ${s} collection, but expects ${p.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Id(e,t,r,n,o)}let l=Id(e,t,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),t.options)??l,d=pP.isNode(u)?u:new fP.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Tg.composeCollection=yP});var jd=R($g=>{"use strict";var Td=pe();function NP(e,t,r){let i=t.offset,n=bP(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Td.Scalar.BLOCK_FOLDED:Td.Scalar.BLOCK_LITERAL,o=t.source?kP(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
74
|
+
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,g]=o[h];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",p="",f=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
|
|
75
|
+
`;for(let h=u;h<s;++h){let[v,g]=o[h];l+=v.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&v.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(b?2:1),"BAD_INDENT",N),v=""}a===Td.Scalar.BLOCK_LITERAL?(d+=p+v.slice(c)+g,p=`
|
|
76
|
+
`):v.length>c||g[0]===" "?(p===" "?p=`
|
|
77
|
+
`:!f&&p===`
|
|
78
|
+
`&&(p=`
|
|
79
79
|
|
|
80
|
-
`),d+=
|
|
81
|
-
`,
|
|
80
|
+
`),d+=p+v.slice(c)+g,p=`
|
|
81
|
+
`,f=!0):g===""?p===`
|
|
82
82
|
`?d+=`
|
|
83
|
-
`:
|
|
84
|
-
`:(d+=
|
|
83
|
+
`:p=`
|
|
84
|
+
`:(d+=p+g,p=" ",f=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
|
|
85
85
|
`+o[h][0].slice(c);d[d.length-1]!==`
|
|
86
86
|
`&&(d+=`
|
|
87
87
|
`);break;default:d+=`
|
|
88
|
-
`}let m=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function
|
|
88
|
+
`}let m=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function bP({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="",c=-1;for(let p=1;p<n.length;++p){let f=n[p];if(!s&&(f==="-"||f==="+"))s=f;else{let m=Number(f);!o&&m?o=m:c===-1&&(c=e+p)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let p=1;p<t.length;++p){let f=t[p];switch(f.type){case"space":l=!0;case"newline":d+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),d+=f.source.length;break;default:{let m=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",m);let h=f.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function kP(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}$g.resolveBlockScalar=NP});var Od=R(Hg=>{"use strict";var $d=pe(),SP=nn();function EP(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(p,f,m)=>r(i+p,f,m);switch(n){case"scalar":s=$d.Scalar.PLAIN,c=xP(a,l);break;case"single-quoted-scalar":s=$d.Scalar.QUOTE_SINGLE,c=CP(a,l);break;case"double-quoted-scalar":s=$d.Scalar.QUOTE_DOUBLE,c=RP(a,l);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=SP.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function xP(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}`),Og(e)}function CP(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Og(e.slice(1,-1)).replace(/''/g,"'")}function Og(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
89
89
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
90
90
|
`,"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===`
|
|
91
91
|
`?n+=a:a=`
|
|
92
|
-
`:(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
|
|
92
|
+
`:(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 RP(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
|
|
93
93
|
`))if(n===`
|
|
94
|
-
`){let{fold:a,offset:o}=
|
|
94
|
+
`){let{fold:a,offset:o}=PP(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=_P[a];if(o)r+=o;else if(a===`
|
|
95
95
|
`)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
|
|
96
|
-
`)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+=
|
|
96
|
+
`)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+=AP(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!==`
|
|
97
97
|
`&&!(o==="\r"&&e[i+2]===`
|
|
98
|
-
`)&&(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
|
|
98
|
+
`)&&(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 PP(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
|
|
99
99
|
`||i==="\r")&&!(i==="\r"&&e[t+2]!==`
|
|
100
100
|
`);)i===`
|
|
101
101
|
`&&(r+=`
|
|
102
|
-
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var
|
|
103
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
102
|
+
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var _P={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
103
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function AP(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}}Hg.resolveFlowScalar=EP});var Fg=R(Bg=>{"use strict";var gi=z(),Dg=pe(),IP=jd(),TP=Od();function jP(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?IP.resolveBlockScalar(e,t,i):TP.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[gi.SCALAR]:c?l=$P(e.schema,n,c,r,i):t.type==="scalar"?l=OP(e,n,t,i):l=e.schema[gi.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??t,"TAG_RESOLVE_FAILED",p),e.options);u=gi.isScalar(d)?d:new Dg.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",p),u=new Dg.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function $P(e,t,r,i,n){if(r==="!")return e[gi.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[gi.SCALAR])}function OP({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[gi.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[gi.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Bg.composeScalar=jP});var qg=R(Lg=>{"use strict";function HP(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}Lg.emptyScalarPosition=HP});var Wg=R(Dd=>{"use strict";var DP=ua(),BP=z(),FP=jg(),Mg=Fg(),LP=nn(),qP=qg(),MP={composeNode:Vg,composeEmptyNode:Hd};function Vg(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=VP(e,t,i),(s||c)&&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":l=Mg.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=FP.composeCollection(MP,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Hd(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!BP.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Hd(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:qP.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Mg.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function VP({options:e},{offset:t,source:r,end:i},n){let a=new DP.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=LP.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Dd.composeEmptyNode=Hd;Dd.composeNode=Vg});var Jg=R(Gg=>{"use strict";var WP=Ca(),zg=Wg(),zP=nn(),GP=Aa();function JP(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new WP.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=GP.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?zg.composeNode(l,n,u,o):zg.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=zP.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}Gg.composeDoc=JP});var Fd=R(Yg=>{"use strict";var UP=ns("process"),KP=Eu(),YP=Ca(),Ia=_a(),Ug=z(),XP=Jg(),QP=nn();function Ta(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 Kg(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?`
|
|
104
104
|
|
|
105
105
|
`:`
|
|
106
|
-
`)+(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
|
|
107
|
-
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(
|
|
106
|
+
`)+(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 Bd=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Ta(r);a?this.warnings.push(new Ia.YAMLWarning(o,i,n)):this.errors.push(new Ia.YAMLParseError(o,i,n))},this.directives=new KP.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Kg(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
107
|
+
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Ug.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ug.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
|
|
108
108
|
${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
|
|
109
|
-
${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:
|
|
110
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
109
|
+
${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:Kg(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(UP.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Ta(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=XP.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 Ia.YAMLParseError(Ta(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 Ia.YAMLParseError(Ta(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=QP.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}
|
|
110
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Ia.YAMLParseError(Ta(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 YP.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}}};Yg.Composer=Bd});var Zg=R(Zs=>{"use strict";var ZP=jd(),e_=Od(),t_=_a(),Xg=ma();function r_(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 t_.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return e_.resolveFlowScalar(e,t,i);case"block-scalar":return ZP.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function i_(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Xg.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
|
|
111
111
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
112
112
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
113
|
-
`,
|
|
114
|
-
`}),{type:"block-scalar",offset:a,indent:i,props:
|
|
113
|
+
`,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Qg(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
|
|
114
|
+
`}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function n_(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 l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Xg.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":a_(e,c);break;case'"':Ld(e,c,"double-quoted-scalar");break;case"'":Ld(e,c,"single-quoted-scalar");break;default:Ld(e,c,"scalar")}}function a_(e,t){let r=t.indexOf(`
|
|
115
115
|
`),i=t.substring(0,r),n=t.substring(r+1)+`
|
|
116
|
-
`;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}];
|
|
117
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function
|
|
118
|
-
`};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})}}}
|
|
116
|
+
`;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}];Qg(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
117
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Qg(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 Ld(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:`
|
|
118
|
+
`};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})}}}Zs.createScalarToken=i_;Zs.resolveAsScalar=r_;Zs.setScalarValue=n_});var tw=R(ew=>{"use strict";var o_=e=>"type"in e?tc(e):ec(e);function tc(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=tc(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=ec(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=ec(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=ec(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 ec({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=tc(t)),r)for(let a of r)n+=a.source;return i&&(n+=tc(i)),n}ew.stringify=o_});var aw=R(nw=>{"use strict";var qd=Symbol("break visit"),s_=Symbol("skip children"),rw=Symbol("remove item");function wi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),iw(Object.freeze([]),e,t)}wi.BREAK=qd;wi.SKIP=s_;wi.REMOVE=rw;wi.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};wi.parentCollection=(e,t)=>{let r=wi.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 iw(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=iw(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===qd)return qd;s===rw&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}nw.visit=wi});var rc=R(Me=>{"use strict";var Md=Zg(),c_=tw(),l_=aw(),Vd="\uFEFF",Wd="",zd="",Gd="",u_=e=>!!e&&"items"in e,d_=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function p_(e){switch(e){case Vd:return"<BOM>";case Wd:return"<DOC>";case zd:return"<FLOW_END>";case Gd:return"<SCALAR>";default:return JSON.stringify(e)}}function f_(e){switch(e){case Vd:return"byte-order-mark";case Wd:return"doc-mode";case zd:return"flow-error-end";case Gd:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
119
119
|
`:case`\r
|
|
120
|
-
`: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}
|
|
121
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
122
|
-
\r `),
|
|
120
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Me.createScalarToken=Md.createScalarToken;Me.resolveAsScalar=Md.resolveAsScalar;Me.setScalarValue=Md.setScalarValue;Me.stringify=c_.stringify;Me.visit=l_.visit;Me.BOM=Vd;Me.DOCUMENT=Wd;Me.FLOW_END=zd;Me.SCALAR=Gd;Me.isCollection=u_;Me.isScalar=d_;Me.prettyToken=p_;Me.tokenType=f_});var Kd=R(sw=>{"use strict";var ja=rc();function Nt(e){switch(e){case void 0:case" ":case`
|
|
121
|
+
`:case"\r":case" ":return!0;default:return!1}}var ow=new Set("0123456789ABCDEFabcdef"),h_=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ic=new Set(",[]{}"),m_=new Set(` ,[]{}
|
|
122
|
+
\r `),Jd=e=>!e||m_.has(e),Ud=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===`
|
|
123
123
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
124
124
|
`:!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===`
|
|
125
125
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
126
|
-
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&
|
|
127
|
-
`,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]===
|
|
126
|
+
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Nt(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(`
|
|
127
|
+
`,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]===ja.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 ja.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==="...")&&Nt(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&&!Nt(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===":")&&Nt(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(Jd),"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("..."))&&Nt(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield ja.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(Jd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Nt(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(`
|
|
128
128
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
129
|
-
`,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=>
|
|
129
|
+
`,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=>Nt(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`
|
|
130
130
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
131
131
|
`)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(`
|
|
132
132
|
`,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===`
|
|
133
133
|
`;)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===`
|
|
134
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield
|
|
134
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield ja.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(Nt(a)||t&&ic.has(a))break;r=i}else if(Nt(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
135
135
|
`?(i+=1,n=`
|
|
136
|
-
`,a=this.buffer[i+1]):r=i),a==="#"||t&&
|
|
137
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&
|
|
136
|
+
`,a=this.buffer[i+1]):r=i),a==="#"||t&&ic.has(a))break;if(n===`
|
|
137
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&ic.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ja.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(Jd),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Nt(i)||r&&ic.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(;!Nt(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(h_.has(r))r=this.buffer[++t];else if(r==="%"&&ow.has(this.buffer[t+1])&&ow.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===`
|
|
138
138
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
139
|
-
`?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)}};
|
|
139
|
+
`?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)}};sw.Lexer=Ud});var Xd=R(cw=>{"use strict";var Yd=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}}}};cw.LineCounter=Yd});var Zd=R(fw=>{"use strict";var v_=ns("process"),lw=rc(),g_=Kd();function Or(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function uw(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 pw(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 nc(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 an(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 ac(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 dw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Or(t.start,"explicit-key-ind")&&!Or(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,pw(t.value)?t.value.end?ac(t.value.end,t.sep):t.value.end=t.sep:ac(t.start,t.sep),delete t.sep)}var Qd=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 g_.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,v_.env.LOG_TOKENS&&console.log("|",lw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=lw.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"&&dw(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&&uw(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":{uw(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=nc(this.peek(2)),i=an(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(`
|
|
140
140
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
141
|
-
`,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)){
|
|
141
|
+
`,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)){ac(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 c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":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(Or(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(pw(r.key)&&!Or(r.sep,"newline")){let o=an(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Or(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=an(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]}):Or(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&&!Or(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)){ac(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||Or(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=nc(i),a=an(n);dw(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(`
|
|
142
142
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
143
|
-
`,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=ks(t),i=Bi(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=ks(t),i=Bi(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())}}};ng.Parser=ld});var lg=P(la=>{"use strict";var ag=Yu(),jP=ea(),ca=ia(),TP=Ul(),$P=W(),OP=cd(),og=ud();function sg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new OP.LineCounter||null,prettyErrors:t}}function HP(e,t={}){let{lineCounter:r,prettyErrors:i}=sg(t),n=new og.Parser(r?.addNewLine),a=new ag.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(ca.prettifyError(e,r)),s.warnings.forEach(ca.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function cg(e,t={}){let{lineCounter:r,prettyErrors:i}=sg(t),n=new og.Parser(r?.addNewLine),a=new ag.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 ca.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(ca.prettifyError(e,r)),o.warnings.forEach(ca.prettifyError(e,r))),o}function DP(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=cg(e,r);if(!n)return null;if(n.warnings.forEach(a=>TP.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 qP(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 $P.isDocument(e)&&!i?e.toString(r):new jP.Document(e,i,r).toString(r)}la.parse=DP;la.parseAllDocuments=HP;la.parseDocument=cg;la.stringify=qP});var It=P(G=>{"use strict";var FP=Yu(),LP=ea(),BP=Au(),dd=ia(),VP=qn(),Er=W(),MP=yr(),WP=ue(),zP=br(),JP=kr(),GP=Ns(),UP=od(),KP=cd(),YP=ud(),Es=lg(),ug=$n();G.Composer=FP.Composer;G.Document=LP.Document;G.Schema=BP.Schema;G.YAMLError=dd.YAMLError;G.YAMLParseError=dd.YAMLParseError;G.YAMLWarning=dd.YAMLWarning;G.Alias=VP.Alias;G.isAlias=Er.isAlias;G.isCollection=Er.isCollection;G.isDocument=Er.isDocument;G.isMap=Er.isMap;G.isNode=Er.isNode;G.isPair=Er.isPair;G.isScalar=Er.isScalar;G.isSeq=Er.isSeq;G.Pair=MP.Pair;G.Scalar=WP.Scalar;G.YAMLMap=zP.YAMLMap;G.YAMLSeq=JP.YAMLSeq;G.CST=GP;G.Lexer=UP.Lexer;G.LineCounter=KP.LineCounter;G.Parser=YP.Parser;G.parse=Es.parse;G.parseAllDocuments=Es.parseAllDocuments;G.parseDocument=Es.parseDocument;G.stringify=Es.stringify;G.visit=ug.visit;G.visitAsync=ug.visitAsync});import fd from"path";function ZP(e){return e.toLowerCase().startsWith(".env")}function jt(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>ZP(i))?"environment-file":r.some(i=>QP.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>XP.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function pd(e,t){let r=jt(t);if(r)return r;let i=fd.resolve(e.projectRoot,...t.split("/")),n=fd.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===fd.resolve(e.configFile)?"native-runtime":null}var XP,QP,ua=I(()=>{"use strict";XP=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),QP=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function xr(e){return e!==0&&e!==0n&&e!=="0"}function Je(e,t){return xr(e.dev)&&xr(t.dev)&&xr(e.ino)&&xr(t.ino)}function z(e,t){let r=xr(e.dev)&&xr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=xr(e.ino)&&xr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var da=I(()=>{"use strict"});var Tt=I(()=>{"use strict";da()});import{createHash as eR}from"node:crypto";import{promises as pt}from"node:fs";import Ze from"node:path";import{TextDecoder as tR}from"node:util";function hd(e,t){let r=Ze.relative(e,t);return r===""||!Ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ze.sep}`)}function rR(e){let t=Ze.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})||Ze.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=jt(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 iR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function nR(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xs(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function dg(e){let t=await pt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await pt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function aR(e,t){let r=Ze.resolve(e),i=Ze.resolve(t);if(!hd(r,i))throw new Error("Native artifact path is outside its root");let n=[await dg(r)],a=r;for(let o of Ze.relative(r,i).split(Ze.sep).filter(Boolean)){a=Ze.join(a,o);let s=await dg(a);if(!hd(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function fg(e){for(let t of e){let r=await pt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!nR(t,r)||await pt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ee(e){let t=rR(e.ref),r=e.maxBytes===null?null:iR(e.maxBytes??md),i=Ze.resolve(e.root,...t.split("/")),n=await aR(e.root,Ze.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await pt.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 pt.realpath(i);if(!hd(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await pt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),pt.lstat(i),pt.realpath(i)]);if(await fg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!xs(a,c)||!xs(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let S=r===null?p.length:r+1-f,N=await s.read(p,0,Math.min(p.length,S),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),pt.lstat(i),pt.realpath(i)]);if(await fg(n),!h.isFile()||h.isSymbolicLink()||v!==o||!xs(c,m)||!xs(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),b;try{b=new tR("utf-8",{fatal:!0}).decode(g)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:e.includeHash===!1?null:eR("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var md,et=I(()=>{"use strict";ua();Tt();md=1024*1024});import{promises as gd}from"node:fs";async function wd(e,t){let r;for(let i=0;i<=vd.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===vd.length||!oR.has(a??""))throw n;await new Promise(o=>setTimeout(o,vd[i]))}throw r}async function yd(e,t){await wd(()=>gd.rename(e,t),`rename ${t}`)}async function Nd(e){await wd(()=>gd.unlink(e),`unlink ${e}`)}async function bd(e,t){await wd(()=>gd.link(e,t),`link ${t}`)}var oR,vd,kd=I(()=>{"use strict";oR=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),vd=[50,100,200]});import{randomUUID as sR}from"crypto";import{promises as Ae}from"fs";import ht from"path";function Cs(e,t){let r=ht.relative(e,t);return r===""||!ht.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ht.sep}`)}function cR(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ps(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function lR(e,t){return Ps(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pg(e){let t=await Ae.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 Ae.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Vi(e){for(let t of e){let r=await Ae.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!cR(t,r)||await Ae.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function uR(e,t,r){let[i,n]=await Promise.all([Ae.lstat(e),Ae.realpath(e),r?Vi(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Ps(i,t)||r&&!Cs(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function dR(e,t){let r=ht.resolve(e),i=ht.resolve(t);if(!Cs(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await pg(r)],a=ht.relative(r,i).split(ht.sep).filter(Boolean),o=r;for(let s of a){await Vi(n),o=ht.join(o,s);try{await Ae.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await pg(o);if(!Cs(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Vi(n),n}async function fR(e){let t;try{t=await Ae.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 pR(e,t,r={}){let i=ht.dirname(e),n=r.containedRoot?await dR(r.containedRoot,i):null;n||await Ae.mkdir(i,{recursive:!0});let a=ht.join(i,`.${ht.basename(e)}.${sR()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Ae.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Ae.lstat(a),Ae.realpath(a)]);if(await Vi(n),!l.isFile()||l.isSymbolicLink()||!Ps(s,l)||!Cs(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Ps(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await uR(a,c,n),await r.beforeCommit?.(),n){await Vi(n);let l=await Ae.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!lR(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await bd(a,e),await Nd(a)):await yd(a,e),await fR(i)}catch(l){if(await o?.close(),!n)await Ae.rm(a,{force:!0});else try{await Vi(n),await Ae.rm(a,{force:!0})}catch{}throw l}}async function $t(e,t,r={}){await pR(e,t,r)}async function Fe(e,t,r={}){await $t(e,JSON.stringify(t,null,2)+`
|
|
144
|
-
`,r)}var
|
|
143
|
+
`,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=nc(t),i=an(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=nc(t),i=an(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())}}};fw.Parser=Qd});var ww=R(Oa=>{"use strict";var hw=Fd(),w_=Ca(),$a=_a(),y_=Du(),N_=z(),b_=Xd(),mw=Zd();function vw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new b_.LineCounter||null,prettyErrors:t}}function k_(e,t={}){let{lineCounter:r,prettyErrors:i}=vw(t),n=new mw.Parser(r?.addNewLine),a=new hw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach($a.prettifyError(e,r)),s.warnings.forEach($a.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function gw(e,t={}){let{lineCounter:r,prettyErrors:i}=vw(t),n=new mw.Parser(r?.addNewLine),a=new hw.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 $a.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach($a.prettifyError(e,r)),o.warnings.forEach($a.prettifyError(e,r))),o}function S_(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=gw(e,r);if(!n)return null;if(n.warnings.forEach(a=>y_.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 E_(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 N_.isDocument(e)&&!i?e.toString(r):new w_.Document(e,i,r).toString(r)}Oa.parse=S_;Oa.parseAllDocuments=k_;Oa.parseDocument=gw;Oa.stringify=E_});var Bt=R(U=>{"use strict";var x_=Fd(),C_=Ca(),R_=yd(),ep=_a(),P_=ua(),Hr=z(),__=Ir(),A_=pe(),I_=jr(),T_=$r(),j_=rc(),$_=Kd(),O_=Xd(),H_=Zd(),oc=ww(),yw=oa();U.Composer=x_.Composer;U.Document=C_.Document;U.Schema=R_.Schema;U.YAMLError=ep.YAMLError;U.YAMLParseError=ep.YAMLParseError;U.YAMLWarning=ep.YAMLWarning;U.Alias=P_.Alias;U.isAlias=Hr.isAlias;U.isCollection=Hr.isCollection;U.isDocument=Hr.isDocument;U.isMap=Hr.isMap;U.isNode=Hr.isNode;U.isPair=Hr.isPair;U.isScalar=Hr.isScalar;U.isSeq=Hr.isSeq;U.Pair=__.Pair;U.Scalar=A_.Scalar;U.YAMLMap=I_.YAMLMap;U.YAMLSeq=T_.YAMLSeq;U.CST=j_;U.Lexer=$_.Lexer;U.LineCounter=O_.LineCounter;U.Parser=H_.Parser;U.parse=oc.parse;U.parseAllDocuments=oc.parseAllDocuments;U.parseDocument=oc.parseDocument;U.stringify=oc.stringify;U.visit=yw.visit;U.visitAsync=yw.visitAsync});import tp from"path";function F_(e){return e.toLowerCase().startsWith(".env")}function Ft(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>F_(i))?"environment-file":r.some(i=>B_.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>D_.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function rp(e,t){let r=Ft(t);if(r)return r;let i=tp.resolve(e.projectRoot,...t.split("/")),n=tp.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===tp.resolve(e.configFile)?"native-runtime":null}var D_,B_,Ha=I(()=>{"use strict";D_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),B_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Dr(e){return e!==0&&e!==0n&&e!=="0"}function Xe(e,t){return Dr(e.dev)&&Dr(t.dev)&&Dr(e.ino)&&Dr(t.ino)}function G(e,t){let r=Dr(e.dev)&&Dr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Dr(e.ino)&&Dr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Da=I(()=>{"use strict"});var Lt=I(()=>{"use strict";Da()});import{createHash as L_}from"node:crypto";import{promises as bt}from"node:fs";import nt from"node:path";import{TextDecoder as q_}from"node:util";function ip(e,t){let r=nt.relative(e,t);return r===""||!nt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${nt.sep}`)}function M_(e){let t=nt.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})||nt.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=Ft(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 V_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function W_(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function sc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Nw(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function z_(e,t){let r=nt.resolve(e),i=nt.resolve(t);if(!ip(r,i))throw new Error("Native artifact path is outside its root");let n=[await Nw(r)],a=r;for(let o of nt.relative(r,i).split(nt.sep).filter(Boolean)){a=nt.join(a,o);let s=await Nw(a);if(!ip(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function bw(e){for(let t of e){let r=await bt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!W_(t,r)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=M_(e.ref),r=e.maxBytes===null?null:V_(e.maxBytes??np),i=nt.resolve(e.root,...t.split("/")),n=await z_(e.root,nt.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await bt.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 bt.realpath(i);if(!ip(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await bt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),bt.lstat(i),bt.realpath(i)]);if(await bw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!sc(a,c)||!sc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],p=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?f.length:r+1-p,N=await s.read(f,0,Math.min(f.length,k),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(f.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),bt.lstat(i),bt.realpath(i)]);if(await bw(n),!h.isFile()||h.isSymbolicLink()||v!==o||!sc(c,m)||!sc(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),b;try{b=new q_("utf-8",{fatal:!0}).decode(g)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:p,hash:e.includeHash===!1?null:L_("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var np,at=I(()=>{"use strict";Ha();Lt();np=1024*1024});import{promises as op}from"node:fs";async function sp(e,t){let r;for(let i=0;i<=ap.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===ap.length||!G_.has(a??""))throw n;await new Promise(o=>setTimeout(o,ap[i]))}throw r}async function cp(e,t){await sp(()=>op.rename(e,t),`rename ${t}`)}async function lp(e){await sp(()=>op.unlink(e),`unlink ${e}`)}async function up(e,t){await sp(()=>op.link(e,t),`link ${t}`)}var G_,ap,dp=I(()=>{"use strict";G_=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),ap=[50,100,200]});import{randomUUID as J_}from"crypto";import{promises as $e}from"fs";import kt from"path";function cc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function U_(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function lc(e,t){return G({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function K_(e,t){return lc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function kw(e){let t=await $e.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 $e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function on(e){for(let t of e){let r=await $e.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!U_(t,r)||await $e.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Y_(e,t,r){let[i,n]=await Promise.all([$e.lstat(e),$e.realpath(e),r?on(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!lc(i,t)||r&&!cc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function X_(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!cc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await kw(r)],a=kt.relative(r,i).split(kt.sep).filter(Boolean),o=r;for(let s of a){await on(n),o=kt.join(o,s);try{await $e.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await kw(o);if(!cc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await on(n),n}async function Q_(e){let t;try{t=await $e.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 Z_(e,t,r={}){let i=kt.dirname(e),n=r.containedRoot?await X_(r.containedRoot,i):null;n||await $e.mkdir(i,{recursive:!0});let a=kt.join(i,`.${kt.basename(e)}.${J_()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await $e.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([$e.lstat(a),$e.realpath(a)]);if(await on(n),!l.isFile()||l.isSymbolicLink()||!lc(s,l)||!cc(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!lc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Y_(a,c,n),await r.beforeCommit?.(),n){await on(n);let l=await $e.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!K_(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await up(a,e),await lp(a)):await cp(a,e),await Q_(i)}catch(l){if(await o?.close(),!n)await $e.rm(a,{force:!0});else try{await on(n),await $e.rm(a,{force:!0})}catch{}throw l}}async function qt(e,t,r={}){await Z_(e,t,r)}async function Oe(e,t,r={}){await qt(e,JSON.stringify(t,null,2)+`
|
|
144
|
+
`,r)}var oe=I(()=>{"use strict";dp();Lt()});function rA(e,t){return pp[e][t]}function uc(e){return Sw.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ew(e){return fp.get(e.trim().toLocaleLowerCase("en-US"))??null}function dc(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${rA(e,i)}
|
|
145
145
|
`).join(`
|
|
146
|
-
`)}var Sd,hR,mR,hg,Ed,oi=I(()=>{"use strict";Sd={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:"验证预期"}},hR={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:"结论"}},mR={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:"结论"}},hg=new Map,Ed=new Map;for(let e of Object.keys(Sd)){for(let[t,r]of Object.entries(Sd[e]))hg.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(hR[e]))Ed.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(mR[e]))Ed.set(r.toLocaleLowerCase("en-US"),t)}});import Cr from"path";function bR(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Cr.posix.isAbsolute(r)||Cr.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 si(e){let t=bR(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Sg(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 Ts(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||Cr.posix.isAbsolute(i)||Cr.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 Xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Eg(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 $s(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>Is)throw new Error(`${t} exceeds ${Is} 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>js)throw new Error(`${t} contains more than ${js} wildcard tokens`);return e}function Ng(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=>$s(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function fa(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 bg(e,t,r){let i=fa(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 kR(e){if(e===void 0)return{...Ie,include:[...Ie.include],exclude:[...Ie.exclude]};let t=Xt(e,"native.snapshot");return{include:Ng(t.include,"native.snapshot.include",Ie.include),exclude:Ng(t.exclude,"native.snapshot.exclude",Ie.exclude),max_files:fa(t.max_files,Ie.max_files,"native.snapshot.max_files"),max_total_bytes:fa(t.max_total_bytes,Ie.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:fa(t.max_duration_ms,Ie.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:fa(t.max_selection_records,Ie.max_selection_records,"native.snapshot.max_selection_records")}}function SR(e){if(e===void 0)return;let t=Xt(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=Xt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:si(i),toArtifactRoot:si(n),stage:a,...o?{cleanup:o}:{}}}function ER(e){if(e===void 0)return;let t=Xt(e,"native.finish");if(t.pull_request===void 0)return{};let r=Xt(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(Cr.posix.isAbsolute(i[0])||Cr.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??gR;if(!Number.isSafeInteger(n)||n<1||n>yg)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${yg}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function xR(e,t={}){let r=Xt(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??Cd;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=SR(r.pending_root_move),l=ER(r.finish);return{artifact_root:si(i),language:Eg(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:kR(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function CR(e){let t=Xt(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:Sg(t.artifact_layout),language:Eg(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function PR(e){let r=Xt(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)=>Ts(i,`hook.allow_paths[${n}]`)))]}}function RR(e){if(e===void 0)return{...As};let t=Xt(e,"memory"),r=t.learning??As.learning,i=t.retrieval??As.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 Pd(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _R(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")||Cr.posix.isAbsolute(r)||Cr.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>vg)throw new Error(`${t} exceeds ${vg} 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>gg)throw new Error(`${t} contains more than ${gg} wildcard tokens`);return r}function AR(e){let t=Pd(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)=>_R(n,`knowledge.local.include[${a}]`)))],max_file_mb:bg(t.max_file_mb,wg.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:bg(t.max_total_mb,wg.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 IR(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 jR(e){let t=Pd(e,"knowledge.remote"),r=IR(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 TR(e){if(e===void 0)return{...kg};let t=Pd(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:AR(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:jR(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 $R(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function OR(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function ha(e,t={}){let r=(0,xd.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=$R(n.ambient_resume),o=n.hook===void 0?void 0:PR(n.hook),s=RR(n.memory),c=TR(n.knowledge),l=n.native===void 0?void 0:xR(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:CR(n.classic),d=OR(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Os(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...As},knowledge:{...kg},native:{artifact_root:si(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Cd,snapshot:{...Ie,include:[...Ie.include],exclude:[...Ie.exclude]}}}}var xd,pa,Is,js,vg,gg,Cd,As,wg,kg,gR,yg,wR,yR,NR,Ie,Pr=I(()=>{"use strict";xd=Gt(It(),1),pa=Number.MAX_SAFE_INTEGER,Is=1024,js=64,vg=1024,gg=64,Cd=5,As={learning:!0,retrieval:!0},wg={include:[],max_file_mb:1,max_total_mb:32},kg={provider:"local"},gR=12e4,yg=6e5,wR=[".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/**"],yR=["**/.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"],NR=[...wR,...yR].sort((e,t)=>e.localeCompare(t,"en")),Ie={include:["**/*"],exclude:[...NR],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as Hs,promises as ci}from"fs";function Rd(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function xg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ma(e){return{dev:e.dev,ino:e.ino,birthtime:Rd(e)}}function Ds(e,t){let r=ma(e),i=ma(t);return Je(r,i)?z(r,i):z(r,i)&&Rd(e)===Rd(t)&&xg(e)===xg(t)&&e.size===t.size}async function li(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 ci.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new mt("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new mt("too-large",`${i} exceeds ${t} bytes`);let o=await ci.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ma(a)});let s=process.platform==="win32"?Hs.O_RDONLY:Hs.O_RDONLY|Hs.O_NOFOLLOW|Hs.O_NONBLOCK,c;try{c=await ci.open(e,s)}catch(l){throw l.code==="ELOOP"?new mt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),ci.lstat(e,{bigint:n}),ci.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ds(a,l)||!Ds(a,u))throw new mt("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ma(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-p,{bytesRead:S}=await c.read(m,0,Math.min(m.length,b),null);if(S===0)break;if(p+=S,p>t)throw new mt("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,S)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),ci.lstat(e,{bigint:n}),ci.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Ds(a,h)||!Ds(a,v))throw new mt("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:ma(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:g}}finally{await c.close()}}var mt,va=I(()=>{"use strict";da();mt=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as qs}from"fs";import Rr from"path";function HR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function _d(e,t){let r=Rr.relative(e,t);return r===""||!Rr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Rr.sep}`)}async function Cg(e,t){let r=Rr.resolve(e),i=await qs.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return qs.realpath(r)}async function Pg(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Rr.join(n,r[a]);let o;try{o=await qs.lstat(n)}catch(u){if(HR(u))return{exists:!1,kind:"missing"};throw u}let s=Rr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await qs.realpath(n);if(!_d(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Mi(e,t,r){let i=Ts(t,r.label),n=Rr.resolve(e),a=await Cg(n,r.label),o=i.split("/"),s=Rr.resolve(n,...o);if(!_d(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Pg(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Qt(e,t,r,i){let n=await Mi(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 Cg(n.projectRoot,i.label);return li(n.target,r,{...i,verify:async(o,s)=>{if(!_d(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Pg(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var _r=I(()=>{"use strict";va();Pr()});import{createHash as DR}from"crypto";function qR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Fs(e,t={}){return(await Ls(e,t)).document}async function FR(e){try{return(await Qt(e,ga,pa,{label:ga})).bytes}catch(t){if(qR(t))return null;throw t}}function LR(e){return e?{exists:!0,sha256:DR("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Ls(e,t={}){let r=await FR(e);return{document:r?ha(r.toString("utf8"),t):null,identity:LR(r)}}async function Ad(e){return(await Fs(e))?.config??null}var ga,Wi=I(()=>{"use strict";Pr();_r();ga=".comet/config.yaml"});var zi=I(()=>{"use strict";kd();da()});var qF,Id=I(()=>{"use strict";zi();Wi();_r();qF=16*1024});var $d=I(()=>{"use strict";zi();Pr();Wi();_r();Id()});import{existsSync as _g,promises as Ar}from"fs";import q from"path";import zR from"os";async function Od(e){try{return await Ar.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function GR(e){try{let t=await Ar.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Gi(e,t){let r=q.relative(e,t);return r===""||!q.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${q.sep}`)}async function Ji(e){let t=[],r=e;for(;!await Od(r);){let n=q.dirname(r);if(n===r)break;t.push(q.basename(r)),r=n}let i=await Ar.realpath(r);return q.resolve(i,...t.reverse())}async function Hd(e){try{return(await Ar.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Vs(e){let t=q.resolve(e);try{(await Ar.stat(t)).isDirectory()||(t=q.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=q.resolve(zR.homedir());for(;;){if(!(t===i&&r!==i)){let o=q.join(t,...Bs.split("/")),s=t===r||await GR(o);if(await Od(o)&&s)return t}if(await Od(q.join(t,".git")))return t;let a=q.dirname(t);if(a===t)return r;t=a}}function Ms(e){return si(e)}async function UR(e,t){let r=Ms(t),i=q.resolve(e,...r.split("/")),n=await Ar.realpath(e),a=await Ji(i);if(!Gi(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ot(e,t){let r=Ms(t),i=await UR(e,r),n=q.join(i,"comet");if(await Hd(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ji(i),Ji(n)]);if(!Gi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=q.resolve(e),c=q.join(s,".comet","runtime","native");if(await Hd(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ar.realpath(s),Ji(c)]);if(!Gi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:q.join(e,...Bs.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:q.join(n,"specs"),changesDir:q.join(n,"changes"),archiveDir:q.join(n,"archive"),runtimeDir:c,changesRuntimeDir:q.join(c,"changes"),locksDir:q.join(c,"locks"),transactionsDir:q.join(c,"transactions")}}function Dd(e){if(!JR.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vt(e,t){Dd(t);let r=q.join(e.changesRuntimeDir,t);if(!B(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Ig(e,t){Dd(t);let r=q.join(e.changesDir,t,"runtime");if(!B(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function K(e,t){let r=vt(e,t);if(_g(r))return r;let i=Ig(e,t);return _g(i)?i:r}function ya(e,t){Dd(t);let r=q.join(e.changesDir,t),i=K(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:q.join(r,"brief.md"),childrenPath:q.join(r,"children.yaml"),specsDir:q.join(r,"specs"),verificationPath:q.join(r,"verification.md"),statePath:q.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:q.join(i,"state.json")}}async function Ag(e){try{let t=await Ar.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function qd(e,t){let r=vt(e,t),i=Ig(e,t),[n,a]=await Promise.all([Ag(r),Ag(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Ir(e,t){if(!t.startsWith("runtime/")||q.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=q.resolve(e,...t.slice(8).split("/"));if(!B(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function we(e,t){let r=q.resolve(t);if(B(e.runtimeDir,r))return e.runtimeDir;if(B(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function B(e,t){return Gi(q.resolve(e),q.resolve(t))}async function V(e,t){let r=q.resolve(e),i=q.resolve(t);if(!Gi(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Hd(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ji(r),Ji(i)]);if(!Gi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Bs,JR,U=I(()=>{"use strict";Pr();Bs=".comet/config.yaml",JR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function YR(e="docs",t="en"){return Os(e,t)}async function ke(e){let t=(await Fs(e))?.config??null;return t?.native?t:null}async function zs(e){let t=await ke(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 jg(e){let t=await Vs(e.startPath),r=await ke(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Bs} 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?Ms(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??YR(i??"docs"),a=await Ot(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Fd,Ws,Ge=I(()=>{"use strict";Pr();Wi();$d();le();U();Fd=Ie,Ws=$s});import{existsSync as XR}from"node:fs";import Na from"node:path";function Tg(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function ZR(e){let t=(Tg(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function e_(e,t,r){let n=Na.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Tg(t,"PATH")??"").split(Na.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Na.win32.extname(e)?[e]:ZR(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Na.join(s,c):Na.resolve(r,c)))}function Ld(e,t,r){return e_(e,t,r).find(i=>XR(i))??e}function Bd(e){if(e.some(t=>QR.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var QR,sL,Js=I(()=>{"use strict";QR=/[&|<>()^%"!\r\n]/u,sL=["$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 t_}from"node:child_process";import $g from"node:path";function n_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function Ui(e,t,r={}){let i=r.timeoutMs??r_,n=r.maxBufferBytes??i_;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=$g.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Ld(e,o,a):e,c=$g.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Bd(t);try{return t_(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"&&l})}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Vd(e,t,d,{cause:u,timedOut:n_(u)})}}var r_,i_,Vd,Gs=I(()=>{"use strict";Js();r_=6e4,i_=8*1024*1024,Vd=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 Og}from"node:fs";import Hg from"node:path";function s_(e){let t=Wd.get(e);if(!t)return;let r=t.value===null?o_:a_;if(Date.now()-t.at>r){Wd.delete(e);return}return t.value}async function ba(e){if(e===process.pid&&Md!==null)return Md;let t=s_(e);if(t!==void 0)return t;let r=await c_(e);return e===process.pid&&r!==null&&(Md=r),e!==process.pid&&Wd.set(e,{value:r,at:Date.now()}),r}async function c_(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Og.readFile(`/proc/${e}/stat`,"utf8"),Og.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 u_(e);if(process.platform==="darwin"){let t=Ui("/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 l_(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function u_(e){try{let n=Ui(Hg.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=Hg.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=Ui(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return l_(i)}function Us(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function zd(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 ba(e);return r===t?"alive":r===null||Us(r)!==Us(t)&&Dg.has(Us(r))&&Dg.has(Us(t))?"unknown":"dead"}var Md,a_,o_,Wd,Dg,Ks=I(()=>{"use strict";Gs();Md=null,a_=6e4,o_=1e4,Wd=new Map;Dg=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as d_}from"async_hooks";import{randomUUID as Lg}from"crypto";import{promises as tt}from"fs";import Bg from"os";import de from"path";function h_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function m_(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 Vg(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 Xs(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Je(r,i)?z(r,i):z(r,i)&&e.size===t.size}function Qs(e,t){return Xs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function v_(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&&Qs(e.identity,t.identity)}async function gt(e){let t,r;try{let i=await li(e,qg,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof mt?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${qg} 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:m_(JSON.parse(t.toString("utf8")),e),identity:Vg(r)}}async function g_(e){return(await gt(e))?.owner??null}async function Gd(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Bg.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await zd(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function w_(e,t){try{await tt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await tt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Zs(e,t){let r=await gt(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Qs(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await tt.mkdir(t,{recursive:!0});let i=de.join(t,`${de.basename(e.file)}.${e.owner.id}.${Lg()}.removed`);try{await tt.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await gt(i);if(!n||n.owner.id!==e.owner.id||!Xs(n.identity,e.identity))throw await w_(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await tt.rm(i,{force:!0}),"removed"}async function Mg(e){let t=await ba(process.pid);return{id:Lg(),pid:process.pid,hostname:Bg.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Wg(e,t){let r;try{r=await tt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await g_(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 pp,eA,tA,Sw,fp,yi=I(()=>{"use strict";pp={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:"验证预期"}},eA={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:"结论"}},tA={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:"结论"}},Sw=new Map,fp=new Map;for(let e of Object.keys(pp)){for(let[t,r]of Object.entries(pp[e]))Sw.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(eA[e]))fp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(tA[e]))fp.set(r.toLocaleLowerCase("en-US"),t)}});import Br from"path";function sA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Br.posix.isAbsolute(r)||Br.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 Ni(e){let t=sA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Tw(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 mc(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||Br.posix.isAbsolute(i)||Br.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 sr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function jw(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 vc(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>fc)throw new Error(`${t} exceeds ${fc} 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>hc)throw new Error(`${t} contains more than ${hc} wildcard tokens`);return e}function _w(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=>vc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Ba(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 Aw(e,t,r){let i=Ba(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 cA(e){if(e===void 0)return{...He,include:[...He.include],exclude:[...He.exclude]};let t=sr(e,"native.snapshot");return{include:_w(t.include,"native.snapshot.include",He.include),exclude:_w(t.exclude,"native.snapshot.exclude",He.exclude),max_files:Ba(t.max_files,He.max_files,"native.snapshot.max_files"),max_total_bytes:Ba(t.max_total_bytes,He.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ba(t.max_duration_ms,He.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Ba(t.max_selection_records,He.max_selection_records,"native.snapshot.max_selection_records")}}function lA(e){if(e===void 0)return;let t=sr(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=sr(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:Ni(i),toArtifactRoot:Ni(n),stage:a,...o?{cleanup:o}:{}}}function uA(e){if(e===void 0)return;let t=sr(e,"native.finish");if(t.pull_request===void 0)return{};let r=sr(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(Br.posix.isAbsolute(i[0])||Br.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??iA;if(!Number.isSafeInteger(n)||n<1||n>Pw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Pw}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function dA(e,t={}){let r=sr(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??mp;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=lA(r.pending_root_move),l=uA(r.finish);return{artifact_root:Ni(i),language:jw(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:cA(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function pA(e){let t=sr(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:Tw(t.artifact_layout),language:jw(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function fA(e){let r=sr(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)=>mc(i,`hook.allow_paths[${n}]`)))]}}function hA(e){if(e===void 0)return{...pc};let t=sr(e,"memory"),r=t.learning??pc.learning,i=t.retrieval??pc.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 vp(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mA(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")||Br.posix.isAbsolute(r)||Br.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>xw)throw new Error(`${t} exceeds ${xw} 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>Cw)throw new Error(`${t} contains more than ${Cw} wildcard tokens`);return r}function vA(e){let t=vp(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)=>mA(n,`knowledge.local.include[${a}]`)))],max_file_mb:Aw(t.max_file_mb,Rw.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Aw(t.max_total_mb,Rw.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 gA(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 wA(e){let t=vp(e,"knowledge.remote"),r=gA(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 yA(e){if(e===void 0)return{...Iw};let t=vp(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:vA(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:wA(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 NA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function bA(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(p=>p!=="native"&&p!=="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 La(e,t={}){let r=(0,hp.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=NA(n.ambient_resume),o=n.hook===void 0?void 0:fA(n.hook),s=hA(n.memory),c=yA(n.knowledge),l=n.native===void 0?void 0:dA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:pA(n.classic),d=bA(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function gc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...pc},knowledge:{...Iw},native:{artifact_root:Ni(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:mp,snapshot:{...He,include:[...He.include],exclude:[...He.exclude]}}}}var hp,Fa,fc,hc,xw,Cw,mp,pc,Rw,Iw,iA,Pw,nA,aA,oA,He,Fr=I(()=>{"use strict";hp=ir(Bt(),1),Fa=Number.MAX_SAFE_INTEGER,fc=1024,hc=64,xw=1024,Cw=64,mp=5,pc={learning:!0,retrieval:!0},Rw={include:[],max_file_mb:1,max_total_mb:32},Iw={provider:"local"},iA=12e4,Pw=6e5,nA=[".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/**"],aA=["**/.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"],oA=[...nA,...aA].sort((e,t)=>e.localeCompare(t,"en")),He={include:["**/*"],exclude:[...oA],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as wc,promises as bi}from"fs";function gp(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function $w(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function qa(e){return{dev:e.dev,ino:e.ino,birthtime:gp(e)}}function yc(e,t){let r=qa(e),i=qa(t);return Xe(r,i)?G(r,i):G(r,i)&&gp(e)===gp(t)&&$w(e)===$w(t)&&e.size===t.size}async function ki(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 bi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new St("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new St("too-large",`${i} exceeds ${t} bytes`);let o=await bi.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:qa(a)});let s=process.platform==="win32"?wc.O_RDONLY:wc.O_RDONLY|wc.O_NOFOLLOW|wc.O_NONBLOCK,c;try{c=await bi.open(e,s)}catch(l){throw l.code==="ELOOP"?new St("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),bi.lstat(e,{bigint:n}),bi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!yc(a,l)||!yc(a,u))throw new St("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:qa(l)}),await r.hooks?.afterOpen?.();let p=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-f,{bytesRead:k}=await c.read(m,0,Math.min(m.length,b),null);if(k===0)break;if(f+=k,f>t)throw new St("too-large",`${i} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),bi.lstat(e,{bigint:n}),bi.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!yc(a,h)||!yc(a,v))throw new St("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:qa(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:g}}finally{await c.close()}}var St,Ma=I(()=>{"use strict";Da();St=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Nc}from"fs";import Lr from"path";function kA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function wp(e,t){let r=Lr.relative(e,t);return r===""||!Lr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Lr.sep}`)}async function Ow(e,t){let r=Lr.resolve(e),i=await Nc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Nc.realpath(r)}async function Hw(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Lr.join(n,r[a]);let o;try{o=await Nc.lstat(n)}catch(u){if(kA(u))return{exists:!1,kind:"missing"};throw u}let s=Lr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Nc.realpath(n);if(!wp(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function sn(e,t,r){let i=mc(t,r.label),n=Lr.resolve(e),a=await Ow(n,r.label),o=i.split("/"),s=Lr.resolve(n,...o);if(!wp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Hw(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Mt(e,t,r,i){let n=await sn(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 Ow(n.projectRoot,i.label);return ki(n.target,r,{...i,verify:async(o,s)=>{if(!wp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Hw(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var cr=I(()=>{"use strict";Ma();Fr()});import{createHash as SA}from"crypto";function EA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function bc(e,t={}){return(await kc(e,t)).document}async function xA(e){try{return(await Mt(e,Va,Fa,{label:Va})).bytes}catch(t){if(EA(t))return null;throw t}}function CA(e){return e?{exists:!0,sha256:SA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function kc(e,t={}){let r=await xA(e);return{document:r?La(r.toString("utf8"),t):null,identity:CA(r)}}async function yp(e){return(await bc(e))?.config??null}var Va,cn=I(()=>{"use strict";Fr();cr();Va=".comet/config.yaml"});var ln=I(()=>{"use strict";dp();Da()});var B1,Np=I(()=>{"use strict";ln();cn();cr();B1=16*1024});var Sp=I(()=>{"use strict";ln();Fr();cn();cr();Np()});import{existsSync as Bw,promises as qr}from"fs";import B from"path";import IA from"os";async function Ep(e){try{return await qr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jA(e){try{let t=await qr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function dn(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function un(e){let t=[],r=e;for(;!await Ep(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await qr.realpath(r);return B.resolve(i,...t.reverse())}async function xp(e){try{return(await qr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ec(e){let t=B.resolve(e);try{(await qr.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(IA.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...Sc.split("/")),s=t===r||await jA(o);if(await Ep(o)&&s)return t}if(await Ep(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function xc(e){return Ni(e)}async function $A(e,t){let r=xc(t),i=B.resolve(e,...r.split("/")),n=await qr.realpath(e),a=await un(i);if(!dn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Vt(e,t){let r=xc(t),i=await $A(e,r),n=B.join(i,"comet");if(await xp(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([un(i),un(n)]);if(!dn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=B.resolve(e),c=B.join(s,".comet","runtime","native");if(await xp(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([qr.realpath(s),un(c)]);if(!dn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...Sc.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:B.join(n,"specs"),changesDir:B.join(n,"changes"),archiveDir:B.join(n,"archive"),runtimeDir:c,changesRuntimeDir:B.join(c,"changes"),locksDir:B.join(c,"locks"),transactionsDir:B.join(c,"transactions")}}function Cp(e){if(!TA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Et(e,t){Cp(t);let r=B.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Lw(e,t){Cp(t);let r=B.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Y(e,t){let r=Et(e,t);if(Bw(r))return r;let i=Lw(e,t);return Bw(i)?i:r}function za(e,t){Cp(t);let r=B.join(e.changesDir,t),i=Y(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:B.join(r,"brief.md"),childrenPath:B.join(r,"children.yaml"),specsDir:B.join(r,"specs"),verificationPath:B.join(r,"verification.md"),statePath:B.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:B.join(i,"state.json")}}async function Fw(e){try{let t=await qr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Rp(e,t){let r=Et(e,t),i=Lw(e,t),[n,a]=await Promise.all([Fw(r),Fw(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Mr(e,t){if(!t.startsWith("runtime/")||B.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=B.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ne(e,t){let r=B.resolve(t);if(q(e.runtimeDir,r))return e.runtimeDir;if(q(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function q(e,t){return dn(B.resolve(e),B.resolve(t))}async function V(e,t){let r=B.resolve(e),i=B.resolve(t);if(!dn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await xp(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([un(r),un(i)]);if(!dn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Sc,TA,K=I(()=>{"use strict";Fr();Sc=".comet/config.yaml",TA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function HA(e="docs",t="en"){return gc(e,t)}async function xe(e){let t=(await bc(e))?.config??null;return t?.native?t:null}async function Rc(e){let t=await xe(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 qw(e){let t=await Ec(e.startPath),r=await xe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Sc} 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?xc(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??HA(i??"docs"),a=await Vt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Pp,Cc,Qe=I(()=>{"use strict";Fr();cn();Sp();oe();K();Pp=He,Cc=vc});import{createHash as Ap,randomUUID as DA}from"node:crypto";import{promises as Ze}from"node:fs";import BA from"node:os";import Ve from"node:path";async function _p(e,t){let r=await Ze.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await Ze.readFile(e),n=await Ze.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 Ww(e){try{let t=JSON.parse((await _p(Ve.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=Ve.join(e,t.file),i=await _p(r,65536);return Ap("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function qA(e,t){let r,i=DA(),n=Ve.join(e,`probe-${i}.cs`),a=Ve.join(e,`probe-${i}.exe`),o=Ve.join(e,`probe-${i}.json`);try{if(await Ze.mkdir(e,{recursive:!0,mode:448}),(await Ze.lstat(e)).isSymbolicLink())return null;r=await Ze.open(Ve.join(e,"prepare.lock"),"wx",384);let s=await Ww(e);if(s)return s;await Ze.writeFile(n,Vw,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=Ve.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await Ze.access(d),c=d;break}catch{}}if(!c)return null;await Er(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=Ap("sha256").update(await _p(a,65536)).digest("hex");return await Ze.writeFile(o,JSON.stringify({file:Ve.basename(a),hash:l}),{flag:"wx",mode:384}),await Ze.rename(o,Ve.join(e,"probe.json")),a}catch{return null}finally{await Ze.unlink(n).catch(()=>{}),await Ze.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await Ze.unlink(Ve.join(e,"prepare.lock")).catch(()=>{}))}}async function Mw(e,t,r){try{let i=await Er(Ve.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 Er(Ve.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 MA(e,t){let r=Pc.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:qA(e,t),retryAfter:1/0};return Pc.set(e,i),i.promise.then(n=>{Pc.get(e)===i&&(n?Pc.delete(e):i.retryAfter=performance.now()+LA)}),i.promise}async function zw(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=Ve.join(t.cacheRoot??Ve.join(BA.tmpdir(),"comet-process-identity"),FA),n=async l=>{if(!l)return null;try{let d=(await Er(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await Ww(i);if(a){let l=await n(a);return l||Mw(e,r,new AbortController().signal)}let o=MA(i,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(n).then(c),Mw(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Vw,FA,LA,Pc,Gw=I(()=>{"use strict";Ji();Vw=`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
|
+
}`,FA=Ap("sha256").update(Vw).digest("hex"),LA=1e4,Pc=new Map});import{promises as Jw}from"node:fs";function WA(e){let t=Tp.get(e);if(t){if(Date.now()-t.at>VA){Tp.delete(e);return}return t.value}}async function Ga(e){if(e===process.pid&&Ip!==null)return Ip;let t=WA(e);if(t!==void 0)return t;let r=_c.get(e);r||(r=zA(e),_c.set(e,r));let i=await r;return _c.get(e)===r&&_c.delete(e),e===process.pid&&i!==null&&(Ip=i),i===null&&Tp.set(e,{value:null,at:Date.now()}),i}async function zA(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Jw.readFile(`/proc/${e}/stat`,"utf8"),Jw.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 zw(e);if(process.platform==="darwin"){let t=(await Er("/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 Ac(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function jp(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 Ga(e);return r===t?"alive":r===null||Ac(r)!==Ac(t)&&Uw.has(Ac(r))&&Uw.has(Ac(t))?"unknown":"dead"}var Ip,VA,Tp,_c,Uw,Ic=I(()=>{"use strict";Ji();Gw();Ip=null,VA=1e4,Tp=new Map,_c=new Map;Uw=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as GA}from"async_hooks";import{randomUUID as Xw}from"crypto";import{promises as ot}from"fs";import Qw from"os";import fe from"path";function KA(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function YA(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 Zw(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 jc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Xe(r,i)?G(r,i):G(r,i)&&e.size===t.size}function Ja(e,t){return jc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function XA(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&&Ja(e.identity,t.identity)}async function st(e){let t,r;try{let i=await ki(e,Kw,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof St?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Kw} 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:YA(JSON.parse(t.toString("utf8")),e),identity:Zw(r)}}async function QA(e){return(await st(e))?.owner??null}async function Op(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Qw.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await jp(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function ZA(e,t){try{await ot.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ot.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function $c(e,t){let r=await st(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ja(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ot.mkdir(t,{recursive:!0});let i=fe.join(t,`${fe.basename(e.file)}.${e.owner.id}.${Xw()}.removed`);try{await ot.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await st(i);if(!n||n.owner.id!==e.owner.id||!jc(n.identity,e.identity))throw await ZA(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ot.rm(i,{force:!0}),"removed"}async function ey(e){let t=await Ga(process.pid);return{id:Xw(),pid:process.pid,hostname:Qw.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function ty(e,t){let r;try{r=await ot.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await QA(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=Zw(await r.stat({bigint:!0}))}finally{await r.close()}let n=await st(e);if(!i||!n||n.owner.id!==t.id||!jc(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function eI(e,t){let r=await V(e.runtimeDir,e.locksDir);await ot.mkdir(r,{recursive:!0});let i=await V(e.runtimeDir,fe.join(r,$p));await ot.mkdir(i,{recursive:!0});let n=await ey(t),a=fe.join(i,`.${n.id}.tmp`),o=fe.join(i,`${n.id}.claim`);try{let s=await ty(a,n);await ot.rename(a,o);let c=await st(o);if(!c||!jc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await ot.rm(a,{force:!0})}}async function tI(e){let t=fe.dirname(e.file),r=!1,i=fe.basename(e.file);for(let n of await ot.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=fe.join(t,n.name);if(fe.resolve(a)!==fe.resolve(e.file))try{let o=await st(a),s=await Op(o);if(s.status==="missing")continue;let c=await st(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Ja(c.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await $c(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function ry(e){let t=await st(e.file);if(t){if(t.owner.id!==e.owner.id||!Ja(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await $c(t,fe.dirname(e.file))}}async function rI(e,t){let r=Date.now()+JA;for(;;){let i=await eI(e,t);if(!await tI(i))return i;if(await ry(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 iI(e){let t=Tc.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Tc.set(e,n),await t,()=>{r(),Tc.get(e)===n&&Tc.delete(e)}}async function Hp(e,t,r){let i=fe.resolve(e.locksDir),n=Yw.getStore();if(n?.has(i))return r();let a=await iI(i);try{let o=await rI(e,t),s=new Map(n??[]);return s.set(i,o),await Yw.run(s,async()=>{try{return await r()}finally{await ry(o)}})}finally{a()}}async function Oc(e,t,r){return Hp(e,`acquire ${t}`,async()=>{let i=await V(e.runtimeDir,e.locksDir);await ot.mkdir(i,{recursive:!0});let n=await V(e.runtimeDir,fe.join(i,KA(t))),a=await ey(r),o=await ty(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Hc(e){await st(e.file)&&await Hp({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${fe.basename(e.file)}`,async()=>{let t=await st(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ja(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=fe.join(e.locksDir,$p);await $c(t,r)})}function nI(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 iy(e){return Op(await st(e))}async function ny(e,t,r,i={}){return Hp(e,`take over ${fe.basename(t)}`,async()=>{let n=await V(e.runtimeDir,e.locksDir),a=await V(e.runtimeDir,t);if(fe.resolve(fe.dirname(a))!==fe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await st(a),s=await Op(o);if(s.status==="missing")return{status:"missing"};if(r&&!XA(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&nI(o?.owner??null)>=UA;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=fe.join(n,$p);return await $c(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Kw,$p,JA,UA,Yw,Tc,Ua=I(()=>{"use strict";Ma();Ic();K();Lt();Kw=16*1024,$p=".coordinator",JA=5e3,UA=900*1e3,Yw=new GA,Tc=new Map});import{createHash as aI}from"node:crypto";function cy(e){return e.replaceAll(`\r
|
|
148
161
|
`,`
|
|
149
162
|
`).replaceAll("\r",`
|
|
150
|
-
`)}function R_(e){return E_("sha256").update(Xg(e)).digest("hex")}function Qd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new te(`${t} must be an object`);return e}function Qg(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new te(`${r} has unknown field(s): ${i.join(", ")}`)}function Zd(e,t){if(typeof e!="string"||e.trim().length===0)throw new te(`${t} must be a non-empty string`);return e.trim()}function Kg(e,t){if(e!==void 0){if(typeof e!="string")throw new te(`${t} must be text`);return Xg(e).replace(/^\n+|\n+$/gu,"")}}function rc(e,t){let r=Zd(e,t).toLowerCase();if(!P_.test(r))throw new te(`${t} must be a SHA-256 hash`);return r}function Yg(e,t,r){let i=Qd(e,t),n=Object.entries(i);if(n.length>Ug)throw new te(`${t} must contain at most ${Ug} entries`);let a={};for(let[o,s]of n){if(Yd(o,`${t} ID`)!==o)throw new te(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=rc(s,`${t}.${o}`)}return a}function Yd(e,t){let r=Zd(e,t);if(!C_.test(r))throw new te(`${t} is not a valid stable requirement ID`);return r}function __(e,t){let r=Zd(e,t);if(!x_.test(r))throw new te(`${t} is not a valid capability ID`);return r}function A_(e,t){let r=`Native delta operations[${t}]`,i=Qd(e,r);Qg(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Yd(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new te(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Yd(i.to_id,`${r}.to_id`),c=Kg(i.title,`${r}.title`),l=Kg(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:rc(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new te(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new te(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new te(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new te(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function I_(e){let t=Qd(e,"Native delta");if(Qg(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Kd)throw new te(`Native delta schema must be ${Kd}`);let r=__(t.capability,"Native delta capability"),i=rc(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new te("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:rc(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=Yg(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:Yg(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new te("Native delta operations must be an array");let s=t.operations.map(A_),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let f of d){if(c.has(f))throw new te(`Native delta operations contain duplicate or overlapping requirement ID ${f} at ${l}`);c.add(f)}}if(o!==void 0){if(a===void 0)throw new te("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new te(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new te(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:Kd,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 j_(e){let t=(0,Xd.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new te(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function ef(e){return I_(typeof e=="string"?j_(e):e)}function Sa(e){return R_(e)}var Xd,Kd,x_,C_,P_,Ug,te,tf=I(()=>{"use strict";Xd=Gt(It(),1),Kd="comet.native.delta.v1",x_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,C_=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,P_=/^[a-f0-9]{64}$/iu,Ug=512,te=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}}});var Ht,Zt,er,Ki,Yi,Ea,xa=I(()=>{"use strict";Ht="comet.native.v3",Zt="comet.native.v2",er="comet.native.v1",Ki="comet.native.transition.v3",Yi="comet.native.transition.v2",Ea="comet.native.transition.v1"});import T_ from"node:path";function Pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function rw(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 ui(e){if(!tw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function iw(e){if(!tw.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function nw(e,t){if(e.length===0||T_.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function B_(e,t){let r=Pa(e,`spec_changes[${t}]`);if(rw(r,H_,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(iw(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"&&nw(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"||!nf.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"||!nf.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 V_(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 af(e,t){if(rw(e,t,Dt),typeof e.name!="string")throw new Error("Native change name is required");if(ui(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"||!D_.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&&!q_.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(B_),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"||!F_.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"&&nw(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!V_(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 di(e){let t=Pa(e,Dt);if(t.schema!==er)throw new Error(`Expected ${er}`);return{schema:er,...af(t,$_)}}function Ca(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rf(e,t,r){if(e===null)return null;let i=typeof e=="string"?L_.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 M_(e){if(e==null)return null;if(typeof e!="string"||!nf.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function W_(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 fi(e){let t=Pa(e,Dt);if(t.schema!==Zt)throw new Error(`Expected ${Zt}`);if(Ca(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Zt} minimum_runtime_version must be 2`);return{schema:Zt,minimum_runtime_version:2,revision:Ca(t.revision,"Native v2 revision"),...af(t,ew)}}function qt(e){let t=Pa(e,Dt);if(t.schema!==Ht){if(t.schema===er||t.schema===Zt){let o=t.schema===er?di(t):fi(t);throw new Xi(o.name,o.schema)}throw new tr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Ca(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new tr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Ca(t.revision,"Native revision"),n=af(t,O_),a=M_(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ht,minimum_runtime_version:3,revision:i,verification_protocol:W_(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:rf(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:rf(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:rf(t.partial_allowance,"Native partial_allowance","allowances")}}function ic(e){let t=Pa(e,Dt);if(t.schema===er){let n=di(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ht}`}}if(t.schema===Zt){let n=fi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ht}`}}if(t.schema!==Ht){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 tr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Ca(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new tr(t.schema,r).message};let i=qt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Zg,$_,ew,O_,H_,D_,q_,F_,Dt,nf,tw,L_,Xi,tr,nc=I(()=>{"use strict";xa();Zg=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],$_=new Set(Zg),ew=new Set([...Zg,"minimum_runtime_version","revision"]),O_=new Set([...ew,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),H_=new Set(["capability","operation","source","base_hash"]),D_=new Set(["shape","build","verify","archive"]),q_=new Set(["implicit","confirmed"]),F_=new Set(["pending","pass","fail"]),Dt="comet-state.yaml",nf=/^[a-f0-9]{64}$/u,tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,L_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Xi=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"},tr=class extends Error{constructor(r,i){super(r!==Ht||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"}});import aw from"node:path";function X_(e,t){return e<t?-1:e>t?1:0}function cw(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:r,truncated:!0}}function lw(e,t){let r=t.toString(36),i=T("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function Q_(e){if(!K_.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=Y_.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==T("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function Z_(e,t){let r=cw(e.text,rr.maxTextBytes),i=e.context.slice(0,rr.maxContextItems).map(n=>cw(n,rr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function dw(e){let t=Q_({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(X_),n=i.slice(0,rr.maxFailedCheckIds),a=e.criteria.slice(t,t+rr.maxItems);for(let c of a){let l=[...r,Z_(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?lw(e.acceptanceHash,u):null,limits:{...rr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>rr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?lw(e.acceptanceHash,o):null,limits:{...rr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>rr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function sf(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 of(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 uw(e){return e.includes("-->")||e.includes("--!>")}function*Qi(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
163
|
+
`)}function lI(e){return aI("sha256").update(cy(e)).digest("hex")}function Lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ie(`${t} must be an object`);return e}function ly(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new ie(`${r} has unknown field(s): ${i.join(", ")}`)}function qp(e,t){if(typeof e!="string"||e.trim().length===0)throw new ie(`${t} must be a non-empty string`);return e.trim()}function oy(e,t){if(e!==void 0){if(typeof e!="string")throw new ie(`${t} must be text`);return cy(e).replace(/^\n+|\n+$/gu,"")}}function Dc(e,t){let r=qp(e,t).toLowerCase();if(!cI.test(r))throw new ie(`${t} must be a SHA-256 hash`);return r}function sy(e,t,r){let i=Lp(e,t),n=Object.entries(i);if(n.length>ay)throw new ie(`${t} must contain at most ${ay} entries`);let a={};for(let[o,s]of n){if(Bp(o,`${t} ID`)!==o)throw new ie(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=Dc(s,`${t}.${o}`)}return a}function Bp(e,t){let r=qp(e,t);if(!sI.test(r))throw new ie(`${t} is not a valid stable requirement ID`);return r}function uI(e,t){let r=qp(e,t);if(!oI.test(r))throw new ie(`${t} is not a valid capability ID`);return r}function dI(e,t){let r=`Native delta operations[${t}]`,i=Lp(e,r);ly(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Bp(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new ie(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Bp(i.to_id,`${r}.to_id`),c=oy(i.title,`${r}.title`),l=oy(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:Dc(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new ie(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new ie(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new ie(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new ie(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function pI(e){let t=Lp(e,"Native delta");if(ly(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Dp)throw new ie(`Native delta schema must be ${Dp}`);let r=uI(t.capability,"Native delta capability"),i=Dc(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new ie("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:Dc(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=sy(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:sy(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new ie("Native delta operations must be an array");let s=t.operations.map(dI),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let p of d){if(c.has(p))throw new ie(`Native delta operations contain duplicate or overlapping requirement ID ${p} at ${l}`);c.add(p)}}if(o!==void 0){if(a===void 0)throw new ie("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new ie(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new ie(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:Dp,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 fI(e){let t=(0,Fp.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new ie(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Mp(e){return pI(typeof e=="string"?fI(e):e)}function Ka(e){return lI(e)}var Fp,Dp,oI,sI,cI,ay,ie,Vp=I(()=>{"use strict";Fp=ir(Bt(),1),Dp="comet.native.delta.v1",oI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sI=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,cI=/^[a-f0-9]{64}$/iu,ay=512,ie=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}}});var Wt,lr,ur,pn,fn,Ya,Xa=I(()=>{"use strict";Wt="comet.native.v3",lr="comet.native.v2",ur="comet.native.v1",pn="comet.native.transition.v3",fn="comet.native.transition.v2",Ya="comet.native.transition.v1"});import hI from"node:path";function Za(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function fy(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 Si(e){if(!py.test(e))throw new Error(`Invalid Native change name: ${e}`)}function hy(e){if(!py.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function my(e,t){if(e.length===0||hI.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kI(e,t){let r=Za(e,`spec_changes[${t}]`);if(fy(r,gI,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(hy(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"&&my(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"||!zp.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"||!zp.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 SI(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 Gp(e,t){if(fy(e,t,zt),typeof e.name!="string")throw new Error("Native change name is required");if(Si(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"||!wI.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&&!yI.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(kI),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"||!NI.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"&&my(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!SI(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 Ei(e){let t=Za(e,zt);if(t.schema!==ur)throw new Error(`Expected ${ur}`);return{schema:ur,...Gp(t,mI)}}function Qa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Wp(e,t,r){if(e===null)return null;let i=typeof e=="string"?bI.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 EI(e){if(e==null)return null;if(typeof e!="string"||!zp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function xI(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 xi(e){let t=Za(e,zt);if(t.schema!==lr)throw new Error(`Expected ${lr}`);if(Qa(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${lr} minimum_runtime_version must be 2`);return{schema:lr,minimum_runtime_version:2,revision:Qa(t.revision,"Native v2 revision"),...Gp(t,dy)}}function Gt(e){let t=Za(e,zt);if(t.schema!==Wt){if(t.schema===ur||t.schema===lr){let o=t.schema===ur?Ei(t):xi(t);throw new hn(o.name,o.schema)}throw new dr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Qa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new dr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Qa(t.revision,"Native revision"),n=Gp(t,vI),a=EI(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Wt,minimum_runtime_version:3,revision:i,verification_protocol:xI(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Wp(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Wp(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Wp(t.partial_allowance,"Native partial_allowance","allowances")}}function Bc(e){let t=Za(e,zt);if(t.schema===ur){let n=Ei(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema===lr){let n=xi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema!==Wt){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 dr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Qa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new dr(t.schema,r).message};let i=Gt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var uy,mI,dy,vI,gI,wI,yI,NI,zt,zp,py,bI,hn,dr,Fc=I(()=>{"use strict";Xa();uy=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],mI=new Set(uy),dy=new Set([...uy,"minimum_runtime_version","revision"]),vI=new Set([...dy,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),gI=new Set(["capability","operation","source","base_hash"]),wI=new Set(["shape","build","verify","archive"]),yI=new Set(["implicit","confirmed"]),NI=new Set(["pending","pass","fail"]),zt="comet-state.yaml",zp=/^[a-f0-9]{64}$/u,py=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,hn=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"},dr=class extends Error{constructor(r,i){super(r!==Wt||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"}});import vy from"node:path";function TI(e,t){return e<t?-1:e>t?1:0}function yy(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:r,truncated:!0}}function Ny(e,t){let r=t.toString(36),i=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function jI(e){if(!AI.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=II.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function $I(e,t){let r=yy(e.text,pr.maxTextBytes),i=e.context.slice(0,pr.maxContextItems).map(n=>yy(n,pr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function ky(e){let t=jI({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(TI),n=i.slice(0,pr.maxFailedCheckIds),a=e.criteria.slice(t,t+pr.maxItems);for(let c of a){let l=[...r,$I(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(p=>p.verificationStatus==="failed").map(p=>p.id),missingAcceptanceIds:l.filter(p=>p.verificationStatus==="missing").map(p=>p.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?Ny(e.acceptanceHash,u):null,limits:{...pr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>pr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?Ny(e.acceptanceHash,o):null,limits:{...pr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>pr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Up(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 Jp(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 by(e){return e.includes("-->")||e.includes("--!>")}function*mn(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
151
164
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
152
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=
|
|
153
|
-
`),[],i)),"Brief",i)}function
|
|
154
|
-
`),
|
|
155
|
-
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=pw(o),c=aA(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function aA(e){let t=pw([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var z_,J_,G_,U_,K_,Y_,rr,Ra,ow,sw,_a=I(()=>{"use strict";oi();ce();z_="comet.native.acceptance.v1",J_=/^acceptance-[a-f0-9]{64}$/u,G_=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),U_=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,K_=/^[a-f0-9]{64}$/u,Y_=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;rr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ra=Object.freeze({maxCriteria:1024}),ow="<!-- comet-native:acceptance-evidence:start -->",sw="<!-- comet-native:acceptance-evidence:end -->"});var ff=I(()=>{"use strict";_a()});function pf(){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 Zi,oc,mw,Aa=I(()=>{"use strict";Zi="comet.native.v4",oc="comet.native.local-execution.v4",mw=["multi-session","single-session"]});var wf={};gS(wf,{NativePortableStateVersionConflictError:()=>Ia,appendNativePortableHistory:()=>ja,compareAndSwapNativePortableState:()=>ww,createNativePortableState:()=>gw,parseNativePortableState:()=>Be,readNativePortableState:()=>jr,writeNativePortableState:()=>gf});import{promises as oA}from"node:fs";function je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Te(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 ye(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 mf(e,t){return e===null?null:ye(e,t)}function vf(e,t){let r=ye(e,t);if(!uA.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function en(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ne(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 fA(e,t){return e===null?null:ne(e,t,Number.MIN_SAFE_INTEGER)}function fe(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ft(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function uc(e,t){return Ft(e,t,(r,i)=>ye(r,`${t}[${i}]`))}function pi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function tn(e,t){let r=ye(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function cc(e,t,r=!1){let i=ye(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 rt(e,t){let r=je(e,t);return Te(r,new Set(["text","truncated"]),t),{text:ye(r.text,`${t}.text`,{empty:!0}),truncated:en(r.truncated,`${t}.truncated`)}}function pA(e,t){let r=`Native spec_changes[${t}]`,i=je(e,r);Te(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ye(i.capability,`${r}.capability`);if(!cA.test(n))throw new Error(`${r}.capability is invalid`);let a=fe(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:cc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:cc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:vf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function hA(e){let t="Native workspace",r=je(e,t);Te(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=fe(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=mf(r.change_branch,`${t}.change_branch`),a=mf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:fe(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 mA(e){let t="Native loop",r=je(e,t);Te(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=uc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);pi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:fe(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:fe(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ne(r.goal_cycle,`${t}.goal_cycle`,1),iteration:ne(r.iteration,`${t}.iteration`),attempt:ne(r.attempt,`${t}.attempt`),retry_epoch:ne(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ne(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ne(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ne(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:mf(r.next_action,`${t}.next_action`)}}function vA(e,t){let r=`Native acceptance[${t}]`,i=je(e,r);Te(i,new Set(["id","source","text","result","reason"]),r);let n=ye(i.id,`${r}.id`);if(!lA.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:cc(i.source,`${r}.source`),text:ye(i.text,`${r}.text`),result:fe(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:rt(i.reason,`${r}.reason`)}}function gA(e,t){let r=`Native builder_handoff.checks[${t}]`,i=je(e,r);return Te(i,new Set(["name","result","note"]),r),{name:rt(i.name,`${r}.name`),result:fe(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:rt(i.note,`${r}.note`)}}function wA(e){let t="Native builder_handoff",r=je(e,t);Te(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=uc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);pi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:je(r.review,`${t}.review`);return n&&Te(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ye(r.candidate_id,`${t}.candidate_id`),identity_provider:ye(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ye(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ne(r.iteration,`${t}.iteration`,1),summary:rt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ft(r.checks,`${t}.checks`,gA),checks_truncated:en(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ft(r.known_limits,`${t}.known_limits`,(a,o)=>rt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:en(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:fe(n.status,["passed"],`${t}.review.status`),summary:rt(n.summary,`${t}.review.summary`),reviewer_execution_ref:ye(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:tn(r.submitted_at,`${t}.submitted_at`)}}function yA(e,t){let r=`Native blockers[${t}]`,i=je(e,r);Te(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=uc(i.acceptance_ids,`${r}.acceptance_ids`);return pi(n,`${r}.acceptance_ids`),{owner:fe(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:rt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:fe(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function NA(e,t){let r=`Native verification.checks[${t}]`,i=je(e,r);return Te(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ye(i.id,`${r}.id`),name:rt(i.name,`${r}.name`),argv_display:Ft(i.argv_display,`${r}.argv_display`,(n,a)=>rt(n,`${r}.argv_display[${a}]`)),argv_truncated:en(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:cc(i.cwd_ref,`${r}.cwd_ref`,!0),status:fe(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:fA(i.exit_code,`${r}.exit_code`),duration_ms:ne(i.duration_ms,`${r}.duration_ms`)}}function bA(e){let t="Native verification",r=je(e,t);Te(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ft(r.checks,`${t}.checks`,NA);pi(i.map(a=>a.id),`${t}.checks IDs`);let n=ye(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ye(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ye(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ne(r.iteration,`${t}.iteration`,1),attempt:ne(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":fe(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:fe(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:rt(r.summary,`${t}.summary`),risks:Ft(r.risks,`${t}.risks`,(a,o)=>rt(a,`${t}.risks[${o}]`)),risks_truncated:en(r.risks_truncated,`${t}.risks_truncated`),completed_at:tn(r.completed_at,`${t}.completed_at`)}}function vw(e,t){let r=`Native history[${t}]`,i=je(e,r);Te(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=uc(i.unresolved_ids,`${r}.unresolved_ids`);return pi(n,`${r}.unresolved_ids`),{goal_cycle:ne(i.goal_cycle,`${r}.goal_cycle`,1),iteration:ne(i.iteration,`${r}.iteration`),attempt:ne(i.attempt,`${r}.attempt`),outcome:fe(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:rt(i.summary,`${r}.summary`),completed_at:tn(i.completed_at,`${r}.completed_at`)}}function kA(e){let t="Native history_overflow.outcome_counts",r=je(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Te(r,new Set(i),t),{pass:ne(r.pass,`${t}.pass`),fail:ne(r.fail,`${t}.fail`),blocked:ne(r.blocked,`${t}.blocked`),"execution-error":ne(r["execution-error"],`${t}.execution-error`),recovery:ne(r.recovery,`${t}.recovery`)}}function SA(e){let t="Native history_overflow",r=je(e,t);Te(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=ne(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:tn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:tn(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=kA(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function EA(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 xA(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 Be(e){let t=je(e,"Native portable state");if(Te(t,dA,"Native portable state"),t.schema!==Zi)throw new Error(`Native portable state schema must be ${Zi}`);let r=ye(t.name,"Native state name");if(!sA.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=Ft(t.spec_changes,"Native spec_changes",pA);pi(i.map(s=>s.capability),"Native spec change capabilities");let n=Ft(t.acceptance,"Native acceptance",vA);pi(n.map(s=>s.id),"Native acceptance IDs");let a=Ft(t.history,"Native history",vw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Zi,name:r,language:fe(t.language,["en","zh-CN"],"Native state language"),phase:fe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:fe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ne(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:vf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:vf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:fe(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:hA(t.workspace),loop:mA(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:wA(t.builder_handoff),blockers:Ft(t.blockers,"Native blockers",yA),verification:t.verification===null?null:bA(t.verification),history:a,history_overflow:SA(t.history_overflow),verification_result:fe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:fe(t.verification_report,["verification.md"],"Native verification_report"),archived:en(t.archived,"Native archived"),created_at:tn(t.created_at,"Native created_at")};return EA(o),xA(o),o}function gw(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return Be({schema:Zi,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:pf(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ja(e,t){let r=Be(e),i=vw(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 Be({...r,history:n,history_overflow:a})}function CA(e,t){let r=(0,lc.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 jr(e){let t=await oA.readFile(e,"utf8");return Be(CA(t,"Native portable state"))}async function gf(e,t,r={}){let i=Be(t);await $t(e,(0,lc.stringify)(i),r)}async function PA(e,t){let r=sc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);sc.set(e,a),await r;try{return await t()}finally{i(),sc.get(e)===a&&sc.delete(e)}}async function ww(e){return PA(e.file,async()=>{let t=ne(e.expectedStateVersion,"Native expected state version",1),r=Be(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await jr(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ia(t,i.state_version);return await gf(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await jr(e.file);if(n.state_version!==t)throw new Ia(t,n.state_version)}}),r})}var lc,sA,cA,lA,uA,dA,Ia,sc,wt=I(()=>{"use strict";lc=Gt(It(),1);le();Aa();sA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lA=/^A[1-9][0-9]*$/u,uA=/^[a-f0-9]{64}$/u,dA=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"]),Ia=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"};sc=new Map});var hi=I(()=>{"use strict"});function TA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $A(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 Nw(e){let t=TA(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!RA.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==yw)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!AA.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!_A.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!jA.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!IA.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:yw,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:$A(t.createdAt,"Native portable migration transaction createdAt")}}var yw,RA,_A,AA,IA,jA,bw=I(()=>{"use strict";nc();ff();wt();hi();Aa();xa();yw="comet.native.portable-migration.v1",RA=new Set(["schema","id","change","fromSchema","status","createdAt"]),_A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AA=/^[a-z0-9][a-z0-9-]{7,127}$/u,IA=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),jA=new Set([er,Zt,Ht])});import OA from"node:path";function Cw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Pw(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 yf(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 Sw(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function MA(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Cw(e,r);if(Pw(i,VA,r),typeof i.capability!="string"||!xw.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=yf(i.base_hash,`${r}.base_hash`),s=Sw(i.delta_content,`${r}.delta_content`),c=Sw(i.source_content,`${r}.source_content`),l=yf(i.expected_target_hash,`${r}.expected_target_hash`),u=yf(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=ef(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(Sa(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Sa(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(f=>f==="."||f===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||Sa(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function WA(e){let t=Cw(e,"Native portable Archive transaction");if(Pw(t,BA,"Native portable Archive transaction"),t.schema!==kw)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!qA.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!xw.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"||!FA.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"||!LA.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(MA);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:kw,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 Nf(e){let t=HA.exec(e);if(t)return{kind:"archive",change:t[1]};let r=DA.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Rw(e,t){let r=Nf(t);if(!r)return null;let i=await ee({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=OA.join(e.transactionsDir,t);if(r.kind==="archive"){let s=WA(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=Nw(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function _w(e){return e.kind==="archive"||e.journal.status!=="committed"}var kw,Ew,HA,DA,qA,FA,LA,BA,VA,xw,bf=I(()=>{"use strict";et();tf();bw();kw="comet.native.archive-transaction.v4",Ew="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",HA=new RegExp(`^portable-archive-(${Ew})\\.json$`,"u"),DA=new RegExp(`^portable-migration-(${Ew})\\.json$`,"u"),qA=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,FA=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LA=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),BA=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),VA=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),xw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as Aw}from"node:crypto";import{constants as Tr,promises as pe}from"node:fs";import Ve from"node:path";import{TextDecoder as zA}from"node:util";function rn(e,t){let r=Ve.relative(e,t);return r===""||!Ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ve.sep}`)}function Iw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function JA(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function jw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function $r(e,t){return z({...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 dc(e,t){let r=await pe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await pe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function fc(e,t,r){let i=Ve.resolve(e),n=Ve.resolve(t);if(!rn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await dc(i,r)],o=i;for(let s of Ve.relative(i,n).split(Ve.sep).filter(Boolean)){await $e(a,r),o=Ve.join(o,s);let c=await dc(o,r);if(!rn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await $e(a,r),a}async function $e(e,t){for(let r of e){let i=await pe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!JA(r,i)||await pe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function GA(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 Or(e){let t=e.maxBytes===null?null:Iw(e.maxBytes),r=Ve.resolve(e.file),i=await fc(e.root,Ve.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>dc(Ve.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await $e(i,e.label);let a=await pe.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=jw(a),s=await pe.realpath(r);if(!rn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>rn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Tr.O_RDONLY:Tr.O_RDONLY|Tr.O_NOFOLLOW|Tr.O_NONBLOCK,l=await pe.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([pe.lstat(r),pe.realpath(r)]);if(await $e(i,e.label),await $e(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!$r(o,u)||!$r(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await GA(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),pe.lstat(r),pe.realpath(r)]);if(await $e(i,e.label),await $e(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!$r(o,m)||!$r(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Aw("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function kf(e){let t=Ve.resolve(e.file),r=await fc(e.root,Ve.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>dc(Ve.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await $e(r,e.label);let n=await pe.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=jw(n),o=await pe.realpath(t);if(!rn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>rn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Tr.O_RDONLY:Tr.O_RDONLY|Tr.O_NOFOLLOW|Tr.O_NONBLOCK,c=await pe.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([pe.lstat(t),pe.realpath(t)]);if(await $e(r,e.label),await $e(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!$r(a,l)||!$r(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=Aw("sha256"),p=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:b}=await c.read(m,0,m.length,null);if(b===0)break;p+=b,f.update(m.subarray(0,b))}await e.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat(),pe.lstat(t),pe.realpath(t)]);if(await $e(r,e.label),await $e(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!$r(a,h)||!$r(a,v))throw new Error(`${e.label} changed while reading`);return{hash:f.digest("hex"),size:p}}finally{await c.close()}}async function Tw(e){let t=await Or(e),r;try{r=new zA("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function $a(e){let t=await fc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await pe.readdir(e.directory,{withFileTypes:!0});else{let i=Iw(e.maxEntries);r=[];let n=await pe.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await $e(t,e.label),{entries:r,verify:()=>$e(t,e.label)}}async function Sf(e){let t=await fc(e.root,e.directory,e.label);return{verify:()=>$e(t,e.label)}}var yt=I(()=>{"use strict";le();Tt()});import ir from"path";import{TextDecoder as KA}from"util";function hc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mc(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 Dw(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ef(e,t){if(typeof e!="string"||e.length===0||ir.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function pc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $w(e,t){if(Ef(e,t),e.includes("\\")||e!==ir.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 tI(e,t){let r=hc(e,`transaction operations[${t}]`);if(mc(r,XA,`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`);Ef(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Ef(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 qw(e){let t=hc(e,"Native Archive transaction journal");if(mc(t,QA,"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"||!Hw.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(!Dw(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(pc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=hc(s,`Archive transaction operations[${c}]`);if(mc(l,ZA,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);$w(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&$w(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&pc(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(pc(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);pc(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function rI(e){let t=hc(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return qw(t);if(mc(t,YA,"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"||!Hw.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ir.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ir.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(!Dw(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(tI),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 iI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ir.join(e.transactionsDir,t)}function Fw(e,t){let r=iI(e,t);return{directory:r,journal:ir.join(r,"transaction.json"),events:ir.join(r,"events.jsonl"),staged:ir.join(r,"staged"),backups:ir.join(r,"backups")}}async function xf(e,t){let r=Fw(e,t);return await Promise.all(Object.values(r).map(i=>V(e.runtimeDir,i))),r}async function Cf(e,t,r={}){let i=await xf(e,t),n=await Or({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(eI.decode(n.bytes)),o=rI(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var YA,XA,QA,ZA,Hw,eI,vc=I(()=>{"use strict";le();U();yt();YA=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),XA=new Set(["id","type","source","target","staged","backup"]),QA=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),ZA=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Hw=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),eI=new KA("utf-8",{fatal:!0})});import{promises as nI}from"fs";import aI from"path";async function oI(e,t,r){let i;try{i=await nI.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 Cf(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(Nf(n.name))try{let a=await Rw(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(_w(a))return!0}catch{return!0}return!1}async function sI(e,t){let r=Date.now()+5e3,i=aI.join(e.locksDir,"root-move.lock");for(;;)try{return await ec(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Jg(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Gg(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 Se(e,t,r,i){let n=await sI(e,t);try{if(await zs(e.projectRoot),await oI(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await tc(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
|
|
156
|
-
`)}}}var Ee=I(()=>{"use strict";Ge();ka();bf();vc()});import{createHash as Lw}from"crypto";import{createReadStream as cI}from"fs";async function Pf(e){let t=Lw("sha256");for await(let r of cI(e))t.update(r);return t.digest("hex")}function Q(e){return Lw("sha256").update(e).digest("hex")}var Lt=I(()=>{"use strict"});import{createHash as bc}from"crypto";import{spawn as Kw}from"node:child_process";import{promises as re}from"fs";import F from"path";function Xw(e){let t=e.deadlineMs??CI;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Nt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return Nt(e)>=1}function Rf(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function on(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function AI(e,t){let r={..._I,...t===void 0?{}:{maxNodes:t},...e};if(!Number.isSafeInteger(r.maxNodes)||r.maxNodes<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxPathBytes)||r.maxPathBytes<1||r.maxPathBytes>r.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return r}async function II(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&F.win32.isAbsolute(i)?F.win32.resolve(i):"C:\\Windows",a=F.win32.join(n,"System32","taskkill.exe");if(!F.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=Kw(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),PI),u.unref()}catch{d(!1)}});for(let s=0;s<RI;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function $f(e,t,r,i){let n=Nt(e);if(n<1)throw Rf();let a=e.gitProcess,o=Kw(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=II(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Rf(m.error):Rf()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Qw(e,t){let r={...Tf,...t===void 0?{}:{maxRecords:t},...e};if(!Number.isSafeInteger(r.maxRecords)||r.maxRecords<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxRecordBytes)||r.maxRecordBytes<1||r.maxRecordBytes>r.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return r}async function wc(e,t,r,i=If){let{child:n,completion:a}=$f(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(p).subarray(0,m)),l+=p.byteLength,l>i&&(u=!0)}),n.stderr.on("data",p=>{if(c>=cn)return;let m=cn-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function _f(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Ha(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=$f(e,t,r,i.stdin!==void 0),c=[],l=bc("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),v=!1,g=!1,b=!1,S=N=>{let x=0;for(;x<N.byteLength;){let w=N.indexOf(0,x),k=w<0?N.byteLength:w,E=N.subarray(x,k);if(!v&&E.byteLength>0&&(h.byteLength+E.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),v=!0,g=!0):h=Buffer.concat([h,E])),w<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let y=h.byteLength+1;!v&&m<=i.maxRecords&&p+y<=i.maxBytes?(c.push(h),p+=y):g=!0,h=Buffer.alloc(0),v=!1,x=w+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>i.maxBytes&&(g=!0);let x=i.outputChunkBytes;if(x===void 0){S(N);return}for(let w=0;w<N.byteLength;w+=x)S(N.subarray(w,Math.min(N.byteLength,w+x)))}),o.stderr.on("data",N=>{if(d>=cn)return;let x=cn-d,w=Buffer.from(N).subarray(0,x);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:x})=>{let w=i.acceptedExitCodes??[0];if(N!==null&&w.includes(N)&&x===null&&!b&&h.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${r.join(" ")} failed${x?`: ${x.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function yc(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function jI(e,t,r){if(r.length===0)return new Set;let i=await Ha(e,t,["check-ignore","--no-index","-z","--stdin"],{...Tf,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=yc(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function TI(e,t,r){let{child:i,completion:n}=$f(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=cn)return;let d=cn-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function sn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function $I(e,t){return e.map(r=>{let i=sn(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function OI(e){let t=F.resolve(e);for(;;){try{return await re.lstat(F.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=F.dirname(t);if(r===t)return!1;t=r}}function HI(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function Zw(e,t,r,i={},n){let a=F.resolve(t.projectRoot),o=F.join(a,".comet","current-change.json"),c=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,o].map(p=>{let m=F.relative(a,F.resolve(p)).replaceAll("\\","/"),h=sn(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(p=>[`:(exclude)${p}`,`:(exclude)${p}/**`]),...HI(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await Ha(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await Ha(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let f=await Ha(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:f}}function ey(e){return{stageBefore:_f(e.stagedBefore),combined:_f(e.combined),stageAfter:_f(e.stagedAfter)}}async function ty(e,t,r=Tf,i={},n){let a=F.resolve(t.projectRoot);if(!await OI(a))return null;let o;try{o=await wc(e,a,["rev-parse","--is-inside-work-tree"])}catch(S){throw on(S)?S:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:S})}if(o.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let s;try{s=await Zw(e,t,r,i,n)}catch(S){throw on(S)?S:new Error("Native Git snapshot provider failed after repository detection",{cause:S})}let{stagedBefore:c,combined:l,stagedAfter:u}=s,d=new Set,f=new Map,p=new Set,m=S=>{for(let N of S){let x=yc(N),w=x.indexOf(" ");if(w<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let k=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(x.slice(0,w))?.groups;if(!k)throw new Error("Native Git snapshot provider returned a malformed staged header");let E=sn(x.slice(w+1));if(E===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");d.add(E),k.stage==="0"&&f.set(E,k.objectId),k.mode==="160000"&&k.stage==="0"&&p.add(E)}};m(c.records),m(u.records);let h=l.records.map(yc),v=$I(h,"combined"),g=new Set(v.filter(S=>!d.has(S))),b=new Set(v.filter((S,N)=>!d.has(S)&&h[N].endsWith("/")));for(let S of p)b.delete(S);return{tracked:d,trackedObjectIds:f,untracked:g,gitlinks:p,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:ey(s)}}function Dr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Bw(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function DI(e,t){return!Dr(e.stageBefore,e.stageAfter)||!Dr(e.stageAfter,t.stageBefore)||!Dr(e.combined,t.combined)||!Dr(t.stageBefore,t.stageAfter)}async function ry(e,t,r,i,n,a){let o;try{o=await Zw(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw on(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=ey(o),l=Bw(s)||Bw(c),u=DI(s,c);l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),u&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=l||u?{schema:"comet.native.git-selection.v1",status:l&&u?"overflow-and-changed":l?"overflow":"changed",...s,finalStageBefore:c.stageBefore,finalCombined:c.combined,finalStageAfter:c.stageAfter}:null,(s.combined.overflow||c.combined.overflow)&&(i.overflow={count:Math.max(1,s.combined.recordCount-s.combined.storedRecordCount,c.combined.recordCount-c.combined.storedRecordCount),hash:Q(`comet.native.git-selection-overflow.v2
|
|
157
|
-
${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function
|
|
158
|
-
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):
|
|
159
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:
|
|
160
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function
|
|
165
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Jp(l,t);else if(r)by(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=Jp(l,null);if(d!==null)t=d;else{let p=l.trimStart();if(p.startsWith("<!--")&&!by(p))r=!0;else{let f=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(p);f&&n.has(f[1].toLowerCase())&&!p.startsWith("</")&&!p.endsWith("/>")&&!new RegExp(`</${f[1]}\\s*>`,"iu").test(p)&&(i=f[1])}}}if(c===-1)break;o=c+1}}function OI(e){return[...mn(e)].map(({line:t,body:r})=>({line:t,body:r}))}function Lc(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function HI(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Kp(e,t,r,i=[],n="content-hash"){let a=Lc(r),o=t.replaceAll("\\","/").trim(),s=i.map(Lc);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-${j(CI,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Yp(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 DI(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of mn(e)){n=s+1;let c=o?Up(a):null;c?.level===1&&(uc(c.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 Xp(e,t="brief.md",r=eo.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=DI(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of mn(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(p===null)continue;let f=p[1].length;a=a===null?f:Math.min(a,f)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of mn(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;p&&p[1].length===a?(c(),s=[p[2]]):s!==null&&s.push(l)}return c(),Yp(o.map(l=>Kp("brief-example",t,l.join(`
|
|
166
|
+
`),[],i)),"Brief",i)}function Qp(e,t="spec.md",r=eo.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,c=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.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(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...Kp("spec-scenario",t,[s.title,...s.body].join(`
|
|
167
|
+
`),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of mn(e)){let d=u?Up(l):null,p=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(p){for(c();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let f=Lc(p[1]);if(f.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:f,body:[],context:o.map(m=>m.text)}}else if(d){for(s!==null&&d.level<=s.level?c():s!==null&&s.body.push(l);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(l)}return c(),Yp(a,"Specification",i)}function Sy(e,t="spec.md",r=eo.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Kp("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of mn(e)){let p=d?Up(u):null;if(p){for(c(),o!==null&&p.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=p.level;)a.pop();a.push(p),/^Scenario\s*:/iu.test(p.text)&&(o=p.level);continue}let f=u.trim();if(!d||o!==null||l()){c();continue}if(f.length===0||Jp(u,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(f)){c(),s={parts:[f],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[f],context:a.map(h=>h.text)}:s.parts.push(f)}return c(),Yp(n,"Specification mandatory requirements",i)}function BI(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||HI(r)||vy.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=vy.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!_I.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function FI(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!PI.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function Ey(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=FI(r,i),a=n.acceptance_id;if(typeof a!="string"||!RI.test(a))throw new Error(`Acceptance evidence entry ${i} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return BI(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function xy(e){let t=OI(e);if(t.some(({line:l,body:u})=>!u&&(l===gy||l===wy)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===gy?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===wy?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[0]+1,n[0]).map(({line:l})=>l).join(`
|
|
168
|
+
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Ey(o),c=LI(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function LI(e){let t=Ey([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var CI,RI,PI,_I,AI,II,pr,eo,gy,wy,to=I(()=>{"use strict";yi();de();CI="comet.native.acceptance.v1",RI=/^acceptance-[a-f0-9]{64}$/u,PI=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),_I=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,AI=/^[a-f0-9]{64}$/u,II=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;pr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),eo=Object.freeze({maxCriteria:1024}),gy="<!-- comet-native:acceptance-evidence:start -->",wy="<!-- comet-native:acceptance-evidence:end -->"});var Zp=I(()=>{"use strict";to()});function ef(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 ro({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var ro,qc=I(()=>{"use strict";ro=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]}}});function tf(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 rf(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}]`;ef(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:tf(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>tf(o,`${n}.evidence`)),note:tf(i.note,`${n}.note`)}})}function nf(e,t){if(!t)throw new vn(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),i=t.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new vn(o,s)}var vn,Mc=I(()=>{"use strict";qc();vn=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}});function af(){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 gn,Vc,Cy,io=I(()=>{"use strict";gn="comet.native.v4",Vc="comet.native.local-execution.v4",Cy=["multi-session","single-session"]});var uf={};VE(uf,{NativePortableStateVersionConflictError:()=>no,appendNativePortableHistory:()=>ao,compareAndSwapNativePortableState:()=>_y,createNativePortableState:()=>Py,parseNativePortableState:()=>ze,readNativePortableState:()=>Vr,writeNativePortableState:()=>lf});import{promises as qI}from"node:fs";function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Be(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 be(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 sf(e,t){return e===null?null:be(e,t)}function cf(e,t){let r=be(e,t);if(!zI.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function wn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function se(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 JI(e,t){return e===null?null:se(e,t,Number.MIN_SAFE_INTEGER)}function he(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Jt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Jc(e,t){return Jt(e,t,(r,i)=>be(r,`${t}[${i}]`))}function Ci(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function yn(e,t){let r=be(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function zc(e,t,r=!1){let i=be(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 ct(e,t){let r=De(e,t);return Be(r,new Set(["text","truncated"]),t),{text:be(r.text,`${t}.text`,{empty:!0}),truncated:wn(r.truncated,`${t}.truncated`)}}function UI(e,t){let r=`Native spec_changes[${t}]`,i=De(e,r);Be(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=be(i.capability,`${r}.capability`);if(!VI.test(n))throw new Error(`${r}.capability is invalid`);let a=he(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:zc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:zc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:cf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function KI(e){let t="Native workspace",r=De(e,t);Be(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=he(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=sf(r.change_branch,`${t}.change_branch`),a=sf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:he(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 YI(e){let t="Native loop",r=De(e,t);Be(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=Jc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ci(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:he(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:he(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:se(r.goal_cycle,`${t}.goal_cycle`,1),iteration:se(r.iteration,`${t}.iteration`),attempt:se(r.attempt,`${t}.attempt`),retry_epoch:se(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:se(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:se(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:se(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:sf(r.next_action,`${t}.next_action`)}}function XI(e,t){let r=`Native acceptance[${t}]`,i=De(e,r);Be(i,new Set(["id","source","text","result","reason"]),r);let n=be(i.id,`${r}.id`);if(!WI.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:zc(i.source,`${r}.source`),text:be(i.text,`${r}.text`),result:he(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ct(i.reason,`${r}.reason`)}}function QI(e,t){let r=`Native builder_handoff.checks[${t}]`,i=De(e,r);return Be(i,new Set(["name","result","note"]),r),{name:ct(i.name,`${r}.name`),result:he(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ct(i.note,`${r}.note`)}}function ZI(e){let t="Native builder_handoff",r=De(e,t);Be(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=Jc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ci(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:De(r.review,`${t}.review`);return n&&Be(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:be(r.candidate_id,`${t}.candidate_id`),identity_provider:be(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:be(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),summary:ct(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:rf(r.acceptance_review)},checks:Jt(r.checks,`${t}.checks`,QI),checks_truncated:wn(r.checks_truncated,`${t}.checks_truncated`),known_limits:Jt(r.known_limits,`${t}.known_limits`,(a,o)=>ct(a,`${t}.known_limits[${o}]`)),known_limits_truncated:wn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:he(n.status,["passed"],`${t}.review.status`),summary:ct(n.summary,`${t}.review.summary`),reviewer_execution_ref:be(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:yn(r.submitted_at,`${t}.submitted_at`)}}function eT(e,t){let r=`Native blockers[${t}]`,i=De(e,r);Be(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Jc(i.acceptance_ids,`${r}.acceptance_ids`);return Ci(n,`${r}.acceptance_ids`),{owner:he(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ct(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:he(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function tT(e,t){let r=`Native verification.checks[${t}]`,i=De(e,r);return Be(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:be(i.id,`${r}.id`),name:ct(i.name,`${r}.name`),argv_display:Jt(i.argv_display,`${r}.argv_display`,(n,a)=>ct(n,`${r}.argv_display[${a}]`)),argv_truncated:wn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:zc(i.cwd_ref,`${r}.cwd_ref`,!0),status:he(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:JI(i.exit_code,`${r}.exit_code`),duration_ms:se(i.duration_ms,`${r}.duration_ms`)}}function rT(e){let t="Native verification",r=De(e,t);Be(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Jt(r.checks,`${t}.checks`,tT);Ci(i.map(a=>a.id),`${t}.checks IDs`);let n=be(r.identity_provider,`${t}.identity_provider`);return{candidate_id:be(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:be(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),attempt:se(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":he(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:he(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ct(r.summary,`${t}.summary`),risks:Jt(r.risks,`${t}.risks`,(a,o)=>ct(a,`${t}.risks[${o}]`)),risks_truncated:wn(r.risks_truncated,`${t}.risks_truncated`),completed_at:yn(r.completed_at,`${t}.completed_at`)}}function Ry(e,t){let r=`Native history[${t}]`,i=De(e,r);Be(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Jc(i.unresolved_ids,`${r}.unresolved_ids`);return Ci(n,`${r}.unresolved_ids`),{goal_cycle:se(i.goal_cycle,`${r}.goal_cycle`,1),iteration:se(i.iteration,`${r}.iteration`),attempt:se(i.attempt,`${r}.attempt`),outcome:he(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ct(i.summary,`${r}.summary`),completed_at:yn(i.completed_at,`${r}.completed_at`)}}function iT(e){let t="Native history_overflow.outcome_counts",r=De(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Be(r,new Set(i),t),{pass:se(r.pass,`${t}.pass`),fail:se(r.fail,`${t}.fail`),blocked:se(r.blocked,`${t}.blocked`),"execution-error":se(r["execution-error"],`${t}.execution-error`),recovery:se(r.recovery,`${t}.recovery`)}}function nT(e){let t="Native history_overflow",r=De(e,t);Be(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=se(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:yn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:yn(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=iT(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function aT(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&&nf(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 oT(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 ze(e){let t=De(e,"Native portable state");if(Be(t,GI,"Native portable state"),t.schema!==gn)throw new Error(`Native portable state schema must be ${gn}`);let r=be(t.name,"Native state name");if(!MI.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=Jt(t.spec_changes,"Native spec_changes",UI);Ci(i.map(s=>s.capability),"Native spec change capabilities");let n=Jt(t.acceptance,"Native acceptance",XI);Ci(n.map(s=>s.id),"Native acceptance IDs");let a=Jt(t.history,"Native history",Ry);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:gn,name:r,language:he(t.language,["en","zh-CN"],"Native state language"),phase:he(t.phase,["shape","build","verify","archive"],"Native state phase"),status:he(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:se(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:cf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:cf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:he(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:KI(t.workspace),loop:YI(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ZI(t.builder_handoff),blockers:Jt(t.blockers,"Native blockers",eT),verification:t.verification===null?null:rT(t.verification),history:a,history_overflow:nT(t.history_overflow),verification_result:he(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:he(t.verification_report,["verification.md"],"Native verification_report"),archived:wn(t.archived,"Native archived"),created_at:yn(t.created_at,"Native created_at")};return aT(o),oT(o),o}function Py(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ze({schema:gn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:af(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ao(e,t){let r=ze(e),i=Ry(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 ze({...r,history:n,history_overflow:a})}function sT(e,t){let r=(0,Gc.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 Vr(e){let t=await qI.readFile(e,"utf8");return ze(sT(t,"Native portable state"))}async function lf(e,t,r={}){let i=ze(t);await qt(e,(0,Gc.stringify)(i),r)}async function cT(e,t){let r=Wc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Wc.set(e,a),await r;try{return await t()}finally{i(),Wc.get(e)===a&&Wc.delete(e)}}async function _y(e){return cT(e.file,async()=>{let t=se(e.expectedStateVersion,"Native expected state version",1),r=ze(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Vr(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new no(t,i.state_version);return await lf(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Vr(e.file);if(n.state_version!==t)throw new no(t,n.state_version)}}),r})}var Gc,MI,VI,WI,zI,GI,no,Wc,xt=I(()=>{"use strict";Mc();Gc=ir(Bt(),1);oe();io();MI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WI=/^A[1-9][0-9]*$/u,zI=/^[a-f0-9]{64}$/u,GI=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"]),no=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"};Wc=new Map});var Ri=I(()=>{"use strict"});function hT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mT(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 Iy(e){let t=hT(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!lT.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ay)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!dT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!uT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!fT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!pT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ay,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:mT(t.createdAt,"Native portable migration transaction createdAt")}}var Ay,lT,uT,dT,pT,fT,Ty=I(()=>{"use strict";Fc();Zp();xt();Ri();io();Xa();Ay="comet.native.portable-migration.v1",lT=new Set(["schema","id","change","fromSchema","status","createdAt"]),uT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dT=/^[a-z0-9][a-z0-9-]{7,127}$/u,pT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),fT=new Set([ur,lr,Wt])});import vT from"node:path";function Dy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function By(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 df(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 $y(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function ET(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Dy(e,r);if(By(i,ST,r),typeof i.capability!="string"||!Hy.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(p=>p==="."||p==="..")))throw new Error(`${r}.delta_source is invalid`);let o=df(i.base_hash,`${r}.base_hash`),s=$y(i.delta_content,`${r}.delta_content`),c=$y(i.source_content,`${r}.source_content`),l=df(i.expected_target_hash,`${r}.expected_target_hash`),u=df(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let p=Mp(s);if(p.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(p.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(Ka(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Ka(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(p=>p==="."||p===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||Ka(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function xT(e){let t=Dy(e,"Native portable Archive transaction");if(By(t,kT,"Native portable Archive transaction"),t.schema!==jy)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!yT.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Hy.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"||!NT.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"||!bT.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(ET);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:jy,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 pf(e){let t=gT.exec(e);if(t)return{kind:"archive",change:t[1]};let r=wT.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Fy(e,t){let r=pf(t);if(!r)return null;let i=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=vT.join(e.transactionsDir,t);if(r.kind==="archive"){let s=xT(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=Iy(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function Ly(e){return e.kind==="archive"||e.journal.status!=="committed"}var jy,Oy,gT,wT,yT,NT,bT,kT,ST,Hy,ff=I(()=>{"use strict";at();Vp();Ty();jy="comet.native.archive-transaction.v4",Oy="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",gT=new RegExp(`^portable-archive-(${Oy})\\.json$`,"u"),wT=new RegExp(`^portable-migration-(${Oy})\\.json$`,"u"),yT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,NT=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bT=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),kT=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ST=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Hy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as qy}from"node:crypto";import{constants as Wr,promises as me}from"node:fs";import Ge from"node:path";import{TextDecoder as CT}from"node:util";function Nn(e,t){let r=Ge.relative(e,t);return r===""||!Ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ge.sep}`)}function My(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function RT(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Vy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function zr(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Uc(e,t){let 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 Kc(e,t,r){let i=Ge.resolve(e),n=Ge.resolve(t);if(!Nn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Uc(i,r)],o=i;for(let s of Ge.relative(i,n).split(Ge.sep).filter(Boolean)){await Fe(a,r),o=Ge.join(o,s);let c=await Uc(o,r);if(!Nn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Fe(a,r),a}async function Fe(e,t){for(let r of e){let i=await me.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!RT(r,i)||await me.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function PT(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 Gr(e){let t=e.maxBytes===null?null:My(e.maxBytes),r=Ge.resolve(e.file),i=await Kc(e.root,Ge.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Uc(Ge.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Fe(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=Vy(a),s=await me.realpath(r);if(!Nn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Nn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Wr.O_RDONLY:Wr.O_RDONLY|Wr.O_NOFOLLOW|Wr.O_NONBLOCK,l=await me.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([me.lstat(r),me.realpath(r)]);if(await Fe(i,e.label),await Fe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!zr(o,u)||!zr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await PT(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),me.lstat(r),me.realpath(r)]);if(await Fe(i,e.label),await Fe(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!zr(o,m)||!zr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:qy("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function hf(e){let t=Ge.resolve(e.file),r=await Kc(e.root,Ge.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>Uc(Ge.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Fe(r,e.label);let n=await me.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=Vy(n),o=await me.realpath(t);if(!Nn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>Nn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Wr.O_RDONLY:Wr.O_RDONLY|Wr.O_NOFOLLOW|Wr.O_NONBLOCK,c=await me.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([me.lstat(t),me.realpath(t)]);if(await Fe(r,e.label),await Fe(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!zr(a,l)||!zr(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=qy("sha256"),f=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:b}=await c.read(m,0,m.length,null);if(b===0)break;f+=b,p.update(m.subarray(0,b))}await e.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat(),me.lstat(t),me.realpath(t)]);if(await Fe(r,e.label),await Fe(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!zr(a,h)||!zr(a,v))throw new Error(`${e.label} changed while reading`);return{hash:p.digest("hex"),size:f}}finally{await c.close()}}async function Wy(e){let t=await Gr(e),r;try{r=new CT("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function so(e){let t=await Kc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await me.readdir(e.directory,{withFileTypes:!0});else{let i=My(e.maxEntries);r=[];let n=await me.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Fe(t,e.label),{entries:r,verify:()=>Fe(t,e.label)}}async function mf(e){let t=await Kc(e.root,e.directory,e.label);return{verify:()=>Fe(t,e.label)}}var Ct=I(()=>{"use strict";oe();Lt()});import fr from"path";import{TextDecoder as AT}from"util";function Xc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qc(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 Uy(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function vf(e,t){if(typeof e!="string"||e.length===0||fr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Yc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function zy(e,t){if(vf(e,t),e.includes("\\")||e!==fr.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 HT(e,t){let r=Xc(e,`transaction operations[${t}]`);if(Qc(r,TT,`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`);vf(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&vf(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 Ky(e){let t=Xc(e,"Native Archive transaction journal");if(Qc(t,jT,"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"||!Jy.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(!Uy(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Yc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Xc(s,`Archive transaction operations[${c}]`);if(Qc(l,$T,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);zy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&zy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Yc(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Yc(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Yc(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function DT(e){let t=Xc(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Ky(t);if(Qc(t,IT,"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"||!Jy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!fr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!fr.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(!Uy(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(HT),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 BT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return fr.join(e.transactionsDir,t)}function Yy(e,t){let r=BT(e,t);return{directory:r,journal:fr.join(r,"transaction.json"),events:fr.join(r,"events.jsonl"),staged:fr.join(r,"staged"),backups:fr.join(r,"backups")}}async function gf(e,t){let r=Yy(e,t);return await Promise.all(Object.values(r).map(i=>V(e.runtimeDir,i))),r}async function wf(e,t,r={}){let i=await gf(e,t),n=await Gr({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(OT.decode(n.bytes)),o=DT(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var IT,TT,jT,$T,Jy,OT,Zc=I(()=>{"use strict";oe();K();Ct();IT=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),TT=new Set(["id","type","source","target","staged","backup"]),jT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),$T=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Jy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),OT=new AT("utf-8",{fatal:!0})});import{promises as FT}from"fs";import LT from"path";async function qT(e,t,r){let i;try{i=await FT.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 wf(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(pf(n.name))try{let a=await Fy(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ly(a))return!0}catch{return!0}return!1}async function MT(e,t){let r=Date.now()+5e3,i=LT.join(e.locksDir,"root-move.lock");for(;;)try{return await Oc(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await iy(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await ny(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 Ce(e,t,r,i){let n=await MT(e,t);try{if(await Rc(e.projectRoot),await qT(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Hc(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
|
|
169
|
+
`)}}}var Re=I(()=>{"use strict";Qe();Ua();ff();Zc()});import{createHash as Xy}from"crypto";import{createReadStream as VT}from"fs";async function yf(e){let t=Xy("sha256");for await(let r of VT(e))t.update(r);return t.digest("hex")}function ee(e){return Xy("sha256").update(e).digest("hex")}var Ut=I(()=>{"use strict"});import{createHash as nl}from"crypto";import{spawn as sN}from"node:child_process";import{promises as ne}from"fs";import F from"path";import{performance as Qy}from"node:perf_hooks";function lN(e){let t=e.deadlineMs??sj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Rt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return Rt(e)>=1}function Nf(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Sn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function dj(e,t){let r={...uj,...t===void 0?{}:{maxNodes:t},...e};if(!Number.isSafeInteger(r.maxNodes)||r.maxNodes<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxPathBytes)||r.maxPathBytes<1||r.maxPathBytes>r.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return r}async function pj(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&F.win32.isAbsolute(i)?F.win32.resolve(i):"C:\\Windows",a=F.win32.join(n,"System32","taskkill.exe");if(!F.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(p,f=!1)=>{c||(c=!0,u&&clearTimeout(u),f&&l?.kill("SIGKILL"),s(p))};try{l=sN(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",p=>d(p===0)),u=setTimeout(()=>d(!1,!0),cj),u.unref()}catch{d(!1)}});for(let s=0;s<lj;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Cf(e,t,r,i){let n=Rt(e);if(n<1)throw Nf();let a=e.gitProcess,o=Qy.now(),s=sN(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),c=null,l=!1,u=null;s.once("error",m=>{c=m});let d=new Promise(m=>{s.once("close",m)}),p=setTimeout(()=>{l=!0,u=pj(s,a).then(()=>({error:null}),m=>({error:m}))},n);p.unref();let f=d.then(async m=>{if(clearTimeout(p),l){let h=await u;throw h?.error?Nf(h.error):Nf()}return{code:m,spawnError:c}}).finally(()=>os(Qy.now()-o));return{child:s,completion:f}}function uN(e,t){let r={...xf,...t===void 0?{}:{maxRecords:t},...e};if(!Number.isSafeInteger(r.maxRecords)||r.maxRecords<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxRecordBytes)||r.maxRecordBytes<1||r.maxRecordBytes>r.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return r}async function tl(e,t,r,i=Sf){let{child:n,completion:a}=Cf(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",f=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(f).subarray(0,m)),l+=f.byteLength,l>i&&(u=!0)}),n.stderr.on("data",f=>{if(c>=xn)return;let m=xn-c,h=Buffer.from(f).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:p}=await a;if(d===0&&p===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${p?`: ${p.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function bf(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function lo(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Cf(e,t,r,i.stdin!==void 0),c=[],l=nl("sha256"),u=[],d=0,p=0,f=0,m=0,h=Buffer.alloc(0),v=!1,g=!1,b=!1,k=N=>{let x=0;for(;x<N.byteLength;){let w=N.indexOf(0,x),S=w<0?N.byteLength:w,E=N.subarray(x,S);if(!v&&E.byteLength>0&&(h.byteLength+E.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),v=!0,g=!0):h=Buffer.concat([h,E])),w<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let y=h.byteLength+1;!v&&m<=i.maxRecords&&f+y<=i.maxBytes?(c.push(h),f+=y):g=!0,h=Buffer.alloc(0),v=!1,x=w+1}};o.stdout.on("data",N=>{l.update(N),p+=N.byteLength,p>i.maxBytes&&(g=!0);let x=i.outputChunkBytes;if(x===void 0){k(N);return}for(let w=0;w<N.byteLength;w+=x)k(N.subarray(w,Math.min(N.byteLength,w+x)))}),o.stderr.on("data",N=>{if(d>=xn)return;let x=xn-d,w=Buffer.from(N).subarray(0,x);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:x})=>{let w=i.acceptedExitCodes??[0];if(N!==null&&w.includes(N)&&x===null&&!b&&h.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:p});return}a(new Error(`git ${r.join(" ")} failed${x?`: ${x.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function rl(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function fj(e,t,r){if(r.length===0)return new Set;let i=await lo(e,t,["check-ignore","--no-index","-z","--stdin"],{...xf,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=rl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function hj(e,t,r){let{child:i,completion:n}=Cf(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=xn)return;let d=xn-o,p=Buffer.from(u).subarray(0,d);a.push(p),o+=p.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function En(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function mj(e,t){return e.map(r=>{let i=En(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function vj(e){let t=F.resolve(e);for(;;){try{return await ne.lstat(F.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=F.dirname(t);if(r===t)return!1;t=r}}function gj(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function dN(e,t,r,i={},n){let a=F.resolve(t.projectRoot),o=F.join(a,".comet","current-change.json"),c=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,o].map(f=>{let m=F.relative(a,F.resolve(f)).replaceAll("\\","/"),h=En(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`]),...gj(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await lo(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await lo(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let p=await lo(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:p}}function pN(e){return{stageBefore:bf(e.stagedBefore),combined:bf(e.combined),stageAfter:bf(e.stagedAfter)}}async function fN(e,t,r=xf,i={},n){let a=F.resolve(t.projectRoot);if(!await vj(a))return null;let o;try{o=await tl(e,a,["rev-parse","--is-inside-work-tree"])}catch(k){throw Sn(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}if(o.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let s;try{s=await dN(e,t,r,i,n)}catch(k){throw Sn(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:c,combined:l,stagedAfter:u}=s,d=new Set,p=new Map,f=new Set,m=k=>{for(let N of k){let x=rl(N),w=x.indexOf(" ");if(w<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(x.slice(0,w))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let E=En(x.slice(w+1));if(E===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");d.add(E),S.stage==="0"&&p.set(E,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(E)}};m(c.records),m(u.records);let h=l.records.map(rl),v=mj(h,"combined"),g=new Set(v.filter(k=>!d.has(k))),b=new Set(v.filter((k,N)=>!d.has(k)&&h[N].endsWith("/")));for(let k of f)b.delete(k);return{tracked:d,trackedObjectIds:p,untracked:g,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:pN(s)}}function Ur(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Zy(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function wj(e,t){return!Ur(e.stageBefore,e.stageAfter)||!Ur(e.stageAfter,t.stageBefore)||!Ur(e.combined,t.combined)||!Ur(t.stageBefore,t.stageAfter)}async function hN(e,t,r,i,n,a){let o;try{o=await dN(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw Sn(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=pN(o),l=Zy(s)||Zy(c),u=wj(s,c);l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),u&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=l||u?{schema:"comet.native.git-selection.v1",status:l&&u?"overflow-and-changed":l?"overflow":"changed",...s,finalStageBefore:c.stageBefore,finalCombined:c.combined,finalStageAfter:c.stageAfter}:null,(s.combined.overflow||c.combined.overflow)&&(i.overflow={count:Math.max(1,s.combined.recordCount-s.combined.storedRecordCount,c.combined.recordCount-c.combined.storedRecordCount),hash:ee(`comet.native.git-selection-overflow.v2
|
|
170
|
+
${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function Nj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function eN(e){let t=F.resolve(e.paths.projectRoot),r=F.resolve(e.paths.nativeRoot),i=F.resolve(e.paths.runtimeDir),n=F.resolve(e.paths.configFile),a=F.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,p=0,f=!1,m=!1,h=!1,v=()=>Rt(e.execution)>=1?!0:(f=!0,h=!0,!1),g=N=>{let x=Buffer.from(`${N.type}\0${N.path}`,"utf8"),w=nl("sha256").update("comet.native.physical-selection-record.v1\0").update(x).digest();for(let S=0;S<c.length;S+=1)c[S]^=w[S];if(l=l+BigInt(`0x${w.toString("hex")}`)&yj,d+=1,p+=x.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||p>e.limits.maxBytes){f=!0,h=!0;return}o.push(N)},b=async N=>{if(h||!v())return;let x;try{x=await ne.opendir(N)}catch(C){if(!v())return;if(!ge(C)&&!ve(C)||N===t&&ge(C))throw C;m||=ve(C),f||=ge(C),h=!0;return}if(!v()){try{await x.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let w=!1,S;try{for(;!h&&v();){let C;try{C=await x.read()}catch(Z){if(!v())break;if(!ge(Z)&&!ve(Z)||N===t&&ge(Z))throw Z;m||=ve(Z),f||=ge(Z),h=!0;break}if(!v()||C===null)break;if(u+=1,u>e.limits.maxNodes){f=!0,h=!0;break}let O=F.join(N,C.name),T=kj(t,O);if(O===n||O===a||Pt(r,O)||Pt(i,O)||e.denylist.some(Z=>Pt(Z,O))||Ft(T)!==null)continue;if(!v())break;let Q;try{Q=await ne.lstat(O)}catch(Z){if(!v())break;if(!ge(Z)&&!ve(Z))throw Z;if(m=!0,g({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:ge(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!v())break;continue}if(!v())break;let Te=Nj(Q);if(Te==="directory"){if(Cj(e.policy,T))continue;if(!v())break;let Z;try{Z=await ne.realpath(O)}catch(Ot){if(!v())break;if(!ge(Ot)&&!ve(Ot))throw Ot;if(m=!0,g({path:T,type:Te}),s.push({path:T,size:null,type:"directory",reason:ge(Ot)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!v())break;continue}if(!v())break;if(!q(e.physicalProjectRoot,Z)||Pt(e.physicalNativeRoot,Z))continue;if(g({path:T,type:Te}),await e.hooks?.afterNode?.(T),!v()||(await b(O),h))break;continue}if(g({path:T,type:Te}),await e.hooks?.afterNode?.(T),!v()||h)break}}catch(C){w=!0,S=C}let E;try{await x.close()}catch(C){E=C}let y=v();if(w)throw S;if(y&&E!==void 0&&E.code!=="ERR_DIR_CLOSED")throw E};await b(t),v(),f?(o.length=0,d=0,p=0):(o.sort((N,x)=>N.path.localeCompare(x.path,"en")),s.sort((N,x)=>N.path.localeCompare(x.path,"en")));let k=f?ee(`comet.native.physical-selection-incomplete.v1
|
|
171
|
+
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):ee(`comet.native.physical-selection.v1
|
|
172
|
+
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:p,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:p,overflow:f,unstable:m}}}function mN(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function bj(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!mN(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function vN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function tN(e,t){let i=(await tl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!cN.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return ee(`gitlink:${i}`)}async function rN(e,t){let r=await tN(e,t),i=await hj(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await tN(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function co(e,t){if(Ft(t)!==null)return!1;let r=F.resolve(e.projectRoot,...t.split("/"));return!Pt(F.resolve(e.nativeRoot),r)&&!Pt(F.resolve(e.runtimeDir),r)}function kj(e,t){return F.relative(e,t).split(F.sep).join("/")}function Sj(e,t){return t.map(r=>F.resolve(e,...r.split(/[\\/]/u)))}function Pt(e,t){let r=F.resolve(e),i=F.resolve(t);return i===r||q(r,i)}function ge(e){return oj.has(e.code??"")}function ve(e){return e.code==="ENOENT"}function Ej(e,t){return ee(`comet.native.snapshot-policy.v1
|
|
173
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function kf(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function xj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function iN(e){let t=Cc(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?xj(n):void 0;if(a&&!a())return!1;let o=kf(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=kf(r,c,a),o===null||o.size===0)return!1}return kf(r,o,a)?.has(r.length)??!1}}function gN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Cc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>Cc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=Ej(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(iN),excludeMatchers:r.map(iN),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Cj(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function nN(e,t,r){if(!e)return!0;let i=()=>H(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function il(e,t,r){let i=JSON.stringify(r);return ee(`${e}
|
|
161
174
|
${Buffer.byteLength(t)}:${t}
|
|
162
|
-
${Buffer.byteLength(i)}:${i}`)}function oy(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function sy(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!oy(r))return e.splice(t,1),r}return null}function Hr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function JI(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await re.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=bc("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!Hr(r,c))return{status:"changed"};for(;;){if(!H(i))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!Hr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function it(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function nt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function an(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Bt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function cy(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=F.posix.normalize(e);if(r!==e||F.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function GI(e,t){let r=it(e,`Native snapshot entry ${t}`);nt(r,yI,`Native snapshot entry ${t}`);let i=cy(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!kc.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Bt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Yw.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function UI(e,t){let r=it(e,`Native snapshot omission ${t}`);if(nt(r,NI,`Native snapshot omission ${t}`),!SI.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!EI.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:cy(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Bt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function KI(e){let t=it(e,"Native snapshot omission overflow");if(nt(t,bI,"Native snapshot omission overflow"),typeof t.hash!="string"||!kc.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:an(t.count,"Native snapshot omission overflow count")}}function nn(e,t){let r=it(e,t);if(nt(r,vI,t),typeof r.hash!="string"||!kc.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Bt(r.recordCount,`${t} recordCount`),n=Bt(r.storedRecordCount,`${t} storedRecordCount`),a=Bt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Gw(e){let t=it(e,"Native Git selection evidence");if(nt(t,mI,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=nn(t.stageBefore,"Native Git selection stageBefore"),i=nn(t.combined,"Native Git selection combined"),n=nn(t.stageAfter,"Native Git selection stageAfter"),a=nn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=nn(t.finalCombined,"Native Git selection finalCombined"),s=nn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Dr(r,n)||!Dr(n,a)||!Dr(i,o)||!Dr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Uw(e,t){let r=it(e,t);if(nt(r,wI,t),typeof r.hash!="string"||!kc.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Bt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Bt(r.recordCount,`${t} recordCount`),a=Bt(r.storedRecordCount,`${t} storedRecordCount`),o=Bt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function YI(e){let t=it(e,"Native physical selection evidence");if(nt(t,gI,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Uw(t.before,"Native physical selection before"),i=Uw(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!iy(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function mi(e){let t=it(e,"Native content snapshot manifest");if(nt(t,uI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!kI.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=it(t.capture,"Native content snapshot capture");if(nt(w,pI,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let k=w.gitSelection===void 0?void 0:Gw(w.gitSelection),E=w.physicalSelection===void 0?void 0:YI(w.physicalSelection),y=null;if(w.projection!==void 0){let C=it(w.projection,"Native content snapshot projection");if(nt(C,hI,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:Gw(C.selection)}}}if(w.provider==="git"){if(E||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...k?{gitSelection:k}:{}}}else{if(k)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(E&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...E?{physicalSelection:E}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=it(t.limits,"Native content snapshot limits");nt(i,dI,"Native content snapshot limits");let n={maxFiles:an(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:an(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:an(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:an(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:an(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=it(t.policy,"Native snapshot policy");if(nt(w,fI,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=ay({include:w.include,exclude:w.exclude,hash:w.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(GI),s=t.omitted.map(UI),c=Bt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:KI(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,k)=>w+k.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>jf||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(w=>w.reason==="git-enumeration-limit"),f=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...f])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),g=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...g])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,S=b?.status==="overflow"||b?.status==="overflow-and-changed",N=b?.status==="changed"||b?.status==="overflow-and-changed";if(S!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}async function ly(e,t,r={}){let i=mi(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=Xw(r),o=Qw(r.gitSelectionLimits),s=await ty(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(ny(s).filter(k=>Oa(e,k))),l=[...s.gitlinks].filter(k=>c.has(k)),u=[...s.nestedRepositories].filter(k=>Oa(e,k)),d=(k,E)=>E.some(y=>k===y||k.startsWith(`${y}/`)),f=k=>d(k,l),p=k=>d(k,u),m=[...i.entries.map(k=>k.path),...i.omitted.flatMap(k=>k.type==="directory"?[k.path,`${k.path}/`]:[k.path])].filter(k=>!c.has(k)&&!f(k)&&!p(k)),h=await jI(a,n,m),v=i.entries.filter(k=>!f(k.path)&&!p(k.path)&&Oa(e,k.path)&&(c.has(k.path)||!h.has(k.path)));await ry(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let k of l)g.push({path:k,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((k,E)=>k.path.localeCompare(E.path,"en"));let b=i.omitted.filter(k=>f(k.path)||p(k.path)||!Oa(e,k.path)?!1:h.has(k.path)?c.has(k.path)||[...c].some(E=>E.startsWith(`${k.path}/`)):!0);for(let k of g)b.some(E=>E.path===k.path&&E.reason===k.reason)||b.push(k);b.sort((k,E)=>k.path.localeCompare(E.path,"en"));let S=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??Q("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,N=Nc(N,"git-selection",{source:"git-selection",...s.overflow}));let x=k=>{S+=1,N=Nc(N,"omission",k)};for(;b.length>jf;){let k=sy(b);if(k===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(k)}return mi({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+S===0,entries:v,omitted:b,omittedCount:b.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:S}}:{}})}function XI(e,t){if(!lI.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(K(e,t),"baseline-manifest.json")}async function uy(e,t={}){let r={maxFiles:t.limits?.maxFiles??gc.maxFiles,maxFileBytes:t.limits?.maxFileBytes??gc.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??gc.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??gc.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=ay(t.policy),n=Xw({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Qw(t.gitSelectionLimits,t.maxSelectionRecords),o=AI(t.physicalSelectionLimits,t.maxSelectionRecords);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=F.resolve(e.projectRoot),c=await re.realpath(s),l=F.resolve(e.nativeRoot),u=await re.realpath(l),d=F.resolve(e.runtimeDir),f=F.resolve(e.configFile),p=F.join(s,".comet","current-change.json"),m=VI(s,t.denylist??[]),h=[],v=[],g=new Map,b=new Map,S=0,N=0,x=Q("comet.native.snapshot-omission-overflow.v1"),w=0,k=!1,E=null,y=_=>{N+=1,x=Nc(x,"omission",_)},C=_=>{if(S+=1,v.length<jf){v.push(_);return}if(oy(_)){let A=sy(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),v.push(_);return}y(_)},O=_=>{S+=_.count,N+=_.count,x=Nc(x,"git-selection",{source:"git-selection",..._})},j=async(_,A)=>{h.push(_),w+=_.size,g.set(_.path,A),k||(k=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Y=(_,A)=>{let $=h.findIndex(Z=>Z.path===_);if($<0)return;let[M]=h.splice($,1);w-=M.size,g.delete(_),C(A)},Re=async(_,A,$,M)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let Z;try{Z=await re.realpath(_)}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;C({path:A,size:$.size,type:"file",reason:he(R)?"changed-during-read":"unreadable"});return}if(!H(n)||!B(c,Z)||bt(u,Z))return;if(h.length>=r.maxFiles){C({path:A,size:$.size,type:"file",reason:"file-count"});return}if($.size>r.maxFileBytes){C({path:A,size:$.size,type:"file",reason:"file-size"});return}if(w+$.size>r.maxTotalBytes){C({path:A,size:$.size,type:"file",reason:"total-size"});return}let J,D,oe;try{if(J=await JI(Z,$.size,$,n),J.status==="budget-exhausted"||!H(n))return;if(J.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(oe=await re.realpath(_),!H(n)))return;D=await re.lstat(_)}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;C({path:A,size:$.size,type:"file",reason:he(R)?"changed-during-read":"unreadable"});return}if(H(n)){if(J.bytes!==$.size||oe!==Z||!Hr($,J.finalStat)||!Hr(J.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==$.size||D.mtimeMs!==$.mtimeMs||D.ctimeMs!==$.ctimeMs){C({path:A,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await j({path:A,hash:J.hash,size:D.size,type:"file",...M===void 0?{}:{gitObjectId:M}},{kind:"file",target:_,realTarget:Z,stat:D})}},X=async(_,A,$)=>{if(!H(n))return;let M,Z,J;try{if(M=await re.readlink(_,{encoding:"buffer"}),!H(n)||(J=await re.lstat(_),!H(n)))return;Z=await re.readlink(_,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;C({path:A,size:null,type:"other",reason:he(R)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!J.isSymbolicLink()||!Hr($,J)||J.mtimeMs!==$.mtimeMs||J.ctimeMs!==$.ctimeMs||!M.equals(Z)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=M.byteLength;if(h.length>=r.maxFiles){C({path:A,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:A,size:D,type:"other",reason:"file-size"});return}if(w+D>r.maxTotalBytes){C({path:A,size:D,type:"other",reason:"total-size"});return}let oe=bc("sha256").update("symlink\0").update(M).digest("hex");H(n)&&await j({path:A,hash:oe,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:M,stat:J})},Rt=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,oe;try{if(D=await re.realpath(A.target),!H(n))return;oe=await re.lstat(A.target)}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;Y(_,{path:_,size:null,type:"file",reason:me(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!oe.isFile()||oe.isSymbolicLink()||!Hr(A.stat,oe)||oe.size!==A.stat.size||oe.mtimeMs!==A.stat.mtimeMs||oe.ctimeMs!==A.stat.ctimeMs)&&Y(_,{path:_,size:oe.isFile()?oe.size:null,type:oe.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,oe;try{if(D=await re.lstat(A.target),!H(n))return;oe=await re.readlink(A.target,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;Y(_,{path:_,size:null,type:"other",reason:me(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Hr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(oe))&&Y(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,M;try{if($=await re.realpath(A.target),!H(n))return;M=await re.lstat(A.target)}catch{if(!H(n))return;Y(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!($===A.realTarget&&M.isDirectory()&&!M.isSymbolicLink()&&Hr(A.stat,M)&&B(c,$)&&!bt(u,$))){Y(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let J;try{if(!H(n))return;J=await Ww(n,$)}catch(D){if(on(D))throw D;Y(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;J.dirty?Y(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):J.hash!==A.hash&&Y(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await re.lstat(A);if(!H(n))return;C({path:_,size:$.isFile()?$.size:null,type:$.isFile()?"file":$.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch($){if(!H(n))return;if(he($))continue;if(!me($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},ae=await ty(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(ae===null){let _=await Vw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let M of _.records){if(M.type!=="file"&&M.type!=="symlink"||g.has(M.path))continue;if(Nt(n)<1)break;if(!Jw(i,M.path,n))continue;if(Nt(n)<1)break;let Z=F.resolve(s,...M.path.split("/")),J;try{J=await re.lstat(Z)}catch(D){if(!H(n))break;if(!me(D)&&!he(D))throw D;C({path:M.path,size:null,type:"file",reason:he(D)?"changed-during-read":"unreadable"});continue}if(Nt(n)<1)break;if(M.type==="symlink"&&J.isSymbolicLink()){if(await X(Z,M.path,J),Nt(n)<1)break;continue}if(M.type!=="file"||!J.isFile()||J.isSymbolicLink()){C({path:M.path,size:J.isFile()?J.size:null,type:J.isDirectory()?"directory":J.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Re(Z,M.path,J),Nt(n)<1)break}Nt(n)>=1&&await Rt();let A=await Vw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=LI(_.evidence,A.evidence);E=$.evidence;for(let M of[..._.omissions,...A.omissions,...$.omissions])v.some(Z=>Z.path===M.path&&Z.reason===M.reason)||C(M)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let R=mi(_);for(let ie of R.entries)ie.gitObjectId!==void 0&&A.set(ie.path,ie);$=A.size>0}let M=new Set,Z=!0;try{let R=await Ha(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)$=!1,Z=!1,A.clear();else for(let ie of R.records){let se=yc(ie),_e=se.indexOf(" "),xe=_e<0?null:sn(se.slice(_e+1));if(_e!==1||xe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");se[0]!=="H"&&M.add(xe)}}catch(R){if(on(R))throw R;$=!1,Z=!1,A.clear()}let J=new Set;try{let R=await wc(n,s,["ls-files","--modified","-z"],If);for(let ie of R.toString("utf8").split("\0")){let se=sn(ie);se!==null&&J.add(se)}}catch{$=!1,Z=!1,A.clear()}let D=new Set,oe=new Set;for(let R of ny(ae)){if(g.has(R)||!Oa(e,R))continue;if(Nt(n)<1)break;if(!Jw(i,R,n))continue;if(Nt(n)<1)break;let ie=F.resolve(s,...R.split("/"));if(ie===f||ie===p||bt(d,ie)||m.some(ze=>bt(ze,ie)))continue;if(ae.gitlinks.has(R)){if(h.length>=r.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let ze,Eo;try{[ze,Eo]=await Promise.all([re.realpath(ie),re.lstat(ie)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Eo.isSymbolicLink()||!Eo.isDirectory()||!B(c,ze)||bt(u,ze)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let _i=await Ww(n,ze);if(_i.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await j({path:R,hash:_i.hash,size:0,type:"file"},{kind:"gitlink",target:ie,realTarget:ze,stat:Eo,hash:_i.hash})}catch(_i){if(on(_i))throw _i;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let se;try{se=await re.lstat(ie)}catch(ze){if(he(ze)&&ae.tracked.has(R)){b.set(R,ie);continue}if(!me(ze)&&!he(ze))throw ze;C({path:R,size:null,type:"file",reason:he(ze)?"changed-during-read":"unreadable"});continue}if(se.isSymbolicLink()){await X(ie,R,se);continue}if(!se.isFile()){ae.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let _e=ae.trackedObjectIds.get(R),xe=_e?A.get(R):void 0;if($&&xe?.gitObjectId!==void 0&&xe.gitObjectId===_e&&!M.has(R)&&!J.has(R)){if(h.length>=r.maxFiles){C({path:R,size:xe.size,type:"file",reason:"file-count"});continue}if(xe.size>r.maxFileBytes){C({path:R,size:xe.size,type:"file",reason:"file-size"});continue}if(w+xe.size>r.maxTotalBytes){C({path:R,size:xe.size,type:"file",reason:"total-size"});continue}h.push({...xe}),w+=xe.size,D.add(R);continue}let bh=Z&&!M.has(R)&&!J.has(R)?_e:void 0;await Re(ie,R,se,bh),bh!==void 0&&oe.add(R)}if(await Rt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await ry(n,e,a,ae,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&oe.size>0){let R=await wc(n,s,["ls-files","--modified","-z"],If),ie=new Set;for(let se of R.toString("utf8").split("\0")){let _e=sn(se);_e!==null&&ie.add(_e)}for(let se of D){if(!ie.has(se))continue;let _e=h.find(xe=>xe.path===se);Y(se,{path:se,size:_e?.size??null,type:"file",reason:"changed-during-read"})}for(let se of oe){if(!ie.has(se))continue;let _e=h.find(xe=>xe.path===se);_e&&delete _e.gitObjectId}}for(let R of ae.omissions)C(R);ae.overflow&&O(ae.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let dS=ae===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...ae.evidence?{gitSelection:ae.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:dS,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:v,omittedCount:S,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${x}`,hash:x,count:N}}:{}}}async function Of(e,t,r={}){let n=(await ke(e.projectRoot))?.native.snapshot??Fd;return uy(e,{...r,policy:t.policy,incrementalBaseline:t,maxSelectionRecords:n.max_selection_records,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Sc(e,t){let r=XI(e,t),i=we(e,r);await V(i,r);try{let n=await Tw({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return mi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var gc,jf,lI,uI,dI,fI,pI,hI,mI,vI,gI,wI,yI,NI,bI,kI,SI,EI,kc,Yw,xI,cn,If,CI,PI,RI,Tf,_I,qI,ln=I(()=>{"use strict";le();Ge();Lt();Tt();U();yt();ua();gc={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},jf=1e3,lI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),dI=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),fI=new Set(["schema","include","exclude","hash"]),pI=new Set(["provider","gitSelection","physicalSelection","projection"]),hI=new Set(["provider","selection"]),mI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),vI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),gI=new Set(["schema","status","before","after"]),wI=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),yI=new Set(["path","hash","size","type","gitObjectId"]),NI=new Set(["path","size","type","reason"]),bI=new Set(["ref","hash","count"]),kI=new Set(["change-created","legacy-migration","explicit"]),SI=new Set(["file","directory","other"]),EI=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),kc=/^[a-f0-9]{64}$/u,Yw=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,xI=new Set(["EACCES","EPERM"]),cn=64*1024,If=64*1024,CI=6e4,PI=1e3,RI=2,Tf={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},_I={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};qI=(1n<<256n)-1n});function Xy(){Xj+=1}var Xj,Qy=I(()=>{"use strict";Xj=0});import{execFileSync as Qj}from"node:child_process";function tT(e,t){Xy();try{return Qj("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Zj,maxBuffer:eT,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Kf(e,t,i)}}function Ue(e,t){return tT(e,t).trim()}var Zj,eT,Kf,Et=I(()=>{"use strict";Qy();Zj=3e4,eT=8*1024*1024,Kf=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as uT}from"node:fs";import dT from"node:path";function Mc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Vc(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 aN(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 gT(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 oN(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));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 uN(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===tp&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!sN(e.children,l)),cN(i)?i:null}if(e.schema===wi&&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=>!sN(e.children,a)),cN(i)?i:null}return null}function sN(e,t){return e.some(r=>r.covers.includes(t))}function cN(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Br(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 wT(e){let t=Mc(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=Mc(n,`Native children acceptance_index.${i}`);if(Vc(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 yT(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));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 c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function dN(e,t,r={}){let i=(0,lN.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Mc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==wi&&a!==Lr)throw Vc(n,nN,"Native children contract"),new Error(`Native children schema must be ${wi} or ${Lr}`);let o=a===wi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Vc(n,o==="indexed-v2"?pT:nN,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let m=Mc(f,`Native child ${p}`);if(Vc(m,o==="indexed-v2"?vT:o==="summary-v2"?mT:hT,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!fT.test(m.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){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:h?m.summary:null,depends_on:aN(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?aN(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(m=>!u.has(m));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}gT(c);let d=r.policy==="advisory";if(a===tp){if(o==="indexed-v2"){let f=wT(n.acceptance_index);d||yT(f,t,r);let p=Object.keys(f);return d||oN(c,p,p),{schema:Lr,acceptance_index:f,children:c}}return{schema:Lr,children:c}}return t&&!d&&oN(c,t),{schema:wi,children:c}}async function Mt(e){let t=dT.join(e.changeDir,ep);try{await uT.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ee({root:e.changeDir,ref:ep}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=dN(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?uN(a,e.acceptanceIds,e.validation??{}):null}}var lN,ep,wi,Lr,tp,fT,nN,pT,hT,mT,vT,Wc=I(()=>{"use strict";lN=Gt(It(),1);et();ep="children.yaml",wi="comet.native.children.v1",Lr="comet.native.children.v2",tp=Lr,fT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nN=new Set(["schema","children"]),pT=new Set(["schema","acceptance_index","children"]),hT=new Set(["name","depends_on","covers"]),mT=new Set(["name","summary","depends_on"]),vT=new Set(["name","depends_on","covers"])});var zc,rp=I(()=>{"use strict";zc=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 Ua=I(()=>{"use strict"});var Jc=I(()=>{"use strict";rp();Ua()});function or(e,t){if(!bT.test(e))throw new Error(`${t} must be a Git commit`)}function ip(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Uc(e){or(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:np(e.contract,i.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Ka,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function np(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Kc(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var bT,Ka,Gc,yi=I(()=>{"use strict";ce();Jc();bT=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Ka="comet.native.supervisor.v2",Gc=3});import Ya from"node:path";import{promises as pN}from"node:fs";function ap(e,t){return Ya.join(vt(e,t),"supervisor")}function Xa(e,t){return Ya.join(ap(e,t),"state.json")}function hN(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==Ka)throw new Error(`Native Supervisor state schema must be ${Ka}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(or(t.integration.targetCommit,"Native Supervisor target commit"),or(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");or(n.candidateCommit,"Native Supervisor integration candidate commit"),or(n.integrationCommit,"Native Supervisor integration check commit"),fN(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&or(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(or(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&fN(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Ke(e,t,r={}){try{let i=await pN.readFile(Xa(e,t),"utf8"),n=JSON.parse(i);if(hN(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(wt(),wf)),c=await s(Ya.join(o.changesDir,t,"comet-state.yaml")),l=await Mt({changeDir:Ya.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Br(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=np(l.contract,u.name),u.contractHash=T("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(wt(),wf)),s=await o(Ya.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Vr(e,t){hN(t),await pN.mkdir(e.changesRuntimeDir,{recursive:!0}),await Fe(Xa(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function fN(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var Mr=I(()=>{"use strict";le();ce();Wc();U();yi()});var op=I(()=>{"use strict"});function st(e){return e.replace(kT,"$1 [REDACTED]").replace(ST,"[REDACTED PRIVATE KEY]").replace(ET,"$1[REDACTED]@").replace(xT,"[REDACTED TOKEN]").replace(CT,'$1"[REDACTED]"').replace(PT,"$1$2$1$3$4[REDACTED]$4").replace(RT,"$1$2[REDACTED]")}var kT,ST,ET,xT,CT,PT,RT,Ni=I(()=>{"use strict";kT=/\b(Bearer|Basic)\s+[^\s"']+/giu,ST=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,ET=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,xT=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,CT=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,PT=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,RT=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{accessSync as NW,constants as bW,createWriteStream as kW,existsSync as SW,promises as EW,statSync as IT}from"node:fs";import bi from"node:path";function jT(e,t){let r=bi.relative(e,t);return r===""||!bi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${bi.sep}`)}function mN(e,t){if(t.length===0||t.includes("\\")||bi.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||bi.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=bi.resolve(e),i=bi.resolve(r,...t.split("/"));if(!jT(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=IT(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var Yc=I(()=>{"use strict";Js();op();Ni()});var vN=I(()=>{"use strict";Et();Yc();ce()});var Xc=I(()=>{"use strict";Et();le()});import{createHash as _N}from"node:crypto";import kN from"path";function Ce(e,t){return e<t?-1:e>t?1:0}function fp(e){if(!mp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function s$(e,t){return e===t?0:e===null?-1:t===null?1:Ce(e,t)}function zr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=kN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||kN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function jN(e,t){return e==="."?e:zr(e,t)}function wn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function c$(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:zr(e.path,`${t} path`),hash:e.hash,size:wn(e.size,`${t} size`),type:"file"}}function l$(e,t){return{path:jN(e.path,`${t} path`),size:e.size===null?null:wn(e.size,`${t} size`),type:e.type,reason:e.reason}}function u$(e,t){return Ce(e.path,t.path)||Ce(e.hash,t.hash)||e.size-t.size}function d$(e,t){return Ce(e.path,t.path)||Ce(e.reason,t.reason)||Ce(e.type,t.type)||(e.size??-1)-(t.size??-1)}function to(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
163
|
-
`,"utf8")}function
|
|
164
|
-
${
|
|
165
|
-
`),e.omissionOverflow&&
|
|
166
|
-
`);let r=0;vp(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Wr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)io(o,n.path)&&(a+=1,Wr(t,"change-attribution",o));Wr(t,"change-end",{attributionCount:a}),a===0&&Wr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Wr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function qN(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=v$(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let k=new Set(r.externalDrift.paths),E=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!E.has(C)||n.some(O=>io(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(k.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=T(Za,e),c=T(Za,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[k,E]of[["baseline",e],["current",t]])for(let y of E.omitted){if(l.length>=o$)break;l.push(sr({kind:"snapshot-omission",source:k,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${k} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...EN("baseline",e),...EN("current",t),...o.totalChanges===0&&a===null?[sr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(r.gitChangedPaths===void 0)return;let k=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>k.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!k.has(E))}},m=k=>{let E=o.candidates.slice(0,k.detailedChangeCount),y=E.filter(ae=>ae.attributedTo.length===0&&!u.has(ae.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,j=d-k.detailedOmissionCount,Y=O+j,Re=[...y.map(ae=>sr({kind:"unattributed-change",source:"implementation-scope",path:ae.path,evidence:{after:ae.after,before:ae.before,changeKind:ae.kind}},`Changed path is not covered by a declared artifact: ${ae.path}`)),...l.slice(0,k.detailedOmissionCount),...f,...Y>0?[DN(k.overflowHash,{changes:C,unattributed:O,unresolved:Y})]:[]],X=h$(Re),Rt=k.includeGitAdvisory?p():void 0;return{schema:dp,contractHash:i,baselineProjectionRef:fp(s),baselineProjectionHash:s,currentProjectionRef:fp(c),currentProjectionHash:c,complete:X.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:X,noCodeReason:a,...Rt?{gitAdvisory:Rt}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let k=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b});if(to({...k,scopeHash:b})<=Si)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>v?w$({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:v}):b,x=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N}),w={...x,scopeHash:T(IN,x)};if(to(w)>Si)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function wp(e){let t=pp(e.baseline),r=pp(e.current),i=HN(e);return{authority:i,baseline:t,current:r,scope:qN(t,r,i)}}function Wt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zt(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function ki(e,t){if(typeof e!="string"||!mp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function CN(e,t,r){let i=fp(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function el(e,t){let r=Wt(e,"Native snapshot projection");if(zt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==AN)throw new Error("Native snapshot projection schema is invalid");let i=mi({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=pp(i);if(T(Za,r)!==T(Za,n))throw new Error("Native snapshot projection is not canonical");let a=T(Za,n);if(t!==void 0&&ki(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function yp(e,t){let r=Wt(e,`Declared artifact ${t}`);if(zt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:zr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function PN(e,t){if(e===null)return null;let r=Wt(e,t);return zt(r,["hash","size"],[],t),{hash:ki(r.hash,`${t} hash`),size:wn(r.size,`${t} size`)}}function RN(e,t){let r=Wt(e,`Implementation change ${t}`);if(zt(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(yp),n=ro(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=PN(r.before,`Implementation change ${t} before`),o=PN(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:zr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function N$(e,t){let r=Wt(e,`Unresolved scope ${t}`);zt(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?jN(r.path,`Unresolved scope ${t} path`):zr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function eo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>zr(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ce);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function FN(e){let t=Wt(e,"Native implementation external drift");if(zt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=eo(t.paths,"Native external drift paths");return ON({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function tl(e){let t=Wt(e,"Native implementation scope"),r=[...y$].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(zt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==dp)throw new Error("Native implementation scope schema is invalid");let i=ki(t.contractHash,"Implementation scope contractHash"),n=ki(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=CN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=ki(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=CN(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(yp);if(JSON.stringify(c)!==JSON.stringify(ro(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(RN),u=[...l].sort((y,C)=>Ce(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>io(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(RN),p=t.externalDrift===void 0?void 0:FN(t.externalDrift),m=new Set(p?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(N$),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:g$(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...h.map(y=>sr({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&S===null?[sr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],x=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(hp))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(hp))||t.complete!==(v.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let w;if(t.gitAdvisory!==void 0){let y=Wt(t.gitAdvisory,"Implementation scope Git advisory");if(zt(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=eo(y.changedPaths,"Git changed paths"),O=eo(y.pathsPresentInSnapshotChanges,"Git present paths"),j=eo(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Y=[...O,...j].sort(Ce);if(JSON.stringify(Y)!==JSON.stringify(C)||j.some(Re=>l.some(X=>X.path===Re)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:j}}let k={schema:dp,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:S,...w?{gitAdvisory:w}:{},...p?{externalDrift:p}:{}},E=ki(t.scopeHash,"Implementation scope scopeHash");if(T(IN,k)!==E)throw new Error("Implementation scope content hash mismatch");return{...k,scopeHash:E}}function b$(e){let t=Wt(e,"Native implementation scope authority");if(zt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(yp);if(JSON.stringify(r)!==JSON.stringify(ro(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=eo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:FN(t.externalDrift),a=HN({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function no(e){let t=Wt(e,"Native implementation scope bundle");zt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=b$(t.authority),i=el(t.baseline),n=el(t.current),a=tl(t.scope),o=qN(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function LN(e){let t=tl(e.scope);return no({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var dp,AN,Za,IN,r$,i$,n$,mp,Si,a$,o$,y$,Ei=I(()=>{"use strict";ce();ln();dp="comet.native.implementation-scope.v2",AN="comet.native.content-snapshot-projection.v1",Za="comet.native.content-snapshot-projection.v1",IN="comet.native.implementation-scope.v2",r$="comet.native.unresolved-scope-id.v1",i$="comet.native.scope-detail-overflow.v1",n$="comet.native.snapshot-projection-overflow.v2",mp=/^[a-f0-9]{64}$/u,Si=1024*1024,a$=128,o$=128;y$=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import BN from"node:path";function cr(e,t){if(!MN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function WN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function zN(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Np(e,t,r=2e3){let i=st(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function ao(e,t){let r=BN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||BN.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function x$(e,t,r){let i=ao(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=jt(i),a=i.toLowerCase(),o=r?ao(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function bp(e){let t=ao(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function yn(e,t){return e<t?-1:e>t?1:0}function rl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function il(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function JN(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function VN(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function C$(e){let t=rl(e,"Native acceptance trace");if(il(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!MN.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=ao(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=rl(o,`Native acceptance trace entry ${s}`);if(il(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>bp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yn))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:ao(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Np(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>yn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=cr(t.traceHash,"Native acceptance trace hash");if(T(k$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function GN(e){let t=rl(e,"Native partial allowance");if(il(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(yn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:zN(t.change),scopeHash:cr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Np(t.reason,"Partial allowance reason"),confirmedSummary:Np(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:WN(t.sourceRevision),confirmedAt:JN(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=cr(t.allowanceHash,"Native partial allowance hash");if(T(S$,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function kp(e){let t=rl(e,"Native verification evidence");if(il(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=cr(t.implementationScopeHash,"Native verification implementation scope hash"),i=C$(t.acceptanceTrace),n=cr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:cr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>bp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(yn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(yn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>bp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:zN(t.change),sourceRevision:WN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:cr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:VN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:x$(t.reportRef,"Native verification report ref"),reportHash:cr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:VN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:JN(t.createdAt,"Native verification timestamp")},d=cr(t.envelopeHash,"Native verification envelope hash");if(T(E$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var MN,k$,S$,E$,nl=I(()=>{"use strict";ce();Ni();ua();Ei();MN=/^[a-f0-9]{64}$/u,k$="comet.native.acceptance-trace.v2",S$="comet.native.partial-allowance.v1",E$="comet.native.verification-evidence.v2"});import UN from"node:path";function Jr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Gr(e,t,r,i=[]){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function lr(e,t){if(typeof e!="string"||!R$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ye(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function eb(e,t){let r=Ye(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function QN(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function O$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>j$||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let r=UN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||UN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function H$(e){let t=Jr(e,"Native check receipt checker");Gr(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Jr(t.limits,"Native check receipt limits");if(Gr(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Nn||t.version!==Sp||t.hash!==YN||r.maxFiles!==Me.maxFiles||r.maxFileBytes!==Me.maxFileBytes||r.maxTotalBytes!==Me.maxTotalBytes||r.maxIssues!==Me.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Nn,version:Sp,hash:YN,limits:{...Me}}}function D$(e){let t=Jr(e,"Native check receipt contract");return Gr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:lr(t.expectedHash,"Native check expected contract hash"),beforeHash:lr(t.beforeHash,"Native check before contract hash"),afterHash:lr(t.afterHash,"Native check after contract hash")}}function q$(e){let t=Jr(e,"Native check receipt implementation");return Gr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:lr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:lr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:lr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:lr(t.afterSnapshotHash,"Native check after snapshot hash")}}function F$(e,t){let r=Jr(e,`Native check batch ${t}`);Gr(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Ye(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Ye(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Ye(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Ye(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Ye(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Ye(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Me.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Me.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function L$(e){let t=Jr(e,"Native check receipt counts");Gr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Ye(t.filesSelected,"Native check filesSelected"),filesScanned:Ye(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ye(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ye(t.bytesScanned,"Native check bytesScanned"),issueCount:Ye(t.issueCount,"Native check issueCount"),recordedIssueCount:Ye(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(F$):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Me.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Me.maxFiles||r.bytesScanned>Me.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function B$(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||XN.indexOf(e.kind)-XN.indexOf(t.kind)}function V$(e){if(!Array.isArray(e)||e.length>Me.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Jr(i,`Native check issue ${n}`);if(Gr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!T$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:O$(a.path,`Native check issue ${n} path`),line:eb(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(B$);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function M$(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!$$.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=ZN.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function W$(e){return T(I$,e)}function tb(e){let t=Jr(e,"Native check receipt");if(Gr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==KN)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!_$.test(t.change))throw new Error("Native check receipt change name is invalid");let r=eb(t.sourceRevision,"Native check source revision"),i=H$(t.checker),n=D$(t.contract),a=q$(t.implementation),o=W$({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(lr(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=QN(t.startedAt,"Native check receipt startedAt"),c=QN(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=L$(t.counts),u=V$(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=M$(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Me.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Me.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:KN,change:t.change,sourceRevision:r,checker:i,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=lr(t.receiptHash,"Native check receipt content hash");if(T(P$,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var KN,P$,Nn,Sp,Me,R$,_$,A$,I$,j$,YN,T$,XN,ZN,$$,Ep=I(()=>{"use strict";ce();KN="comet.native.check-receipt.v1",P$="comet.native.check-receipt.v1",Nn="scoped-text-safety",Sp=1,Me=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),R$=/^[a-f0-9]{64}$/u,_$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,A$="comet.native.checker-policy.v1",I$="comet.native.check-input.v1",j$=2048,YN=T(A$,{policy:Nn,version:Sp,limits:Me,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),T$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),XN=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],ZN=["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"],$$=new Set(ZN)});function bn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Ur(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function ur(e,t){if(typeof e!="string"||!G$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ct(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=st(e).trim();if(!r||r.length>X$||r!==e.trim())throw new Error(`${t} is invalid`);return r}function xp(e,t){let r=Ct(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function oo(e,t,r=Ct,i=!1,n=Q$){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function eO(e,t){if(typeof e!="string"||!U$.test(e))throw new Error(`${t} is invalid`);return e}function tO(e){let t=bn(e,"Native verification receipt bindings");if(Ur(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!K$.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:ur(t.contractHash,"Native verification receipt contract hash"),scopeHash:ur(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:ur(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:ur(t.artifactHash,"Native verification receipt artifact hash")}}function rO(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Y$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function iO(e,t,r,i){let n=bn(t,`Native ${e} evidence`);if(e==="automated-check"){if(Ur(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=xp(n.startedAt,"Native automated-check start time"),o=xp(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=bn(n.worktree,"Native automated-check worktree");if(Ur(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=bn(n.afterFence,"Native automated-check after fence");if(Ur(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ct(n.executable,"Native automated-check executable"),args:oo(n.args,"Native automated-check arguments",Ct,!0),cwd:Ct(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Ct(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:ur(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:ur(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:ur(n.outputHash,"Native automated-check output hash"),outputSummary:Ct(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Ur(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=rO(n.checkReceiptRef);if(ur(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:oo(n.subjects,"Native static inspection subjects",Ct,i==="required-check"),rule:Ct(n.rule,"Native static inspection rule"),resultSummary:Ct(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Ur(n,["steps","observations"],"Native manual-evidence evidence"),{steps:oo(n.steps,"Native manual evidence steps"),observations:oo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function nO(e){let t=bn(e,"Native verification receipt");if(Ur(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=Ct(t.actor,"Native verification receipt actor"),o=oo(t.acceptanceIds,"Native receipt acceptance IDs",eO,i==="required-check",Z$).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Cp,kind:r,role:i,status:n,bindings:tO(t.bindings),acceptanceIds:o,actor:a,issuedAt:xp(t.issuedAt,"Native verification receipt issue time"),evidence:iO(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Nn||s.actor!==`native-runtime:${Nn}`))throw new Error("Native required check policy identity is invalid");return s}function rb(e){let t=bn(e,"Native verification receipt");if(Ur(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Cp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=nO(i),a=ur(t.receiptHash,"Native verification receipt hash");if(T(z$,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Pp(e){return T(J$,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Cp,z$,J$,G$,U$,K$,Y$,X$,Q$,Z$,so=I(()=>{"use strict";ce();Ep();Ni();Cp="comet.native.verification-receipt.v3",z$=Cp,J$="comet.native.declared-artifacts.v1",G$=/^[a-f0-9]{64}$/u,U$=/^acceptance-[a-f0-9]{64}$/u,K$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Y$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,X$=4096,Q$=256,Z$=1024});import{createHash as aO}from"node:crypto";import{promises as Pt}from"node:fs";import Jt from"node:path";function Rp(e,t){let r=Jt.relative(e,t);return r===""||!Jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Jt.sep}`)}function oO(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function al(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ib(e){let t=await Pt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Pt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sO(e,t){let r=Jt.resolve(e),i=Jt.resolve(t);if(!Rp(r,i))throw new Error("Native evidence path is outside its change");let n=[await ib(r)],a=r;for(let o of Jt.relative(r,i).split(Jt.sep).filter(Boolean)){a=Jt.join(a,o);let s=await ib(a);if(!Rp(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function nb(e){for(let t of e){let r=await Pt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!oO(t,r)||await Pt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function cO(e,t,r={}){let i=await sO(t,Jt.dirname(e));await r.afterParentChainCaptured?.();let n=await Pt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Pt.realpath(e);if(!Rp(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Pt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Pt.lstat(e),Pt.realpath(e)]);if(await nb(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!al(s,n)||!al(s,c))throw new Error("Native evidence document changed while opening");if(s.size>kn)throw new Error(`Native evidence document exceeds ${kn} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=kn+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>kn)throw new Error(`Native evidence document exceeds ${kn} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Pt.lstat(e),Pt.realpath(e)]);if(await nb(i),!m.isFile()||m.isSymbolicLink()||h!==a||!al(s,p)||!al(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 sb(e,t){if(!ob.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function lO(e,t,r,i,n){if(!ob.test(r))throw new Error("Native report evidence hash is invalid");let a=await xi({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"||aO("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 Sn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function uO(e,t,r,i,n){let a=sb(r,i);return n?Jt.join(n,...a.split("/")):Ir(K(e,t),a)}async function xi(e){let t=uO(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??we(e.paths,t);return await V(r,t),cO(t,r,e.hooks)}function ab(e,t){return el(e,t)}function dO(e,t){let r=tl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function fO(e,t,r){let i=GN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function pO(e,t,r){let i=kp(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function hO(e,t,r,i=!1,n){let a=await ol(e,t,r.implementationScopeRef,void 0,n);if(i&&await lO(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await cb(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function co(e,t,r,i,n){let a=Sn(r,"scopes"),o=dO(await xi({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Sn(o.baselineProjectionRef,"snapshots"),c=Sn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([xi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ab(d,s)),xi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ab(d,c))]);return LN({baseline:l,current:u,scope:o})}async function ol(e,t,r,i,n){return(await co(e,t,r,i,n)).scope}async function cb(e,t,r,i,n){let a=Sn(r,"allowances");return fO(await xi({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function lo(e,t,r,i,n){let a=Sn(r,"receipts"),o=rb(await xi({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function En(e,t,r,i,n){let a=Sn(r,"verifications"),o=pO(await xi({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await hO(e,t,o,!1,n),o}var ob,kn,K2,Kr=I(()=>{"use strict";le();U();Tt();Ei();nl();so();ob=/^[a-f0-9]{64}$/u,kn=Si,K2=3*kn});import Ri from"node:path";import{realpathSync as XH}from"node:fs";import{execFileSync as yS}from"child_process";import NS from"fs";import pr from"path";function Ai(e,t){return yS("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function jn(e,t){return kh(e)===kh(t)}function kh(e){let t=pr.resolve(e);try{let r=NS.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ve(e){try{let t=pr.resolve(Ai(e,["rev-parse","--show-toplevel"])),i=Ai(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?pr.resolve(i.slice(9)):t,a=null;try{a=Ai(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!jn(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Co(e){try{Ai(e,["rev-parse","--is-inside-work-tree"]);let t=Ai(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:pr.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function hr(e){return Co(e).map(t=>t.root)}function Al(e,t){let r=t.find(a=>jn(pr.resolve(a.root),pr.resolve(e)));if(!r)return null;let i=pr.resolve(t[0].root),n=pr.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!jn(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Ut(e,t){try{let r=Ai(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ce();var Wf=Gt(It(),1);import{promises as Ty}from"fs";import qr from"path";et();le();oi();Ge();Ee();U();yt();ln();import{createHash as Nj}from"crypto";import bj from"path";var at=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});Ee();U();import{constants as Pc,promises as kt}from"node:fs";import St from"node:path";import{TextDecoder as mj}from"node:util";import dj from"path";zi();Pr();var ij=Gt(It(),1);zi();Pr();_r();_r();Wi();$d();zi();_r();var rV=4*1024*1024;var nj=null;function aj(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function dy(e,t){return(...r)=>{let i=nj;if(i===null)return t(...r);let n=aj(`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}}Wi();var sV=dy("hookWritePolicy",async e=>(await Ad(e))?.hook??{allow_paths:[]});va();import{randomUUID as oj}from"node:crypto";import{promises as Ec}from"node:fs";import py from"node:path";var xc="comet.selection.v2",hy=16*1024;function Cc(e){return py.join(e,".comet","current-change.json")}function sj(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fy(e){return e===null||typeof e=="string"}function my(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!sj(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!fy(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:xc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==xc)throw new Error(`current change selection schema must be ${xc}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!fy(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Hf(e){let t;try{let i=Cc(e),{bytes:n}=await li(i,hy,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...my(t)}}async function Df(e,t){let r=my(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Cc(e),n=`${i}.${oj()}.tmp`;await Ec.mkdir(py.dirname(i),{recursive:!0});try{await Ec.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
167
|
-
`,"utf8"),await
|
|
168
|
-
`)])}catch(d){if(!
|
|
169
|
-
${t}`).digest("hex")}async function
|
|
175
|
+
${Buffer.byteLength(i)}:${i}`)}function wN(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function yN(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!wN(r))return e.splice(t,1),r}return null}function Jr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Rj(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await ne.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=nl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!Jr(r,c))return{status:"changed"};for(;;){if(!H(i))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!Jr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function lt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ut(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function kn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Kt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function NN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=F.posix.normalize(e);if(r!==e||F.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Pj(e,t){let r=lt(e,`Native snapshot entry ${t}`);ut(r,ej,`Native snapshot entry ${t}`);let i=NN(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!al.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Kt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!cN.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function _j(e,t){let r=lt(e,`Native snapshot omission ${t}`);if(ut(r,tj,`Native snapshot omission ${t}`),!nj.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!aj.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:NN(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Kt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function Aj(e){let t=lt(e,"Native snapshot omission overflow");if(ut(t,rj,"Native snapshot omission overflow"),typeof t.hash!="string"||!al.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:kn(t.count,"Native snapshot omission overflow count")}}function bn(e,t){let r=lt(e,t);if(ut(r,XT,t),typeof r.hash!="string"||!al.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Kt(r.recordCount,`${t} recordCount`),n=Kt(r.storedRecordCount,`${t} storedRecordCount`),a=Kt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function aN(e){let t=lt(e,"Native Git selection evidence");if(ut(t,YT,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=bn(t.stageBefore,"Native Git selection stageBefore"),i=bn(t.combined,"Native Git selection combined"),n=bn(t.stageAfter,"Native Git selection stageAfter"),a=bn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=bn(t.finalCombined,"Native Git selection finalCombined"),s=bn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Ur(r,n)||!Ur(n,a)||!Ur(i,o)||!Ur(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function oN(e,t){let r=lt(e,t);if(ut(r,ZT,t),typeof r.hash!="string"||!al.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Kt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Kt(r.recordCount,`${t} recordCount`),a=Kt(r.storedRecordCount,`${t} storedRecordCount`),o=Kt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function Ij(e){let t=lt(e,"Native physical selection evidence");if(ut(t,QT,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=oN(t.before,"Native physical selection before"),i=oN(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!mN(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function Pi(e){let t=lt(e,"Native content snapshot manifest");if(ut(t,zT,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!ij.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=lt(t.capture,"Native content snapshot capture");if(ut(w,UT,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let S=w.gitSelection===void 0?void 0:aN(w.gitSelection),E=w.physicalSelection===void 0?void 0:Ij(w.physicalSelection),y=null;if(w.projection!==void 0){let C=lt(w.projection,"Native content snapshot projection");if(ut(C,KT,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:aN(C.selection)}}}if(w.provider==="git"){if(E||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...S?{gitSelection:S}:{}}}else{if(S)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(E&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...E?{physicalSelection:E}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=lt(t.limits,"Native content snapshot limits");ut(i,GT,"Native content snapshot limits");let n={maxFiles:kn(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:kn(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:kn(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:kn(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:kn(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=lt(t.policy,"Native snapshot policy");if(ut(w,JT,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=gN({include:w.include,exclude:w.exclude,hash:w.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(Pj),s=t.omitted.map(_j),c=Kt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Aj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,S)=>w+S.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Ef||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(w=>w.reason==="git-enumeration-limit"),p=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...p])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=f?.status==="overflow"||f?.status==="overflow-and-changed",h=f?.status==="changed"||f?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),g=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...g])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",N=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}async function bN(e,t,r={}){let i=Pi(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=lN(r),o=uN(r.gitSelectionLimits),s=await fN(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(vN(s).filter(S=>co(e,S))),l=[...s.gitlinks].filter(S=>c.has(S)),u=[...s.nestedRepositories].filter(S=>co(e,S)),d=(S,E)=>E.some(y=>S===y||S.startsWith(`${y}/`)),p=S=>d(S,l),f=S=>d(S,u),m=[...i.entries.map(S=>S.path),...i.omitted.flatMap(S=>S.type==="directory"?[S.path,`${S.path}/`]:[S.path])].filter(S=>!c.has(S)&&!p(S)&&!f(S)),h=await fj(a,n,m),v=i.entries.filter(S=>!p(S.path)&&!f(S.path)&&co(e,S.path)&&(c.has(S.path)||!h.has(S.path)));await hN(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let S of l)g.push({path:S,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((S,E)=>S.path.localeCompare(E.path,"en"));let b=i.omitted.filter(S=>p(S.path)||f(S.path)||!co(e,S.path)?!1:h.has(S.path)?c.has(S.path)||[...c].some(E=>E.startsWith(`${S.path}/`)):!0);for(let S of g)b.some(E=>E.path===S.path&&E.reason===S.reason)||b.push(S);b.sort((S,E)=>S.path.localeCompare(E.path,"en"));let k=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??ee("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=il(N,"git-selection",{source:"git-selection",...s.overflow}));let x=S=>{k+=1,N=il(N,"omission",S)};for(;b.length>Ef;){let S=yN(b);if(S===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(S)}return Pi({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+k===0,entries:v,omitted:b,omittedCount:b.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}})}function Tj(e,t){if(!WT.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(Y(e,t),"baseline-manifest.json")}async function kN(e,t={}){let r={maxFiles:t.limits?.maxFiles??el.maxFiles,maxFileBytes:t.limits?.maxFileBytes??el.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??el.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??el.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=gN(t.policy),n=lN({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=uN(t.gitSelectionLimits,t.maxSelectionRecords),o=dj(t.physicalSelectionLimits,t.maxSelectionRecords);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=F.resolve(e.projectRoot),c=await ne.realpath(s),l=F.resolve(e.nativeRoot),u=await ne.realpath(l),d=F.resolve(e.runtimeDir),p=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),m=Sj(s,t.denylist??[]),h=[],v=[],g=new Map,b=new Map,k=0,N=0,x=ee("comet.native.snapshot-omission-overflow.v1"),w=0,S=!1,E=null,y=_=>{N+=1,x=il(x,"omission",_)},C=_=>{if(k+=1,v.length<Ef){v.push(_);return}if(wN(_)){let A=yN(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),v.push(_);return}y(_)},O=_=>{k+=_.count,N+=_.count,x=il(x,"git-selection",{source:"git-selection",..._})},T=async(_,A)=>{h.push(_),w+=_.size,g.set(_.path,A),S||(S=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let $=h.findIndex(te=>te.path===_);if($<0)return;let[W]=h.splice($,1);w-=W.size,g.delete(_),C(A)},Te=async(_,A,$,W)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let te;try{te=await ne.realpath(_)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:$.size,type:"file",reason:ve(P)?"changed-during-read":"unreadable"});return}if(!H(n)||!q(c,te)||Pt(u,te))return;if(h.length>=r.maxFiles){C({path:A,size:$.size,type:"file",reason:"file-count"});return}if($.size>r.maxFileBytes){C({path:A,size:$.size,type:"file",reason:"file-size"});return}if(w+$.size>r.maxTotalBytes){C({path:A,size:$.size,type:"file",reason:"total-size"});return}let J,D,le;try{if(J=await Rj(te,$.size,$,n),J.status==="budget-exhausted"||!H(n))return;if(J.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(le=await ne.realpath(_),!H(n)))return;D=await ne.lstat(_)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:$.size,type:"file",reason:ve(P)?"changed-during-read":"unreadable"});return}if(H(n)){if(J.bytes!==$.size||le!==te||!Jr($,J.finalStat)||!Jr(J.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==$.size||D.mtimeMs!==$.mtimeMs||D.ctimeMs!==$.ctimeMs){C({path:A,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await T({path:A,hash:J.hash,size:D.size,type:"file",...W===void 0?{}:{gitObjectId:W}},{kind:"file",target:_,realTarget:te,stat:D})}},Z=async(_,A,$)=>{if(!H(n))return;let W,te,J;try{if(W=await ne.readlink(_,{encoding:"buffer"}),!H(n)||(J=await ne.lstat(_),!H(n)))return;te=await ne.readlink(_,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:null,type:"other",reason:ve(P)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!J.isSymbolicLink()||!Jr($,J)||J.mtimeMs!==$.mtimeMs||J.ctimeMs!==$.ctimeMs||!W.equals(te)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=W.byteLength;if(h.length>=r.maxFiles){C({path:A,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:A,size:D,type:"other",reason:"file-size"});return}if(w+D>r.maxTotalBytes){C({path:A,size:D,type:"other",reason:"total-size"});return}let le=nl("sha256").update("symlink\0").update(W).digest("hex");H(n)&&await T({path:A,hash:le,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:W,stat:J})},Ot=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,le;try{if(D=await ne.realpath(A.target),!H(n))return;le=await ne.lstat(A.target)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;Q(_,{path:_,size:null,type:"file",reason:ge(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!le.isFile()||le.isSymbolicLink()||!Jr(A.stat,le)||le.size!==A.stat.size||le.mtimeMs!==A.stat.mtimeMs||le.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:le.isFile()?le.size:null,type:le.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,le;try{if(D=await ne.lstat(A.target),!H(n))return;le=await ne.readlink(A.target,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;Q(_,{path:_,size:null,type:"other",reason:ge(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Jr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(le))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,W;try{if($=await ne.realpath(A.target),!H(n))return;W=await ne.lstat(A.target)}catch{if(!H(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!($===A.realTarget&&W.isDirectory()&&!W.isSymbolicLink()&&Jr(A.stat,W)&&q(c,$)&&!Pt(u,$))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let J;try{if(!H(n))return;J=await rN(n,$)}catch(D){if(Sn(D))throw D;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;J.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):J.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await ne.lstat(A);if(!H(n))return;C({path:_,size:$.isFile()?$.size:null,type:$.isFile()?"file":$.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch($){if(!H(n))return;if(ve($))continue;if(!ge($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},ce=await fN(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(ce===null){let _=await eN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let W of _.records){if(W.type!=="file"&&W.type!=="symlink"||g.has(W.path))continue;if(Rt(n)<1)break;if(!nN(i,W.path,n))continue;if(Rt(n)<1)break;let te=F.resolve(s,...W.path.split("/")),J;try{J=await ne.lstat(te)}catch(D){if(!H(n))break;if(!ge(D)&&!ve(D))throw D;C({path:W.path,size:null,type:"file",reason:ve(D)?"changed-during-read":"unreadable"});continue}if(Rt(n)<1)break;if(W.type==="symlink"&&J.isSymbolicLink()){if(await Z(te,W.path,J),Rt(n)<1)break;continue}if(W.type!=="file"||!J.isFile()||J.isSymbolicLink()){C({path:W.path,size:J.isFile()?J.size:null,type:J.isDirectory()?"directory":J.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Te(te,W.path,J),Rt(n)<1)break}Rt(n)>=1&&await Ot();let A=await eN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=bj(_.evidence,A.evidence);E=$.evidence;for(let W of[..._.omissions,...A.omissions,...$.omissions])v.some(te=>te.path===W.path&&te.reason===W.reason)||C(W)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let P=Pi(_);for(let ae of P.entries)ae.gitObjectId!==void 0&&A.set(ae.path,ae);$=A.size>0}let W=new Set,te=!0;try{let P=await lo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)$=!1,te=!1,A.clear();else for(let ae of P.records){let ue=rl(ae),je=ue.indexOf(" "),Pe=je<0?null:En(ue.slice(je+1));if(je!==1||Pe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ue[0]!=="H"&&W.add(Pe)}}catch(P){if(Sn(P))throw P;$=!1,te=!1,A.clear()}let J=new Set;try{let P=await tl(n,s,["ls-files","--modified","-z"],Sf);for(let ae of P.toString("utf8").split("\0")){let ue=En(ae);ue!==null&&J.add(ue)}}catch{$=!1,te=!1,A.clear()}let D=new Set,le=new Set;for(let P of vN(ce)){if(g.has(P)||!co(e,P))continue;if(Rt(n)<1)break;if(!nN(i,P,n))continue;if(Rt(n)<1)break;let ae=F.resolve(s,...P.split("/"));if(ae===p||ae===f||Pt(d,ae)||m.some(Ye=>Pt(Ye,ae)))continue;if(ce.gitlinks.has(P)){if(h.length>=r.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Ye,is;try{[Ye,is]=await Promise.all([ne.realpath(ae),ne.lstat(ae)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(is.isSymbolicLink()||!is.isDirectory()||!q(c,Ye)||Pt(u,Ye)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let zi=await rN(n,Ye);if(zi.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await T({path:P,hash:zi.hash,size:0,type:"file"},{kind:"gitlink",target:ae,realTarget:Ye,stat:is,hash:zi.hash})}catch(zi){if(Sn(zi))throw zi;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ue;try{ue=await ne.lstat(ae)}catch(Ye){if(ve(Ye)&&ce.tracked.has(P)){b.set(P,ae);continue}if(!ge(Ye)&&!ve(Ye))throw Ye;C({path:P,size:null,type:"file",reason:ve(Ye)?"changed-during-read":"unreadable"});continue}if(ue.isSymbolicLink()){await Z(ae,P,ue);continue}if(!ue.isFile()){ce.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let je=ce.trackedObjectIds.get(P),Pe=je?A.get(P):void 0;if($&&Pe?.gitObjectId!==void 0&&Pe.gitObjectId===je&&!W.has(P)&&!J.has(P)){if(h.length>=r.maxFiles){C({path:P,size:Pe.size,type:"file",reason:"file-count"});continue}if(Pe.size>r.maxFileBytes){C({path:P,size:Pe.size,type:"file",reason:"file-size"});continue}if(w+Pe.size>r.maxTotalBytes){C({path:P,size:Pe.size,type:"file",reason:"total-size"});continue}h.push({...Pe}),w+=Pe.size,D.add(P);continue}let xm=te&&!W.has(P)&&!J.has(P)?je:void 0;await Te(ae,P,ue,xm),xm!==void 0&&le.add(P)}if(await Ot(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await hN(n,e,a,ce,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&le.size>0){let P=await tl(n,s,["ls-files","--modified","-z"],Sf),ae=new Set;for(let ue of P.toString("utf8").split("\0")){let je=En(ue);je!==null&&ae.add(je)}for(let ue of D){if(!ae.has(ue))continue;let je=h.find(Pe=>Pe.path===ue);Q(ue,{path:ue,size:je?.size??null,type:"file",reason:"changed-during-read"})}for(let ue of le){if(!ae.has(ue))continue;let je=h.find(Pe=>Pe.path===ue);je&&delete je.gitObjectId}}for(let P of ce.omissions)C(P);ce.overflow&&O(ce.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let DE=ce===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...ce.evidence?{gitSelection:ce.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:DE,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:v,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${x}`,hash:x,count:N}}:{}}}async function Rf(e,t,r={}){let n=(await xe(e.projectRoot))?.native.snapshot??Pp;return kN(e,{...r,policy:t.policy,incrementalBaseline:t,maxSelectionRecords:n.max_selection_records,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function ol(e,t){let r=Tj(e,t),i=Ne(e,r);await V(i,r);try{let n=await Wy({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return Pi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var el,Ef,WT,zT,GT,JT,UT,KT,YT,XT,QT,ZT,ej,tj,rj,ij,nj,aj,al,cN,oj,xn,Sf,sj,cj,lj,xf,uj,yj,Cn=I(()=>{"use strict";Gi();oe();Qe();Ut();Lt();K();Ct();Ha();el={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Ef=1e3,WT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zT=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),GT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),JT=new Set(["schema","include","exclude","hash"]),UT=new Set(["provider","gitSelection","physicalSelection","projection"]),KT=new Set(["provider","selection"]),YT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),XT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),QT=new Set(["schema","status","before","after"]),ZT=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),ej=new Set(["path","hash","size","type","gitObjectId"]),tj=new Set(["path","size","type","reason"]),rj=new Set(["ref","hash","count"]),ij=new Set(["change-created","legacy-migration","explicit"]),nj=new Set(["file","directory","other"]),aj=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),al=/^[a-f0-9]{64}$/u,cN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,oj=new Set(["EACCES","EPERM"]),xn=64*1024,Sf=64*1024,sj=6e4,cj=1e3,lj=2,xf={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},uj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};yj=(1n<<256n)-1n});import{execFileSync as $$}from"node:child_process";function D$(e,t){try{return Qn(()=>$$("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:O$,maxBuffer:H$,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Mf(e,t,i)}}function Je(e,t){return D$(e,t).trim()}var O$,H$,Mf,pt=I(()=>{"use strict";Gi();O$=3e4,H$=8*1024*1024,Mf=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as V0}from"node:fs";import W0 from"node:path";function Il(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Al(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 Ab(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 Y0(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 Ib(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));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 Ob(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===sh&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!Tb(e.children,l)),jb(i)?i:null}if(e.schema===$i&&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=>!Tb(e.children,a)),jb(i)?i:null}return null}function Tb(e,t){return e.some(r=>r.covers.includes(t))}function jb(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Zr(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 X0(e){let t=Il(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=Il(n,`Native children acceptance_index.${i}`);if(Al(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 Q0(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));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 c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let p=["source","text"].filter(f=>d[f]!==u[f]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${p.join(", ")} exactly from the current acceptance catalog`)}}}function Hb(e,t,r={}){let i=(0,$b.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Il(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==$i&&a!==Qr)throw Al(n,_b,"Native children contract"),new Error(`Native children schema must be ${$i} or ${Qr}`);let o=a===$i?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Al(n,o==="indexed-v2"?G0:_b,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((p,f)=>{let m=Il(p,`Native child ${f}`);if(Al(m,o==="indexed-v2"?K0:o==="summary-v2"?U0:J0,`Native ${s} child fields (child ${f})`),typeof m.name!="string"||!z0.test(m.name))throw new Error(`Native child ${f} name is invalid`);let h=o==="summary-v2";if(h){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:h?m.summary:null,depends_on:Ab(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Ab(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:p})=>p);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let p of c){let f=p.depends_on.filter(m=>!u.has(m));if(f.length>0)throw new Error(`Native child ${p.name} depends on unknown child: ${f.join(", ")}`)}Y0(c);let d=r.policy==="advisory";if(a===sh){if(o==="indexed-v2"){let p=X0(n.acceptance_index);d||Q0(p,t,r);let f=Object.keys(p);return d||Ib(c,f,f),{schema:Qr,acceptance_index:p,children:c}}return{schema:Qr,children:c}}return t&&!d&&Ib(c,t),{schema:$i,children:c}}async function Qt(e){let t=W0.join(e.changeDir,oh);try{await V0.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await re({root:e.changeDir,ref:oh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Hb(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Ob(a,e.acceptanceIds,e.validation??{}):null}}var $b,oh,$i,Qr,sh,z0,_b,G0,J0,U0,K0,Tl=I(()=>{"use strict";$b=ir(Bt(),1);at();oh="children.yaml",$i="comet.native.children.v1",Qr="comet.native.children.v2",sh=Qr,z0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_b=new Set(["schema","children"]),G0=new Set(["schema","acceptance_index","children"]),J0=new Set(["name","depends_on","covers"]),U0=new Set(["name","summary","depends_on"]),K0=new Set(["name","depends_on","covers"])});var Ro=I(()=>{"use strict"});var jl=I(()=>{"use strict";qc();Ro()});function gr(e,t){if(!eO.test(e))throw new Error(`${t} must be a Git commit`)}function ch(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Ol(e){gr(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:lh(e.contract,i.name),contractHash:j("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Po,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function lh(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Hl(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var eO,Po,$l,Oi=I(()=>{"use strict";de();jl();eO=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Po="comet.native.supervisor.v2",$l=3});import _o from"node:path";import{promises as Bb}from"node:fs";function uh(e,t){return _o.join(Et(e,t),"supervisor")}function Ao(e,t){return _o.join(uh(e,t),"state.json")}function Fb(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==Po)throw new Error(`Native Supervisor state schema must be ${Po}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(gr(t.integration.targetCommit,"Native Supervisor target commit"),gr(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");gr(n.candidateCommit,"Native Supervisor integration candidate commit"),gr(n.integrationCommit,"Native Supervisor integration check commit"),Db(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&gr(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(gr(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&Db(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function et(e,t,r={}){try{let i=await Bb.readFile(Ao(e,t),"utf8"),n=JSON.parse(i);if(Fb(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(xt(),uf)),c=await s(_o.join(o.changesDir,t,"comet-state.yaml")),l=await Qt({changeDir:_o.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Zr(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=lh(l.contract,u.name),u.contractHash=j("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(xt(),uf)),s=await o(_o.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ei(e,t){Fb(t),await Bb.mkdir(e.changesRuntimeDir,{recursive:!0}),await Oe(Ao(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Db(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var ti=I(()=>{"use strict";oe();de();Tl();K();Oi()});var dh=I(()=>{"use strict"});function mt(e){return e.replace(tO,"$1 [REDACTED]").replace(rO,"[REDACTED PRIVATE KEY]").replace(iO,"$1[REDACTED]@").replace(nO,"[REDACTED TOKEN]").replace(aO,'$1"[REDACTED]"').replace(oO,"$1$2$1$3$4[REDACTED]$4").replace(sO,"$1$2[REDACTED]")}var tO,rO,iO,nO,aO,oO,sO,Hi=I(()=>{"use strict";tO=/\b(Bearer|Basic)\s+[^\s"']+/giu,rO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,iO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,nO=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,aO=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,oO=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,sO=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{accessSync as $G,constants as OG,createWriteStream as HG,existsSync as DG,promises as BG,statSync as uO}from"node:fs";import Di from"node:path";function dO(e,t){let r=Di.relative(e,t);return r===""||!Di.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Di.sep}`)}function Lb(e,t){if(t.length===0||t.includes("\\")||Di.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Di.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Di.resolve(e),i=Di.resolve(r,...t.split("/"));if(!dO(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=uO(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var Dl=I(()=>{"use strict";ea();dh();Hi()});var qb=I(()=>{"use strict";pt();Dl();de()});var Bl=I(()=>{"use strict";pt();oe()});import{createHash as ek}from"node:crypto";import Jb from"path";function Ae(e,t){return e<t?-1:e>t?1:0}function gh(e){if(!Nh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function LO(e,t){return e===t?0:e===null?-1:t===null?1:Ae(e,t)}function ii(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=Jb.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Jb.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function ik(e,t){return e==="."?e:ii(e,t)}function Dn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function qO(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:ii(e.path,`${t} path`),hash:e.hash,size:Dn(e.size,`${t} size`),type:"file"}}function MO(e,t){return{path:ik(e.path,`${t} path`),size:e.size===null?null:Dn(e.size,`${t} size`),type:e.type,reason:e.reason}}function VO(e,t){return Ae(e.path,t.path)||Ae(e.hash,t.hash)||e.size-t.size}function WO(e,t){return Ae(e.path,t.path)||Ae(e.reason,t.reason)||Ae(e.type,t.type)||(e.size??-1)-(t.size??-1)}function $o(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
176
|
+
`,"utf8")}function ri(e,t,r){let i=`${t}
|
|
177
|
+
${aa(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function zO(e){if($o(e)<=Fi)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=ek("sha256");a.update(`${DO}
|
|
178
|
+
`),e.omissionOverflow&&ri(a,"existing-overflow",e.omissionOverflow);let o=(p,f)=>{f||(i+=1),n+=1,ri(a,"omission",p)},s=p=>{i+=1,n+=1,ri(a,"entry",p)},c=()=>{for(let p=r.length-1;p>=0;p-=1){let f=r[p];if(!(f.reason==="git-enumeration-limit"||f.reason==="git-selection-changed"||f.reason==="physical-enumeration-limit"||f.reason==="physical-selection-changed"))return r.splice(p,1),f}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;$o(u)>Fi;){if(r.filter(f=>f.reason!=="git-enumeration-limit"&&f.reason!=="git-selection-changed"&&f.reason!=="physical-enumeration-limit"&&f.reason!=="physical-selection-changed").length>0){let f=Math.max(1,Math.ceil(r.length/4));for(let m=0;m<f;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let f=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-f))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function wh(e){let t=Pi(e),r=t.entries.map((n,a)=>qO(n,`Snapshot entry ${a}`));if(r.sort(VO),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>MO(n,`Snapshot omission ${a}`));return i.sort(WO),zO({schema:tk,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Oo(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:ii(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>Ae(r.path,i.path)||Ae(r.kind,i.kind))}function Ho(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Ub(e){return e?{hash:e.hash,size:e.size}:null}function bh(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ae(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&r({path:u,kind:c?l?"modified":"removed":"added",before:Ub(c),after:Ub(l)})}}function nk(e,t){return{...e,attributedTo:t.filter(r=>Ho(r,e.path))}}function kh(e){let t=Oo(e.declaredArtifacts),r=[];return bh(e.baseline,e.current,i=>{r.push(nk(i,t))}),r}function wr(e,t){return{id:`scope:${j(OO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function GO(e,t){let r=t.omitted.map(i=>wr({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(wr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(wr({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function Kb(e,t){return GO(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function yh(e,t){return Ae(e.kind,t.kind)||Ae(e.source,t.source)||LO(e.path,t.path)||Ae(e.id,t.id)}function JO(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(yh)}function ak(e){return[...new Set(e.map((t,r)=>ii(t,`Git path ${r}`)))].sort(Ae)}function Yb(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function UO(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function ok(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=ak(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Yb(e.baseCommit,"Native external drift base commit"),targetBranch:UO(e.targetBranch,"Native external drift target branch"),targetCommit:Yb(e.targetCommit,"Native external drift target commit"),paths:t}}function sk(e){if(typeof e.contractHash!="string"||!Nh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Oo(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:ak(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:ok(e.externalDrift)}}}function KO(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,p=0;return bh(e,t,f=>{let m=r.some(h=>Ho(h,f.path));if(d+=1,c.push(f.path),!m&&!n?.has(f.path)&&(p+=1),o?.has(f.path)&&s.push(f.path),!u&&a.length<BO){let h=nk(f,r),v=$o(h);l+v<=Fi?(a.push(h),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:p}}function ck(e,t){return wr({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function YO(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:Dn(Number(t[1]),"Scope overflow change count"),unresolved:Dn(Number(t[2]),"Scope overflow unresolved count"),unattributed:Dn(Number(t[3]),"Scope overflow unattributed count")},i=Bi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(ck(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function XO(e){let t=ek("sha256");t.update(`${HO}
|
|
179
|
+
`);let r=0;bh(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){ri(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Ho(o,n.path)&&(a+=1,ri(t,"change-attribution",o));ri(t,"change-end",{attributionCount:a}),a===0&&ri(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&ri(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function lk(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=KO(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let S=new Set(r.externalDrift.paths),E=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!E.has(C)||n.some(O=>Ho(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(S.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(To,e),c=j(To,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[S,E]of[["baseline",e],["current",t]])for(let y of E.omitted){if(l.length>=FO)break;l.push(wr({kind:"snapshot-omission",source:S,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${S} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,p=[...Kb("baseline",e),...Kb("current",t),...o.totalChanges===0&&a===null?[wr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(r.gitChangedPaths===void 0)return;let S=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>S.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!S.has(E))}},m=S=>{let E=o.candidates.slice(0,S.detailedChangeCount),y=E.filter(ce=>ce.attributedTo.length===0&&!u.has(ce.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,T=d-S.detailedOmissionCount,Q=O+T,Te=[...y.map(ce=>wr({kind:"unattributed-change",source:"implementation-scope",path:ce.path,evidence:{after:ce.after,before:ce.before,changeKind:ce.kind}},`Changed path is not covered by a declared artifact: ${ce.path}`)),...l.slice(0,S.detailedOmissionCount),...p,...Q>0?[ck(S.overflowHash,{changes:C,unattributed:O,unresolved:Q})]:[]],Z=JO(Te),Ot=S.includeGitAdvisory?f():void 0;return{schema:vh,contractHash:i,baselineProjectionRef:gh(s),baselineProjectionHash:s,currentProjectionRef:gh(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:Z,noCodeReason:a,...Ot?{gitAdvisory:Ot}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let S=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b});if($o({...S,scopeHash:b})<=Fi)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>v?XO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:v}):b,x=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N}),w={...x,scopeHash:j(rk,x)};if($o(w)>Fi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function Sh(e){let t=wh(e.baseline),r=wh(e.current),i=sk(e);return{authority:i,baseline:t,current:r,scope:lk(t,r,i)}}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function er(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Bi(e,t){if(typeof e!="string"||!Nh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xb(e,t,r){let i=gh(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function ql(e,t){let r=Zt(e,"Native snapshot projection");if(er(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==tk)throw new Error("Native snapshot projection schema is invalid");let i=Pi({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=wh(i);if(j(To,r)!==j(To,n))throw new Error("Native snapshot projection is not canonical");let a=j(To,n);if(t!==void 0&&Bi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Eh(e,t){let r=Zt(e,`Declared artifact ${t}`);if(er(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ii(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Qb(e,t){if(e===null)return null;let r=Zt(e,t);return er(r,["hash","size"],[],t),{hash:Bi(r.hash,`${t} hash`),size:Dn(r.size,`${t} size`)}}function Zb(e,t){let r=Zt(e,`Implementation change ${t}`);if(er(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Eh),n=Oo(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Qb(r.before,`Implementation change ${t} before`),o=Qb(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:ii(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function ZO(e,t){let r=Zt(e,`Unresolved scope ${t}`);er(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?ik(r.path,`Unresolved scope ${t} path`):ii(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function jo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>ii(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ae);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function uk(e){let t=Zt(e,"Native implementation external drift");if(er(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=jo(t.paths,"Native external drift paths");return ok({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Ml(e){let t=Zt(e,"Native implementation scope"),r=[...QO].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(er(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==vh)throw new Error("Native implementation scope schema is invalid");let i=Bi(t.contractHash,"Implementation scope contractHash"),n=Bi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Xb(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Bi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Xb(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Eh);if(JSON.stringify(c)!==JSON.stringify(Oo(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Zb),u=[...l].sort((y,C)=>Ae(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>Ho(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(Zb),f=t.externalDrift===void 0?void 0:uk(t.externalDrift),m=new Set(f?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(p)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(ZO),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:YO(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(y=>wr({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&k===null?[wr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],x=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(yh))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(yh))||t.complete!==(v.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let w;if(t.gitAdvisory!==void 0){let y=Zt(t.gitAdvisory,"Implementation scope Git advisory");if(er(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=jo(y.changedPaths,"Git changed paths"),O=jo(y.pathsPresentInSnapshotChanges,"Git present paths"),T=jo(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Q=[...O,...T].sort(Ae);if(JSON.stringify(Q)!==JSON.stringify(C)||T.some(Te=>l.some(Z=>Z.path===Te)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let S={schema:vh,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:p,unresolvedScopes:v,noCodeReason:k,...w?{gitAdvisory:w}:{},...f?{externalDrift:f}:{}},E=Bi(t.scopeHash,"Implementation scope scopeHash");if(j(rk,S)!==E)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:E}}function eH(e){let t=Zt(e,"Native implementation scope authority");if(er(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(Eh);if(JSON.stringify(r)!==JSON.stringify(Oo(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=jo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:uk(t.externalDrift),a=sk({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Do(e){let t=Zt(e,"Native implementation scope bundle");er(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=eH(t.authority),i=ql(t.baseline),n=ql(t.current),a=Ml(t.scope),o=lk(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function dk(e){let t=Ml(e.scope);return Do({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var vh,tk,To,rk,OO,HO,DO,Nh,Fi,BO,FO,QO,Li=I(()=>{"use strict";de();Cn();vh="comet.native.implementation-scope.v2",tk="comet.native.content-snapshot-projection.v1",To="comet.native.content-snapshot-projection.v1",rk="comet.native.implementation-scope.v2",OO="comet.native.unresolved-scope-id.v1",HO="comet.native.scope-detail-overflow.v1",DO="comet.native.snapshot-projection-overflow.v2",Nh=/^[a-f0-9]{64}$/u,Fi=1024*1024,BO=128,FO=128;QO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import pk from"node:path";function yr(e,t){if(!hk.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function vk(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function xh(e,t,r=2e3){let i=mt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Bo(e,t){let r=pk.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||pk.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function nH(e,t,r){let i=Bo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Ft(i),a=i.toLowerCase(),o=r?Bo(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function Ch(e){let t=Bo(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Bn(e,t){return e<t?-1:e>t?1:0}function Vl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function gk(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function fk(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function aH(e){let t=Vl(e,"Native acceptance trace");if(Wl(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!hk.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=Bo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Vl(o,`Native acceptance trace entry ${s}`);if(Wl(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Ch(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Bn))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Bo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:xh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Bn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=yr(t.traceHash,"Native acceptance trace hash");if(j(tH,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function wk(e){let t=Vl(e,"Native partial allowance");if(Wl(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Bn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:vk(t.change),scopeHash:yr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:xh(t.reason,"Partial allowance reason"),confirmedSummary:xh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:mk(t.sourceRevision),confirmedAt:gk(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=yr(t.allowanceHash,"Native partial allowance hash");if(j(rH,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Rh(e){let t=Vl(e,"Native verification evidence");if(Wl(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=yr(t.implementationScopeHash,"Native verification implementation scope hash"),i=aH(t.acceptanceTrace),n=yr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:yr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>Ch(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Bn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(Bn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(p=>Ch(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Bn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:vk(t.change),sourceRevision:mk(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:yr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:fk(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:nH(t.reportRef,"Native verification report ref"),reportHash:yr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:fk(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:gk(t.createdAt,"Native verification timestamp")},d=yr(t.envelopeHash,"Native verification envelope hash");if(j(iH,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var hk,tH,rH,iH,zl=I(()=>{"use strict";de();Hi();Ha();Li();hk=/^[a-f0-9]{64}$/u,tH="comet.native.acceptance-trace.v2",rH="comet.native.partial-allowance.v1",iH="comet.native.verification-evidence.v2"});import yk from"node:path";function ni(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ai(e,t,r,i=[]){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Nr(e,t){if(typeof e!="string"||!sH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function xk(e,t){let r=tt(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function Sk(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function hH(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>dH||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let r=yk.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||yk.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function mH(e){let t=ni(e,"Native check receipt checker");ai(t,["policy","version","hash","limits"],"Native check receipt checker");let r=ni(t.limits,"Native check receipt limits");if(ai(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Fn||t.version!==Ph||t.hash!==bk||r.maxFiles!==Ue.maxFiles||r.maxFileBytes!==Ue.maxFileBytes||r.maxTotalBytes!==Ue.maxTotalBytes||r.maxIssues!==Ue.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Fn,version:Ph,hash:bk,limits:{...Ue}}}function vH(e){let t=ni(e,"Native check receipt contract");return ai(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Nr(t.expectedHash,"Native check expected contract hash"),beforeHash:Nr(t.beforeHash,"Native check before contract hash"),afterHash:Nr(t.afterHash,"Native check after contract hash")}}function gH(e){let t=ni(e,"Native check receipt implementation");return ai(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Nr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Nr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Nr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Nr(t.afterSnapshotHash,"Native check after snapshot hash")}}function wH(e,t){let r=ni(e,`Native check batch ${t}`);ai(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:tt(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:tt(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:tt(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:tt(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:tt(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:tt(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Ue.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Ue.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function yH(e){let t=ni(e,"Native check receipt counts");ai(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:tt(t.filesSelected,"Native check filesSelected"),filesScanned:tt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:tt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:tt(t.bytesScanned,"Native check bytesScanned"),issueCount:tt(t.issueCount,"Native check issueCount"),recordedIssueCount:tt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(wH):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Ue.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Ue.maxFiles||r.bytesScanned>Ue.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function NH(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||kk.indexOf(e.kind)-kk.indexOf(t.kind)}function bH(e){if(!Array.isArray(e)||e.length>Ue.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=ni(i,`Native check issue ${n}`);if(ai(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!pH.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:hH(a.path,`Native check issue ${n} path`),line:xk(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(NH);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function kH(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!fH.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=Ek.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function SH(e){return j(uH,e)}function Ck(e){let t=ni(e,"Native check receipt");if(ai(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Nk)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!cH.test(t.change))throw new Error("Native check receipt change name is invalid");let r=xk(t.sourceRevision,"Native check source revision"),i=mH(t.checker),n=vH(t.contract),a=gH(t.implementation),o=SH({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Nr(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=Sk(t.startedAt,"Native check receipt startedAt"),c=Sk(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=yH(t.counts),u=bH(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=kH(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let p=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==p)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Ue.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Ue.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let f={schema:Nk,change:t.change,sourceRevision:r,checker:i,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=Nr(t.receiptHash,"Native check receipt content hash");if(j(oH,f)!==m)throw new Error("Native check receipt content hash mismatch");return{...f,receiptHash:m}}var Nk,oH,Fn,Ph,Ue,sH,cH,lH,uH,dH,bk,pH,kk,Ek,fH,_h=I(()=>{"use strict";de();Nk="comet.native.check-receipt.v1",oH="comet.native.check-receipt.v1",Fn="scoped-text-safety",Ph=1,Ue=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),sH=/^[a-f0-9]{64}$/u,cH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lH="comet.native.checker-policy.v1",uH="comet.native.check-input.v1",dH=2048,bk=j(lH,{policy:Fn,version:Ph,limits:Ue,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),pH=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),kk=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Ek=["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"],fH=new Set(Ek)});function Ln(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function oi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function br(e,t){if(typeof e!="string"||!CH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=mt(e).trim();if(!r||r.length>AH||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Ah(e,t){let r=jt(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function Fo(e,t,r=jt,i=!1,n=IH){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function jH(e,t){if(typeof e!="string"||!RH.test(e))throw new Error(`${t} is invalid`);return e}function $H(e){let t=Ln(e,"Native verification receipt bindings");if(oi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!PH.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:br(t.contractHash,"Native verification receipt contract hash"),scopeHash:br(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:br(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:br(t.artifactHash,"Native verification receipt artifact hash")}}function OH(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=_H.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function HH(e,t,r,i){let n=Ln(t,`Native ${e} evidence`);if(e==="automated-check"){if(oi(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Ah(n.startedAt,"Native automated-check start time"),o=Ah(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Ln(n.worktree,"Native automated-check worktree");if(oi(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Ln(n.afterFence,"Native automated-check after fence");if(oi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:jt(n.executable,"Native automated-check executable"),args:Fo(n.args,"Native automated-check arguments",jt,!0),cwd:jt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:jt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:br(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:br(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:br(n.outputHash,"Native automated-check output hash"),outputSummary:jt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){oi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=OH(n.checkReceiptRef);if(br(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Fo(n.subjects,"Native static inspection subjects",jt,i==="required-check"),rule:jt(n.rule,"Native static inspection rule"),resultSummary:jt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return oi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Fo(n.steps,"Native manual evidence steps"),observations:Fo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function DH(e){let t=Ln(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=jt(t.actor,"Native verification receipt actor"),o=Fo(t.acceptanceIds,"Native receipt acceptance IDs",jH,i==="required-check",TH).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Ih,kind:r,role:i,status:n,bindings:$H(t.bindings),acceptanceIds:o,actor:a,issuedAt:Ah(t.issuedAt,"Native verification receipt issue time"),evidence:HH(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Fn||s.actor!==`native-runtime:${Fn}`))throw new Error("Native required check policy identity is invalid");return s}function Rk(e){let t=Ln(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Ih)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=DH(i),a=br(t.receiptHash,"Native verification receipt hash");if(j(EH,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Th(e){return j(xH,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Ih,EH,xH,CH,RH,PH,_H,AH,IH,TH,Lo=I(()=>{"use strict";de();_h();Hi();Ih="comet.native.verification-receipt.v3",EH=Ih,xH="comet.native.declared-artifacts.v1",CH=/^[a-f0-9]{64}$/u,RH=/^acceptance-[a-f0-9]{64}$/u,PH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_H=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,AH=4096,IH=256,TH=1024});import{createHash as BH}from"node:crypto";import{promises as $t}from"node:fs";import tr from"node:path";function jh(e,t){let r=tr.relative(e,t);return r===""||!tr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${tr.sep}`)}function FH(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Pk(e){let t=await $t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await $t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function LH(e,t){let r=tr.resolve(e),i=tr.resolve(t);if(!jh(r,i))throw new Error("Native evidence path is outside its change");let n=[await Pk(r)],a=r;for(let o of tr.relative(r,i).split(tr.sep).filter(Boolean)){a=tr.join(a,o);let s=await Pk(a);if(!jh(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function _k(e){for(let t of e){let r=await $t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!FH(t,r)||await $t.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function qH(e,t,r={}){let i=await LH(t,tr.dirname(e));await r.afterParentChainCaptured?.();let n=await $t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await $t.realpath(e);if(!jh(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await $t.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),$t.lstat(e),$t.realpath(e)]);if(await _k(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Gl(s,n)||!Gl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>qn)throw new Error(`Native evidence document exceeds ${qn} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=qn+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>qn)throw new Error(`Native evidence document exceeds ${qn} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,m,h]=await Promise.all([o.stat(),$t.lstat(e),$t.realpath(e)]);if(await _k(i),!m.isFile()||m.isSymbolicLink()||h!==a||!Gl(s,f)||!Gl(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 Tk(e,t){if(!Ik.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function MH(e,t,r,i,n){if(!Ik.test(r))throw new Error("Native report evidence hash is invalid");let a=await qi({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"||BH("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 Mn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function VH(e,t,r,i,n){let a=Tk(r,i);return n?tr.join(n,...a.split("/")):Mr(Y(e,t),a)}async function qi(e){let t=VH(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ne(e.paths,t);return await V(r,t),qH(t,r,e.hooks)}function Ak(e,t){return ql(e,t)}function WH(e,t){let r=Ml(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function zH(e,t,r){let i=wk(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function GH(e,t,r){let i=Rh(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function JH(e,t,r,i=!1,n){let a=await Jl(e,t,r.implementationScopeRef,void 0,n);if(i&&await MH(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await jk(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function qo(e,t,r,i,n){let a=Mn(r,"scopes"),o=WH(await qi({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Mn(o.baselineProjectionRef,"snapshots"),c=Mn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([qi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Ak(d,s)),qi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Ak(d,c))]);return dk({baseline:l,current:u,scope:o})}async function Jl(e,t,r,i,n){return(await qo(e,t,r,i,n)).scope}async function jk(e,t,r,i,n){let a=Mn(r,"allowances");return zH(await qi({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Mo(e,t,r,i,n){let a=Mn(r,"receipts"),o=Rk(await qi({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Vn(e,t,r,i,n){let a=Mn(r,"verifications"),o=GH(await qi({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await JH(e,t,o,!1,n),o}var Ik,qn,uK,si=I(()=>{"use strict";oe();K();Lt();Li();zl();Lo();Ik=/^[a-f0-9]{64}$/u,qn=Fi,uK=3*qn});import Wi from"node:path";import{realpathSync as IF}from"node:fs";Gi();Ji();import{execFileSync as ix}from"child_process";import nx from"fs";import di from"path";import{AsyncLocalStorage as Pm}from"node:async_hooks";ea();var pi=new Pm,_m=new Pm;function Am(e){return pi.getStore()?e():pi.run(new Map,e)}function ax(e){let t=pi.getStore();for(let r of e)t?.set(xr(r.root),e);return e}function ra(e,t){return Qn(()=>ix("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function ia(e,t){return xr(e)===xr(t)}function xr(e){let t=di.resolve(e);try{let r=nx.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function we(e){try{let t=_m.getStore()?.get(xr(e)),r=pi.getStore()?.get(t??xr(e));if(r){let c=na(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=di.resolve(ra(e,["rev-parse","--show-toplevel"])),n=pi.getStore()?.get(xr(i))??Im(e),a=na(i,n);if(pi.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=ra(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!ia(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function cs(e){try{let t=pi.getStore()?.get(_m.getStore()?.get(xr(e))??xr(e));return t?t.map(r=>({...r})):(ra(e,["rev-parse","--is-inside-work-tree"]),Im(e))}catch{return[]}}function Im(e){let t=ox(ra(e,["worktree","list","--porcelain","-z"]));return ax(t),t.map(r=>({...r}))}function ox(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:di.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 Cr(e){return cs(e).map(t=>t.root)}function na(e,t){let r=t.find(a=>ia(di.resolve(a.root),di.resolve(e)));if(!r)return null;let i=di.resolve(t[0].root),n=di.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!ia(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function nr(e,t){try{let r=ra(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}de();var Hf=ir(Bt(),1);import{promises as zN}from"fs";import Kr from"path";at();oe();yi();Qe();Re();K();Ct();Cn();import{createHash as i$}from"crypto";import n$ from"path";var dt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});Re();K();import{constants as ul,promises as _t}from"node:fs";import At from"node:path";import{TextDecoder as Qj}from"node:util";import Uj from"path";ln();Fr();var Bj=ir(Bt(),1);ln();Fr();cr();cr();cn();Sp();ln();cr();var oW=4*1024*1024;import{AsyncLocalStorage as Fj}from"node:async_hooks";var Lj=new Fj;function qj(){let e=Lj.getStore();return e?.active?e:null}function Mj(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function SN(e,t){return(...r)=>{let i=qj();if(i===null)return t(...r);let n=Mj(`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}}cn();var pW=SN("hookWritePolicy",async e=>(await yp(e))?.hook??{allow_paths:[]});Ma();import{randomUUID as Vj}from"node:crypto";import{promises as sl}from"node:fs";import xN from"node:path";var cl="comet.selection.v2",CN=16*1024;function ll(e){return xN.join(e,".comet","current-change.json")}function Wj(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function EN(e){return e===null||typeof e=="string"}function RN(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!Wj(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!EN(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:cl,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==cl)throw new Error(`current change selection schema must be ${cl}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!EN(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Pf(e){let t;try{let i=ll(e),{bytes:n}=await ki(i,CN,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...RN(t)}}async function _f(e,t){let r=RN(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=ll(e),n=`${i}.${Vj()}.tmp`;await sl.mkdir(xN.dirname(i),{recursive:!0});try{await sl.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
180
|
+
`,"utf8"),await sl.rename(n,i)}catch(a){throw await sl.rm(n,{force:!0}),a}}Np();Da();var PN=(e,t)=>{let r=e[t];return r==null?null:String(r)};function po(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function uo(e,t){let r=po(e,t);if(Uj.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function Kj(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function _N(e){if(!e.run_id)return null;let t=po(e,"run_id"),r=po(e,"skill"),i=po(e,"skill_version"),n=po(e,"skill_hash"),a=uo(e,"pending_ref"),o=uo(e,"trajectory_ref"),s=uo(e,"context_ref"),c=uo(e,"artifacts_ref"),l=uo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:PN(e,"current_step"),iteration:u,pending:PN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Kj(e)}}var gz=Number.MAX_SAFE_INTEGER;var Yj=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Xj(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},r=_N(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function Af(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!Yj.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Xj(t)}oe();Lt();var Rn={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};function pl(e,t){let r=At.relative(e,t);return r===""||!At.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${At.sep}`)}function Zj(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function dl(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function e$(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function fl(e,t,r){let i=dt[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=At.resolve(e),a=At.resolve(n,...i.slice(8).split("/"));if(!pl(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function AN(e){let t=await _t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await _t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function t$(e,t){let r=At.resolve(e),i=At.resolve(t);if(!pl(r,i))throw new Error("Native Run path is outside its change");let n=[await AN(r)],a=r;for(let o of At.relative(r,i).split(At.sep).filter(Boolean)){a=At.join(a,o);let s;try{s=await AN(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!pl(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function IN(e){for(let t of e){let r=await _t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!e$(t,r)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function r$(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function hl(e,t,r,i,n){let a=await t$(e,At.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await _t.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=Zj(o),c=await _t.realpath(t);if(!pl(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?ul.O_RDONLY:ul.O_RDONLY|ul.O_NOFOLLOW|ul.O_NONBLOCK,u;try{u=await _t.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,p,f]=await Promise.all([u.stat(),_t.lstat(t),_t.realpath(t)]);if(await IN(a),!d.isFile()||!p.isFile()||p.isSymbolicLink()||f!==c||!dl(s,d)||!dl(s,p))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await r$(u,r,i);await n?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([u.stat(),_t.lstat(t),_t.realpath(t)]);if(await IN(a),!v.isFile()||v.isSymbolicLink()||g!==c||!dl(s,h)||!dl(s,v))throw new Error(`${i} changed while reading`);let b;try{b=new Qj("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${i} is not valid UTF-8`,{cause:k})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function TN(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function If(e){return Af(e)}async function Pn(e,t){let r=fl(e,"stateRef"),i=await hl(e,r,Rn.runStateBytes,"Native Run state",t);return i?Af(TN(i.text,"Native Run state")):null}async function _i(e,t,r){let i=fl(e,"trajectoryRef",t),n=await hl(e,i,Rn.trajectoryBytes,"Native Run trajectory",r);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Rn.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Rn.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function jN(e,t,r){return(await hl(e,fl(e,"trajectoryRef",t),Rn.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function ml(e,t,r){let i=await hl(e,fl(e,"checkpointRef",t),Rn.checkpointBytes,"Native Run checkpoint",r);return i?TN(i.text,"Native Run checkpoint"):null}var a$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Tf(e){return i$("sha256").update(e).digest("hex")}function o$(e,t){if(!a$.test(t))throw new Error(`Invalid Native change name: ${t}`);return n$.join(Y(e,t),"trajectory.jsonl")}function s$(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function c$(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function l$(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=s$(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
181
|
+
`)])}catch(d){if(!c$(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Tf(t),targetHash:Tf(l),tailHash:Tf(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function u$(e,t){let r=o$(e,t);await V(Ne(e,r),r);let i=Y(e,t),n=await jN(i,dt.trajectoryRef);return n===null?{status:"clean",file:r}:l$(r,Buffer.from(n))}async function $N(e,t){let r=await u$(e,t);return"inspection"in r?r.inspection:r}import{createHash as d$}from"node:crypto";import{promises as vl}from"node:fs";import hr from"node:path";oe();at();Re();K();var fo=/^[a-f0-9]{64}$/u,ON=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,p$=16*1024,$f=process.platform,f$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function _n(e){return f$.has(e)}function FN(e,t){let r=hr.relative(e,t);return hr.isAbsolute(r)||r===".."||r.startsWith(`..${hr.sep}`)?null:r.replaceAll("\\","/")||"."}function LN(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function qN(e,t){if(e.length===0||LN(e)||e.includes("\\")||hr.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=hr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Of(e,t){return d$("sha256").update(`${e}
|
|
182
|
+
${t}`).digest("hex")}async function HN(e,t){let r=await vl.realpath(t),i=await vl.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=$f==="win32"?hr.normalize(r).toLowerCase():r;return Of(e,`${n}
|
|
170
183
|
${i.dev}
|
|
171
184
|
${i.ino}
|
|
172
|
-
${i.birthtimeMs}`)}async function
|
|
185
|
+
${i.birthtimeMs}`)}async function DN(e,t){let r=await vl.realpath(t),i=await vl.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=$f==="win32"?hr.normalize(r).toLowerCase():r;return Of(e,n)}function h$(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 jf(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||LN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function MN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(jf(e.changeBranch,"Native workspace change branch"),jf(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 m$(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"||!ON.test(t.baseCommit)||typeof t.targetCommit!="string"||!ON.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");jf(t.targetBranch,"Native workspace Git target branch")}function gl(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"||!fo.test(String(t.projectRootId))||!fo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");h$(t.capturedAt),qN(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&&!fo.test(String(t.projectRootPathId))||a&&!fo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!fo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&m$(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(MN(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 v$(e,t){return hr.join(Y(e,t),"workspace.json")}function g$(e,t){let r=v$(e,t),i=Ne(e,r),n=FN(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:qN(n,"Native workspace file ref")}}async function w$(e,t){try{let r=g$(e,t),i=await re({root:r.root,ref:r.ref,maxBytes:p$});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ho(e,t){let r=we(e.projectRoot),i={projectRoot:hr.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await mr(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await An({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function y$(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=FN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=we(e.paths.projectRoot),i=r.isGitWorktree?nr(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:nr(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([HN("comet.native.workspace-project-root.v2",e.paths.projectRoot),HN("comet.native.workspace-native-root.v2",e.paths.nativeRoot),DN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),DN("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&MN(e.binding);let p={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Of("comet.native.workspace-session.v2",`${s}
|
|
173
186
|
${c}
|
|
174
|
-
${e.sessionId}`)}:{}},
|
|
175
|
-
`).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}async function
|
|
176
|
-
`).trim()}function
|
|
177
|
-
`))}function Uj(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Jy))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Jy))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Gy(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Uy(e.markdown)},markdown:e.markdown}}function Kj(e,t){return Ky(e.id,t.id)}function Ky(e,t){return e<t?-1:e>t?1:0}function Yy(e){let t=Gy(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(Uj).sort((d,f)=>Ky(d.snapshot.capability,f.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=uf(e.briefMarkdown,t,Wa.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...df(f,d.source,Wa.maxAcceptanceCriteria-a.length)),a.push(...fw(f,d.source,Wa.maxAcceptanceCriteria-a.length)));if(a.sort(Kj),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Wa.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Wa.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Uy(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=T(Gj,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:T(Jj,u)}}var Yj={maxSpecs:64};async function hn(e){if(e.specChanges.length>Yj.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ee({root:e.changeDir,ref:e.briefRef,maxBytes:null}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ee({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Yy({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Ge();Ee();import{promises as lT}from"node:fs";import Qf from"node:path";Et();import{promises as rT}from"node:fs";le();Aa();import Zy from"node:path";function za(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ja(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 mn(e,t){return e===null?null:Oe(e,t)}function vn(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 iT(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 nT(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function gn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Yf(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 aT(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 Xf(e,t){let r=Oe(e,t);if(!Zy.isAbsolute(r))throw new Error(`${t} must be absolute`);return Zy.resolve(r)}function oT(e,t){let r=`Native local checks[${t}]`,i=za(e,r);if(Ja(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=gn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Yf(i.startedAt,`${r}.startedAt`),s=Yf(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=vn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=za(i.activeProcess,`${r}.activeProcess`),d=gn(u.status,["starting","running"],`${r}.activeProcess.status`);if(Ja(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:vn(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:nT(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:vn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Xf(i.cwd,`${r}.cwd`),exitCode:iT(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Oe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:gn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:Oe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function sT(e){let t="Native local execution state",r=za(e,t);if(Ja(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==oc)throw new Error(`Native local execution schema must be ${oc}`);let i=za(r.workspace,"Native local workspace");Ja(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=za(r.execution,"Native local execution");Ja(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Yf(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:gn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:gn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:mn(o.executionId,"Native local execution.executionId"),status:gn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:vn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:aT(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:vn(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(oT);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:oc,change:Oe(r.change,"Native local change"),basedOnStateVersion:vn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:mn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:mn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:mn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:mn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Xf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Xf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:mn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:Oe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function Lc(e){let t;try{t=await rT.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return sT(r)}function eN(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}wt();U();var tN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rN="comet-state.yaml",iN="state.json";function gi(e,t){if(!tN.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Qf.join(e.changesDir,t);if(!B(e.changesDir,r))throw new Error("Native change path escaped");return r}function Bc(e,t){return Qf.join(gi(e,t),rN)}function Fr(e,t){return Qf.join(vt(e,t),iN)}async function Ga(e,t){try{let r=await lT.readFile(Bc(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function ot(e,t){return jr(Bc(e,t))}async function Zf(e){let t=await ot(e.paths,e.name),r=Fr(e.paths,e.name);try{let i=await Lc(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}le();et();ce();var bN=Gt(It(),1);import{promises as zT}from"node:fs";import xt from"node:path";Et();et();ce();Ge();U();wt();Wc();Wc();yi();Mr();Et();Ks();le();ce();Yc();Ee();U();vN();yi();Mr();Xc();Et();Ge();Xc();ka();U();var Qc=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function sp(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}import VT from"node:path";Et();Ge();Ee();yi();Mr();async function Zc(e){let t=sp(e.parent),r=Ut(e.paths.projectRoot,t);if(!r)return null;let i=Ut(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=hr(e.paths.projectRoot).map(o=>VT.resolve(o)).find(o=>ve(o).currentBranch===t);if(!n)return null;let a=Uc({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return ip(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function cp(e,t){let r=xt.normalize(xt.resolve(e)),i=xt.normalize(xt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function JT(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function GT(e){let t=JT(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function lp(e){try{let t=await ee({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return GT(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function up(e){return T("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function UT(e){let t=hr(e.projectRoot);t.some(i=>cp(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>xt.resolve(n)))]){let n=await ke(i);n&&r.push({projectRoot:i,paths:await Ot(i,n.native.artifact_root),parent:cp(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function KT(e,t){let r=xt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await jr(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function YT(e,t){let r;try{r=await zT.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=xt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await jr(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function XT(e,t,r){let i=xt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${xt.sep}`))return null;let n=i.split(xt.sep).join("/");try{let a=(0,bN.parseDocument)(Ue(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:Be(a.toJS({mapAsMap:!1}))}catch{return null}}function QT(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function NN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Qa(e){let t=xt.join(e.paths.changesDir,e.state.name),r=await lp(t),i=null,n;try{n=await Mt({changeDir:t,validation:Br(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await Ke(e.paths,e.state.name,{diagnostics:!0});if(g){let b=Kc(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(S=>({...S,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=up({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Lr){let g=await Ke(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let x=await Zc({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await Vr(e.paths,x))}}if(g){let N=Kc(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let b=new Map(n.contract.children.map(N=>[N.name,N])),S=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==N.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of S){if(N.status!=="ready")continue;b.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:S,readyChildren:S.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await UT(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let S of await YT(g,l)){let N={...S,source:g,committedState:XT(g,S.file,b)};u.set(S.state.name,[...u.get(S.state.name)??[],N])}for(let S of l){let N=await KT(g,S);N&&d.set(S,[...d.get(S)??[],{source:g,state:N}])}}let f=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===g.name&&NN(w,o));if(b){f.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let S=u.get(g.name)?.[0];if(S){f.set(g.name,{kind:"blocked",phase:S.state.phase,projectRoot:S.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?f.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&f.set(g.name,QT(N[0].state,N[0].source,o))}let p=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,h=g=>{let b=m.get(g);if(b)return b;let S=p.get(g),x=S.depends_on.map(h).every(({status:O})=>O==="done"),w=f.get(g),k=w?.kind==="active"&&x?S.depends_on.filter(O=>!(u.get(O)??[]).some(({source:j,committedState:Y})=>cp(j.projectRoot,w.projectRoot)&&Y?.name===O&&NN(Y,o))):[],E,y=w?.message??null;w?.kind==="done"?(E=x?"done":"blocked",x||(y=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(E=x&&k.length===0?"active":"blocked",x?k.length>0&&(y=`Native child ${g} does not include merged dependencies: ${k.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?E="blocked":(E=s&&x?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:S.summary,dependsOn:[...S.depends_on],covers:[...S.covers],status:E,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:y};return m.set(g,C),C},v=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}wt();hi();Ua();Jc();Ee();ff();tf();wt();hi();le();oi();Ua();U();oi();Kr();Ge();var lb=Gt(It(),1);_r();var X2=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 iJ=256*1024;wt();hi();Mr();var wO=_s("en");Ge();Ee();yi();Mr();wt();hi();Et();Ks();ce();Yc();import xn from"node:path";Ee();hi();U();function bO(e,t){let r=xn.relative(xn.resolve(e),xn.resolve(t));if(xn.isAbsolute(r)||r===".."||r.startsWith(`..${xn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(xn.sep).join("/");return mN(e,i),i}function pb(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:bO(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var TG=1024*1024*1024;Ee();Jc();Ua();Mr();Ee();Mr();Ee();bf();var SK=16*1024;async function hb(e){let t=await Hf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(ui(t.selection.change),t.selection)}async function mb(e,t){return Se(e,`select change ${t}`,async()=>{ui(t),await Ga(e,t)?await ot(e,t):await Vt(e,t),await Df(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}U();async function vb(e,t){let r=[],i=K(e,t.name),n=Ir(i,at.stateRef),a;try{a=await dn(i)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&r.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Ir(i,a.trajectoryRef),s=await ky(e,t.name);if(s.status==="repairable")return r.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await vi(i,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Ir(i,a.checkpointRef);try{let u=await jc(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}ln();import VO from"path";import{isDeepStrictEqual as Dp}from"util";le();Lt();ka();Ee();U();yt();Ni();ce();ce();var Cn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var kO=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function SO(e,t){return e<t?-1:e>t?1:0}function EO(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!kO.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(SO)}function Ap(e=[]){return EO(e,"Native repair failed check IDs",Cn.maxFailedCheckIds,!0)}function gb(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function xO(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:gb(e.failedAcceptanceIds,t.failedAcceptanceIds)&&gb(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Ip(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(xO(i,a))break;r+=1,i=a}return r}nl();Ei();function jp(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var wb="repairStagnation",Xe={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},PO=/^[a-f0-9]{64}$/u;var RO=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),_O=["data","runId","sequence","timestamp","type"],yb=["disposition","overrideSummaryHash","signatureHash"],AO=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Nb=12;function $p(e,t){return e<t?-1:e>t?1:0}function bb(e,t,r){let i=Object.keys(e).sort($p);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function cl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function mo(e,t){if(typeof e!="string"||!PO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function IO(e){if(!Array.isArray(e)||e.length>Cn.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort($p)}function kb(e){if(typeof e!="string"||e.length===0||e.length>Xe.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Tp(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Xe.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xe.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Xe.maxTextCharacters&&(!n||e.length>Xe.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Xe.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Xe.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Tp(s,t+1,r,`${i}[${c}]`));return}let a=cl(e,i),o=Object.keys(a);if(o.length>Xe.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xe.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Xe.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Tp(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function jO(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function TO(e,t,r){let i=cl(e,`Native repair trajectory event ${t+1}`);if(bb(i,_O,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(jO(i.timestamp),typeof i.type!="string"||!RO.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(kb(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Tp(i.data,0,n,"Native trajectory event data"),cl(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Op(e){let t=cl(e,"Native repair trajectory projection"),r=Object.keys(t).sort($p),i=r.length===yb.length&&r.every((l,u)=>l===yb[u]);i||bb(t,AO,"Native repair trajectory projection");let n=mo(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:mo(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=mo(t.contractHash,"Native repair trajectory contract hash"),s=IO(t.failedAcceptanceIds),c=Ap(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function $O(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function OO(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??Nb;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Ip({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<Cn.warningAtConsecutiveFailures?"continue":a<Cn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function HO(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??Nb;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Sb(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xe.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=kb(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=TO(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Xe.maxTotalDataNodes||c>Xe.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?mo(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?mo(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,wb)){if(i?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Op(f[wb]);if($O(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&p!==null&&n!==null&&p!==n&&(r.length=0,o=0),p!==null&&(n=p),OO(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");HO(m,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>Cn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function Eb(e){return Sb(e).history}function xb(e){let t=Sb(e).latestProjection;return t?{...t}:null}Lt();var Pn={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:[]},Hp=Q("comet-native-runtime:v3:scope-reopen"),DO=[{skillVersion:"3",skillHash:Q("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Q("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Q("comet-native-runtime:v1")}];function Cb(e){return e.skillVersion===Pn.definition.metadata.version&&e.skillHash===Hp||DO.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Lt();Lt();function Pb(e){return Q(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}xa();var jb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],MO=new Set(jb),Tb=new Set([...jb,"minimum_runtime_version","revision"]),WO=new Set([...Tb,"operation"]),qp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),zO=new Set([...qp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Fp=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Bp(e,t){return VO.join(K(e,t),"transition.json")}function ul(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Vp(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function ll(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!zO.has(u)),a=[...qp].find(u=>!Object.hasOwn(r,u)),o=qp.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(jp(r.summary,"Native transition journal event summary"),st(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(r.noCodeReason!==null&&(jp(r.noCodeReason,"Native transition journal event no-code reason"),st(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Op(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function JO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Lp({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Lp(e,t)}function Mp(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let i=r?JO(e.eventData,e.evidenceHash):Lp(e.eventData,e.evidenceHash),n=Ff(e.nextRun),a=e.previousRun===null?null:Ff(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function Rb(e,t,r=!1){if(e.skill!==Pn.definition.metadata.name||(r?!Cb(e):e.skillVersion!==Pn.definition.metadata.version||e.skillHash!==Hp)||e.orchestration!==Pn.definition.orchestration.mode||e.pendingRef!==at.pendingRef||e.trajectoryRef!==at.trajectoryRef||e.contextRef!==at.contextRef||e.artifactsRef!==at.artifactsRef||e.checkpointRef!==at.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function _b(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Ab(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Wp(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(Rb(o,"next Run",i||a!==null),Ab(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Rb(a,"previous Run",!0),Ab(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Dp(_b(a),_b(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function GO(e,t,r){return Q(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function $b(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function Ib(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function zp(e,t,r,i,n=!1){let a=r.eventData,o=Ib(e),s=Ib(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(i==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Dp(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(i==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Dp(e.spec_changes,t.spec_changes),l=Pb({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||r.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(i==="spec-rebase"){let c=GO(e.name,a.summary,t.spec_changes),l=Q(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function UO(e,t){let r=ul(e);if(Vp(r,WO),r.schema!==Ki)throw new Error(`Expected Native transition schema ${Ki}`);let i=ll(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${Ki} minimum_runtime_version must be ${3}`);let n=ll(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Mp(r,t),o=qt(r.previousState),s=qt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(zp(o,s,a,r.operation),Wp(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Ki,minimum_runtime_version:3,revision:n,operation:r.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function KO(e,t){let r=ul(e);if(Vp(r,MO),r.schema!==Ea)throw new Error(`Expected Native transition schema ${Ea}`);let i=Mp(r,t,!0),n=di(r.previousState),a=di(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return zp(n,a,i,$b(n,a,i.eventData),!0),Wp(n,a,i,!0),{schema:Ea,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function YO(e,t){let r=ul(e);if(Vp(r,Tb),r.schema!==Yi)throw new Error(`Expected Native transition schema ${Yi}`);if(ll(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Yi} minimum_runtime_version must be 2`);let n=ll(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Mp(r,t,!0),o=fi(r.previousState),s=fi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(zp(o,s,a,$b(o,s,a.eventData),!0),Wp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Yi,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function XO(e,t){let r=ul(e);if(r.schema===Ki)return{status:"current",journal:UO(r,t)};if(r.schema===Ea)return{status:"migration-required",journal:KO(r,t)};if(r.schema===Yi)return{status:"migration-required",journal:YO(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function QO(e,t){let r=Bp(e,t),i=we(e,r);await V(i,r);try{let n=await Or({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return XO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ob(e,t){let r=await QO(e,t);if(!r)return null;if(r.status==="migration-required")throw new Fp(t);return r.journal}var ZO=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function e0(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function t0(e){return e?e.map(e0).join(" "):null}function r0(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function ct(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function i0(e){return e.map(t=>ct(t,[],null))}function n0(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[ct("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(ct("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(ct("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),ct("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(ct("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(ct("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),ct("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Pe(e,t){let r=t.commandArgs===void 0?r0(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?t0(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??i0(t.requiredInputs??[])}}function dl(e){let r=(e.findings??[]).filter(d=>!fn(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||ZO.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Pe(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Pe(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[ct("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Pe(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Pe(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Pe(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Pe(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[ct("summary",["--summary"],"<summary>")]});if(n)return Pe(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Pe(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[ct("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Pe(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Pe(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Pe(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Pe(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Pe(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[ct("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Pe(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Pe(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=n0(e.state);return Pe(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import vo from"path";U();var Hb=8,a0={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function o0(e){let t=a0[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:fn(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function s0(e,t,r){if(!r.path)return null;let i;if(vo.isAbsolute(r.path)?i=vo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=vo.resolve(Ne(e,t.name),...r.path.split(/[\\/]/u)):i=vo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!B(e.projectRoot,i))return null;let n=vo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function c0(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Jp(e){return e.findings.map(t=>{let r=o0(t.code);return{code:t.code,message:t.message,severity:r.severity,path:s0(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:c0(r.retry,e.state,t.code),repairCommand:r.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function Gp(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,Hb),truncated:t.length>Hb}}le();import Rn from"path";Lt();U();yt();ua();Ni();var go={maxArtifacts:128},_n=/^[a-f0-9]{64}$/u;function fl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Yr(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function Db(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Up(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function l0(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Rn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Rn.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function qb(e,t){return Rn.join(K(e,t),"checkpoints","progress.json")}function wo(e,t){return Rn.join(K(e,t),"checkpoint-journal.json")}function Fb(e,t,r){if(!_n.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Rn.join(K(e,t),"checkpoints","manifests",`${r}.json`)}function u0(e){if(!_n.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Kp(e,t,r){let i=await Or({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function d0(e,t){let r=fl(e,`checkpoint manifest artifact ${t}`);pl(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=l0(Yr(r.path,`checkpoint artifact ${t} path`,4096)),n=jt(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!_n.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Up(r.size,`checkpoint artifact ${t} size`)}}function Yp(e,t){let r=fl(e,"Native checkpoint manifest");if(pl(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>go.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(d0),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Up(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function Lb(e){return Q(JSON.stringify(Yp(e,e.change)))}function Bb(e,t){let r=fl(e,"Native progress checkpoint");if(pl(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Db(r.previousRevision,"Native checkpoint previousRevision"),a=Db(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Yr(r.manifestHash,"Native checkpoint manifestHash",64);if(!_n.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=u0(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Yr(r.inputHash,"Native checkpoint inputHash",64);if(!_n.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Yr(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Up(r.artifactCount,"Native checkpoint artifactCount");if(u>go.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Yr(r.summary,"Native checkpoint summary"),f=Yr(r.nextAction,"Native checkpoint nextAction");if(st(d)!==d||st(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Yr(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function f0(e,t){let r=fl(e,"Native checkpoint journal");if(pl(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=qt(r.previousState),n=qt(r.nextState),a=Bb(r.checkpoint,t),o=Yp(r.manifest,t),s=Yr(r.inputHash,"Native checkpoint journal inputHash",64),c=Q(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!_n.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Lb(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:i,nextState:n,checkpoint:a,manifest:o}}async function p0(e,t,r){let i=Rn.resolve(e.projectRoot,...t.split("/"));if(!B(e.projectRoot,i)||B(e.nativeRoot,i)||B(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=pd(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await kf({root:e.projectRoot,file:i,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function h0(e,t){let r=qb(e,t),i=we(e,r);await V(i,r);try{return Bb(await Kp(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function m0(e,t,r){let i=Fb(e,t,r),n=we(e,i);await V(n,i);let a=await Kp(n,i,"Native checkpoint manifest"),o=Yp(a,t);if(Vb(e,o),Lb(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Xp(e,t){let r=wo(e,t),i=we(e,r);await V(i,r);try{let n=f0(await Kp(i,r,"Native checkpoint journal"),t);return Vb(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Vb(e,t){for(let r of t.artifacts){let i=pd(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function Mb(e){let t;try{t=await h0(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:qb(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await m0(e.paths,e.name,t.manifestHash);let a=Q(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await p0(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Fb(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var Wb=240,zb=8,hl=50;function Jb(e){let t=Array.from(e);return t.length<=Wb?e:`${t.slice(0,Wb-1).join("")}…`}function v0(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function g0(e){let t=[...new Set(e.map(v0))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,zb),reasonCount:e.length,codesTruncated:t.length>zb};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,hl),reasonsTruncated:e.length>hl}}}async function Gb(e){let t=null;try{let s=await Xp(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:wo(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:wo(e.paths,e.state.name)}}let r=await Mb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=g0(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:go.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:Jb(r.checkpoint.summary),nextAction:Jb(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:go.maxArtifacts}}import{promises as vH}from"node:fs";import fk from"node:path";ce();import Ub from"node:path";var w0="comet.native.archive-preflight.v1",y0="comet.native.archive-preflight.v1",N0="comet.native.archive-operation.v1",b0=/^[a-f0-9]{64}$/u,Kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,k0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ml(e,t){return e<t?-1:e>t?1:0}function S0(e,t){if(typeof e!="string"||!b0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function dr(e,t){return e===null?null:S0(e,t)}function E0(e,t){let r=Ub.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Ub.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function x0(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function C0(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function P0(e,t){if(!Kb.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let r=dr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=dr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=dr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:r,actualBaseHash:i,proposedHash:n}}function R0(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:dr(e.contractHash,"Native archive contract hash"),acceptanceHash:dr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:dr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:dr(e.reportHash,"Native archive report hash"),envelopeHash:dr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:dr(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(r=>r===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function _0(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!k0.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(ml);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function A0(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ml)}function Yb(e){if(!Kb.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(P0).sort((l,u)=>ml(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let r=t.map(l=>({...l,operationHash:T(N0,l)})),i=R0(e.evidence),n=C0(e.workspace),a=[...new Set([..._0(e.findingCodes??[]),...A0({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(ml),o=x0(e.revision),s=E0(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:r,evidence:i,workspace:n,findingCodes:a};return{schema:w0,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:T(y0,c)}}et();ce();import{createHash as I0}from"node:crypto";import Xb from"node:path";var j0="comet.native.conflict-radar.v1",We=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}),T0="comet.native.conflict-radar.v1",$0="comet.native.conflict-radar-signals.v1",O0=/^[a-f0-9]{64}$/u,ek=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,H0=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),D0=new Set(["capability","operation","baseHash"]),q0=new Set(["path","kind"]);function An(e,t){return e<t?-1:e>t?1:0}function Qp(e){return Buffer.byteLength(e,"utf8")}function Zp(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function eh(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Qp(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function F0(e,t){let r=eh(e,t,We.maxArtifactPathBytes),i=Xb.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||Xb.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function tk(e,t){if(typeof e!="string"||!O0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function L0(e,t){let r=Zp(e,D0,t),i=eh(r.capability,`${t} capability`,We.maxCapabilityBytes);if(!ek.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:tk(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function B0(e,t){let r=Zp(e,q0,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:F0(r.path,`${t} path`),kind:r.kind}}function V0(e,t){let r=Zp(e,H0,`Conflict radar change ${t}`),i=eh(r.name,`Conflict radar change ${t} name`,We.maxNameBytes);if(!ek.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>We.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>We.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>L0(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>An(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>B0(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>An(c.path,l.path)||An(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:tk(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function M0(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>We.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(V0).sort((n,a)=>An(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>We.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>We.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function W0(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function z0(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function J0(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function G0(e,t){let r=[],i=I0("sha256").update(`${$0}
|
|
178
|
-
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Tn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<We.maxSignalsPerRelationship&&r.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(W0(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=z0(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:J0(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function Qb(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function U0(e,t){return Qb(e.classification)-Qb(t.classification)||An(e.left,t.left)||An(e.right,t.right)}function Zb(e,t,r,i){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:j0,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function rk(e){let t=M0(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(G0(t[s],t[c]));r.sort(U0);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=T(T0,{changes:t,relationships:i}),a=r.slice(0,We.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Zb(t,r,a,n);for(;a.length>0&&Qp(JSON.stringify(o))>We.maxSerializedBytes;)a=a.slice(0,-1),o=Zb(t,r,a,n);if(Qp(JSON.stringify(o))>We.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}Kr();yt();var K0=4096;async function Y0(e,t=We.maxChanges){try{let r=await $a({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function ik(e,t){let r=await Vt(e,t),[i,n]=await Promise.all([r.implementation_scope?ol(e,t,r.implementation_scope):null,ar(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function vl(e,t,r={}){let n=(await Y0(e,K0)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await ik(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await ik(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=rk([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}Ge();U();_a();et();Kr();ln();Ei();nl();import{execFile as sH}from"node:child_process";Js();op();import{promisify as cH}from"node:util";Ee();le();Ep();U();Tt();import{constants as th,promises as lt}from"node:fs";import In from"node:path";var Q0=/^[a-f0-9]{64}$/u,Z0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function eH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function gl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function tH(e,t){let r=In.resolve(e),i=In.resolve(t);if(!B(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...In.relative(r,i).split(In.sep).filter(Boolean)]){o&&(a=In.join(a,o));let s=await lt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await lt.realpath(a);if(n.length>0&&!B(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function ak(e){for(let t of e){let r=await lt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!eH(t,r)||await lt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function rH(e){if(!Q0.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function iH(e){let t=Z0.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function nH(e,t,r){return Ir(K(e,t),rH(r))}async function aH(e,t,r){let i=await tH(r,In.dirname(e)),n=await lt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([lt.realpath(t),lt.realpath(e)]);if(!B(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":th.O_RDONLY|th.O_NOFOLLOW|th.O_NONBLOCK,c=await lt.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),lt.lstat(e),lt.realpath(e)]);if(await ak(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!gl(n,l)||!gl(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=await c.read(m,0,m.length,null);if(b.bytesRead===0)break;p+=b.bytesRead,f.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,g]=await Promise.all([c.stat(),lt.lstat(e),lt.realpath(e)]);if(await ak(i),!v.isFile()||v.isSymbolicLink()||g!==o||!B(a,g)||!gl(l,h)||!gl(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function ok(e,t,r){let i=iH(r),n=K(e,t),a=nH(e,t,i),o=we(e,a);await V(o,a);let s=tb(await aH(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}Kr();Ee();Ni();var yo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};ln();so();Ei();var $6=64*1024;var O6=3600*1e3;var H6=cH(sH);var lH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function sk(e,t){let r=[];for(let i of lH){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function ck(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ok(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}so();var Xr=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}};function uH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function dH(e){let t=uH(e.bundle.baseline),r=await Of(e.paths,t,{origin:"explicit",now:e.now});return wp({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function uk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await co(e.paths,e.state.name,e.state.implementation_scope),r=await hn({changeDir:Ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await dH({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function dk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await uk(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function fH(e){let t=await ee({root:Ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:hw(t.text)}}function pH(e){let{receipt:t,implementationScope:r}=e,i=[],n=gp({baseline:r.baseline,current:r.current,declaredArtifacts:r.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function hH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Pp(e.implementationScope.scope.declaredArtifacts)}}async function lk(e){let t=await lo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=sk(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new Xr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await ck({paths:e.paths,state:e.state,receipt:t});if(n){let a=pH({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function mH(e){let t=hH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await lk({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Xr)return r.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await lk({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Xr)return r.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new Xr(r)}function rh(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function ih(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:rh(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([uk(e),En(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:rh(e.state.verification_result,"stale"),envelope:null};let i=await fH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await mH({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:rh(e.state.verification_result,"invalid"),envelope:null}}}function gH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function pk(e){try{return await vH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wH(e,t){try{return(await ee({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function yH(e,t,r){let i=Ma(e,r.capability);if(!B(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=fk.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await wH(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await ee({root:Ne(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function NH(e,t){return pk(Bp(e,t))}async function nh(e){let t=e.now??new Date,r=await Vt(e.paths,e.name),i=await ar(e.paths,e.name),n=await ke(e.paths.projectRoot),a=gH(r.name,t),o=fk.resolve(e.paths.nativeRoot,...a.split("/"));if(!B(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(r.spec_changes.map(m=>yH(e.paths,r.name,m))),ih({paths:e.paths,state:r,now:t}),vl(e.paths,r.name),qc(e.paths,r.name),$y(e.paths,r.name),NH(e.paths,r.name),pk(o)]);return Yb({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}U();Kr();so();Ei();async function bH(e,t){let r=K(e,t.name),i=await dn(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await jc(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await vi(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function kH(e,t){let r=await bH(e,t);return{committed:r,latest:xb(r),history:Eb(r)}}async function hk(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await kH(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}Kr();yt();U();function No(e,t){try{return ya(e,t)}catch{return}}var bo=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function EH(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function xH(e){return(await hb(e))?.change??null}function CH(e,t,r=!1,i){return dl({state:e,archiveReady:t,evidenceRetreat:r}).command}async function PH(e,t){let r=Ne(e,t.name),i=[...(await Fc(r,t.brief)).findings,...(await Wy(e,t)).findings,...await vb(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Sc(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await ly(e,n);a.complete||i.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await hn({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Ob(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await Uf(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function ah(e,t,r){let i=await xH(e)===t,n=await qd(e,t),a=await La(e,t),o;try{let y=await zf(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:No(e,t),phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,artifacts:No(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,artifacts:No(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:y.message}}if(n.status!=="available"){let y={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=Jp({paths:e,state:o,findings:[y]}),O=dl({state:o,findings:C});return{name:o.name,artifacts:No(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:Gp(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await Gb({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await hk(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await hn({changeDir:Ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Y=await En(e,o.name,o.verification_evidence);for(let Re of Y.acceptanceTrace.entries)C.set(Re.acceptanceId,Re.status==="failed"?"failed":Re.status==="missing"?"missing":"satisfied")}let O=dw({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),j=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...j?{nextPageCommand:EH(j),nextPageArgs:j}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await vl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let y=await ar(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await pn({paths:e,identity:y});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Oc({paths:e,identity:y});f.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],m=!1;if(o.phase==="verify"){let y=await dk({paths:e,state:o});m=y.freshness!=="fresh",p.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,v=[];if(o.phase==="archive")try{h=await nh({paths:e,name:o.name}),v.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await PH(e,o),...s.findings,...d,...f,...p,...l,...v].filter((y,C,O)=>O.findIndex(j=>j.code===y.code&&j.path===y.path)===C),b=Jp({paths:e,state:o,findings:g}),S=b.filter(y=>!fn(y.code)),N=o.phase==="archive"&&h?.ready===!0&&S.length===0,x=m||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),w=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),k=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=b.find(y=>y.severity==="error");return{name:o.name,artifacts:No(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:w||k?null:CH(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:Gp(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:dl({state:o,findings:b,archiveReady:N,evidenceRetreat:x,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:hl,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function mk(e){let t;try{t=await Sf({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await SH.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>bo.maxChanges))throw new Error(`Native status exceeds ${bo.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}U();var sh=Gt(It(),1);Et();ce();et();wt();import{promises as RH}from"node:fs";import oh from"node:path";var wl=class extends Error{};async function ch(e,t){let r=await ee({root:e.nativeRoot,ref:oh.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,sh.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new wl("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:Be(i)}}async function gk(e,t,r){let i;try{i=await RH.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=oh.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await ch(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof wl)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function yl(e){return T("comet.native.status-record.v1",e)}function vk(e){let t=oh.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Ue(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=Be((0,sh.parse)(Ue(e.projectRoot,["show",`${r}:${t}`])));return yl(i)===yl(e.state)?r:null}catch{return null}}function wk(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=vk(e),i=vk(t);if(!r||!i)return!1;try{return Ue(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function yk(e,t){return e.state.archived&&t.state.archived&&yl(e.state)===yl(t.state)}import Rk from"node:path";import{promises as Nk}from"node:fs";import _H from"node:path";ce();var AH=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),IH=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),jH=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),TH=new Set(["status","summary"]);function Nl(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function bl(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function $H(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Ci(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function OH(e,t,r,i){let n=Nl(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=bl(n,AH,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Nl(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=bl(o,IH,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Nl(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=bl(c,TH,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=Nl(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:m,...h}=f,v=bl(h,jH,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],b=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(b)||m!==void 0&&m!==T("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(f.name!==g.name||f.summary!==g.summary||!$H(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let S=g.depends_on.length===0?"ready":"pending";if(f.status!==S)return`Native Supervisor child ${g.name} has progressed beyond its initial ${S} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((f.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function bk(e){let t=Xa(e.paths,e.state.name),r;try{let c=await Nk.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Ci(t,"","Native Supervisor overlay is not a regular file");r=await Nk.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Ci(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Ci(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=_H.join(e.paths.changesDir,e.state.name),a;try{a=await Mt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Ci(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await Ke(e.paths,e.state.name)}catch(c){return Ci(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Ci(t,r,"Native Supervisor overlay disappeared during inspection");let s=OH(i,e.state,a.contract,o);return s?Ci(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}Aa();yi();function He(e,t,r){return e.language==="zh-CN"?r:t}function HH(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:He(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:He(e,"Reply A or B","回复 A 或 B"),agentInstruction:He(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(He(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(He(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:He(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:He(e,"Accept the result","接受结果"),agentInstruction:He(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let n=r?.children.some(({status:c})=>c==="blocked")??!1,a=r?.children.some(({status:c})=>c==="needs-reverify")??!1,o=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=Gc)??!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(He(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(He(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 DH(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 qH(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:He(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:He(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function xk(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Pi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function kk(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function FH(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Sk(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function LH(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function BH(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 Qr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:xk({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Pi("summary","--summary"),FH(e.name,e.flag)]}}function Ek(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:He(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function VH(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function kl(e){return[Qr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Qr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function MH(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 ko(e,t,r={}){let i=LH(t)&&e.coordination_mode===void 0,n=HH(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:[Pi("summary","--summary")],commandAlternatives:[Qr({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:[Pi("summary","--summary")],commandAlternatives:[Qr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...kl({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:[Pi("summary","--summary")],commandAlternatives:[Qr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Qr({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:[Pi("summary","--summary")],commandAlternatives:[Qr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...kl({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:[Pi("summary","--summary")],commandAlternatives:kl({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:kl({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?xk({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:BH({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?[Sk("coordination-mode","--coordination-mode",mw)]:[]],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:[kk()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Gc)??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:He(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&f===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:f!==null?[f]:[Pi("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=kk();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${He(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:MH([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Ek(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>VH(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:Ek(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Sk("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...qH(e)],userCommunication:DH(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Qr({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 Ck from"node:path";function Pk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function lh(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:Pk(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:Pk(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>Ck.relative(t.projectRoot,Ck.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}U();function _k(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function Ak(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function Ik(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:JH(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:GH(i,r)}))]:[]]}function jk(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function WH(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=i!==null||r.requestCheckRounds>0;return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:n?"confirmed":"unconfirmed",...n?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function Sl(e,t,r=ve(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:Rk.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function uh(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=lh(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...ko(t),disposition:"blocked",action:"archive",commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the reported Git blocker; do not treat this archived change as complete until it succeeds."},runnerAction:{...ko(t).runnerAction,kind:"none"}}:ko(t),c=e.details?Ik(t,null,[]):[],l=Ak(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?_k(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:ya(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:Rk.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:jk(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function zH(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function El(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function JH(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:El(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function GH(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:El(e.summary,t)??""}}async function Tk(e){let t=await Zf(e),r=lh(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Qa({paths:e.paths,state:t.state}),a=await bk({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Ke(e.paths,e.name,{diagnostics:!0}),s=o?{...Sl(e.paths,t.state,e.gitContext),projectRoot:"."}:Sl(e.paths,t.state,e.gitContext),c=ko(t.state,n,{verifierExecutionRef:eN(t.state,t.local),...t.local?{verificationCheckPlans:pb(t.local,t.local.workspace.projectRoot)}:{}}),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?zH(e.paths,o):[],d=o?(()=>{let m=new Map(n?.children.map(w=>[w.name,w.status])??[]),h=w=>m.get(w.name)??w.status,v=o.children.filter(w=>h(w)==="pending"||h(w)==="ready").length,g=o.children.filter(w=>h(w)==="active"||h(w)==="verified").length,b=o.children.filter(w=>h(w)==="integrated"||h(w)==="archived").length,S=o.children.filter(w=>h(w)==="blocked"||h(w)==="needs-reverify").length,N=o.children.filter(w=>h(w)==="active"||h(w)==="blocked"||h(w)==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:El(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let k=El(w,u);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:b,blocked:S,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:b},risks:x,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&b===o.children.length?"parent-verification":v>0?"dispatch-ready-child":S>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let m=o?.stateVersion??0,h=Ik(t.state,o,u),v=Ak(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?_k(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:m}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,artifacts:ya(e.paths,t.state.name),phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:jk(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=WH(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...m?{verifierStartup:m}:{}}})(),...n?{childSummary:n.children.reduce((m,h)=>({...m,[h.status]:(m[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}le();Gs();Et();import{accessSync as _4,constants as A4,promises as dh}from"node:fs";import Ok from"node:path";Xc();Gs();var $k="comet.native.workspace-finish.v1",Hk="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Dk=new RegExp(`^${Hk}$`,"u"),UH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function KH(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==$k||typeof t.name!="string"||!Dk.test(t.name)||typeof t.transactionId!="string"||!UH.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Ok.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}return{schema:$k,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function YH(e,t){if(!Dk.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Ok.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function fh(e,t,r={}){let i=YH(e,t);try{let n=await dh.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=KH(JSON.parse(await dh.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function qk(e,t={}){let r;try{r=await dh.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${Hk})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await fh(e,a[1],t);o&&i.push(o)}return i}function xl(e,t){let r=Ri.normalize(ph(e)),i=Ri.normalize(ph(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ph(e){let t=Ri.resolve(e);try{return XH.native(t)}catch{return t}}async function Fk(e,t){let r=[];for(let i of await mk(e))t!==void 0&&i!==t||r.push({name:i,kind:await Ga(e,i)?"portable":"legacy"});return r}async function QH(e,t){let r=Ri.resolve(e),i=Co(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>xl(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>Ri.resolve(l)).sort()){let l=xl(c,r)?r:c,u=ph(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let f=await ke(l);if(!f)continue;let p=await Ot(l,f.native.artifact_root);o.push({projectRoot:l,config:f,paths:p,gitContext:Al(l,i)??ve(l),changes:await Fk(p,t)})}if(o.length===0){let c=await ke(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Ot(e,c.native.artifact_root);o.push({projectRoot:Ri.resolve(e),config:c,paths:l,gitContext:Al(e,i)??ve(e),changes:await Fk(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await gk(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await fh(c.paths,t,{onError:l})].filter(u=>u!==null):await qk(c.paths,{onError:l})}return o}function Lk(e,t){return e.workspace.bindingState==="aligned"?0:xl(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function ZH(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:d,kind:f})=>{let p=d.finishJournalErrors?.find(({name:m})=>m===n);if(f==="portable")try{let m=await ot(d.paths,n);return{source:d,name:n,kind:f,workspace:Sl(d.paths,m,d.gitContext),portableStatus:null,inspectionError:p?.message??null,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}}catch(m){return{source:d,name:n,kind:f,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:d,name:n,kind:f,workspace:a.length>1?await La(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:p?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:f})=>f.name===n).map(f=>{let p=uh({paths:d.paths,...f,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null});return{source:d,name:n,kind:"portable",workspace:p.workspace,portableStatus:p,inspectionError:d.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:f,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(f=>f.name===n).map(f=>({source:d,error:f})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(f=>f.name===n).map(f=>({source:d,error:f})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(p=>p.finishJournals?.some(({name:m})=>m===n)),f=d?.finishJournals?.find(({name:p})=>p===n);if(d&&f){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:f.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:f.result?.message??"Native workspace finish record is orphaned."},finishJournal:f});continue}}if(s.length>0){for(let f of o)if(f.kind==="portable")try{f.record=await ch(f.source.paths,Ri.join(f.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(f=>[...o,...s.filter(p=>!yk(f.record,p.record))].every(p=>p.record&&wk(f.record,p.record)));if(d){i.push(d);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((d,f)=>Lk(d,e)-Lk(f,e)||d.source.projectRoot.localeCompare(f.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>bo.maxChanges)throw new Error(`Native status discovery exceeds ${bo.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}async function eD(e,t,r){let i=await La(e.source.paths,e.name),n=null;try{n=await Hy(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:ah(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function Bk(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return uh({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await Tk({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return Bk({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return eD(e,t,r)}async function Vk(e){let{sources:t,candidates:r}=await tD(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>xl(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),ah(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}return e.onSelectedRoot?.(r[0].source.projectRoot),Bk(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function tD(e,t){let r=await QH(e,t),i=(await ZH(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}va();import So from"path";import{realpathSync as yD}from"fs";function Mk(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),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var fr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Wk(e){return e?e.command?`${fr.next} ${e.command}`:e.ask_user?`${fr.next} ${e.ask_user}`:null:null}function zk(e,t){let r=[e.summary],i=Wk(e.next);return i&&r.push(i),e.user_message&&r.push("",fr.relay,e.user_message),t!==void 0&&r.push("",fr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
187
|
+
${e.sessionId}`)}:{}},f=e.binding?{schema:"comet.native.workspace.v3",...p,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...p};return gl(f),f}async function mr(e,t){let r=await w$(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(gl(r),r)}async function wl(e){gl(e.identity);let t=await y$({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),$f==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function An(e){if(gl(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await wl(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=we(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function VN(e,t){let r=await mr(e,t);if(r===null)return null;let i=await An({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}Xa();Fc();Fc();var yl=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"},mo=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"},Nl=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},g2=dc("en");function ke(e,t){Si(t);let r=Kr.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function bl(e,t){let r=Y(e,t),i=Kr.join(r,"schema-migration.json");await V(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await zN.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function GN(e,t){let r=Y(e,t),i=Kr.join(r,"checkpoint-journal.json");await V(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await zN.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function JN(e,t=Kr.dirname(e)){let r=Kr.relative(t,e).split(Kr.sep).join("/"),i=await re({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Hf.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 Df(e,t){let r=Kr.join(ke(e,t),zt);await V(e.nativeRoot,r);let i=Bc(await JN(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await bl(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await k$(e,i.state),i)}async function UN(e,t){let r=Kr.join(ke(e,t),zt);await V(e.nativeRoot,r);let i=Bc(await JN(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function k$(e,t){if(await ol(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Yt(e,t){let r=await Df(e,t);if(r.status==="migration-required")throw new hn(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new dr(r.schema,r.minimumRuntimeVersion);return await VN(e,t),r.state}Qe();import{promises as rF}from"fs";yi();import{promises as Bf}from"fs";import YN from"path";at();Ut();K();var Ff=["outcome","scope","nonGoals","acceptanceExamples"],KN=[...Ff,"constraints","decisions","openQuestions","verificationExpectations"],S$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],E$=new Set(["nonGoals","decisions","openQuestions"]),vo=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},XN={maxFileBytes:np};function QN(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
188
|
+
`).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}async function x$(e,t){let r=YN.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Bf.realpath(e),n=await Bf.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Bf.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function go(e){return{valid:e.length===0,findings:e}}function ZN(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 C$(e){return ZN(e).trim()}function Lf(e){let t=C$(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(`
|
|
189
|
+
`).trim()}function R$(e){let t=Lf(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 P$(e){let t=Lf(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 eb(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 kl(e,t,r={}){let i=[],n;try{n=(await re({root:e,ref:t,maxBytes:XN.maxFileBytes})).text}catch(s){return go([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of QN(n))a.set(uc(s)??s,c);for(let s of r.compact?Ff:KN)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?KN.filter(s=>!r.compact||a.has(s)):Ff;for(let s of o){let c=a.get(s)??"";Lf(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):P$(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!E$.has(s)&&R$(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return eb(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),go(i)}async function qf(e,t){let r=[],i;try{i=(await re({root:e,ref:t,maxBytes:XN.maxFileBytes})).text}catch(a){return go([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of QN(i))n.set(Ew(a)??a,o);for(let a of S$)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return go(r)}function wo(e,t){return YN.join(e.specsDir,t,"spec.md")}async function tb(e,t){let r=[],i=ke(e,t.name);for(let n of t.spec_changes){let a=wo(e,n.capability),o=null;try{await V(e.nativeRoot,a),o=await yf(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await x$(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return go(r)}to();de();at();to();de();import rb from"node:path";var _$="comet.native.contract.v1",A$="comet.native.acceptance-set.v1",ib=/^[a-f0-9]{64}$/u,yo={maxAcceptanceCriteria:eo.maxCriteria};function nb(e,t){let r=rb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||rb.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function ab(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
190
|
+
`))}function I$(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(ib))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(ib))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=nb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:ab(e.markdown)},markdown:e.markdown}}function T$(e,t){return ob(e.id,t.id)}function ob(e,t){return e<t?-1:e>t?1:0}function sb(e){let t=nb(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(I$).sort((d,p)=>ob(d.snapshot.capability,p.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Xp(e.briefMarkdown,t,yo.maxAcceptanceCriteria);for(let{snapshot:d,markdown:p}of r)p===null||d.source===null||(a.push(...Qp(p,d.source,yo.maxAcceptanceCriteria-a.length)),a.push(...Sy(p,d.source,yo.maxAcceptanceCriteria-a.length)));if(a.sort(T$),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>yo.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${yo.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:ab(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(A$,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(_$,u)}}var j$={maxSpecs:64};async function In(e){if(e.specChanges.length>j$.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:null}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await re({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:sb({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Qe();Re();import{promises as z$}from"node:fs";import Jf from"node:path";pt();import{promises as B$}from"node:fs";oe();io();import cb from"node:path";function No(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bo(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 Le(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 Tn(e,t){return e===null?null:Le(e,t)}function jn(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 F$(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 L$(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function $n(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Vf(e,t){if(e===null)return null;let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function q$(e,t){let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Wf(e,t){let r=Le(e,t);if(!cb.isAbsolute(r))throw new Error(`${t} must be absolute`);return cb.resolve(r)}function M$(e,t){let r=`Native local checks[${t}]`,i=No(e,r);if(bo(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)=>Le(u,`${r}.argv[${d}]`,!0)),a=$n(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Vf(i.startedAt,`${r}.startedAt`),s=Vf(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=jn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=No(i.activeProcess,`${r}.activeProcess`),d=$n(u.status,["starting","running"],`${r}.activeProcess.status`);if(bo(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:jn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:Le(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:Le(i.id,`${r}.id`),name:Le(i.name,`${r}.name`),operationId:Le(i.operationId,`${r}.operationId`),status:a,repeatable:L$(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:jn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Wf(i.cwd,`${r}.cwd`),exitCode:F$(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Le(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:$n(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:Le(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function V$(e){let t="Native local execution state",r=No(e,t);if(bo(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Vc)throw new Error(`Native local execution schema must be ${Vc}`);let i=No(r.workspace,"Native local workspace");bo(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=No(r.execution,"Native local execution");bo(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Vf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Le(o.operationId,"Native local execution.operationId"),stage:$n(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:$n(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Tn(o.executionId,"Native local execution.executionId"),status:$n(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:jn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:q$(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:jn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:Le(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(M$);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:Vc,change:Le(r.change,"Native local change"),basedOnStateVersion:jn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Tn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Tn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Tn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Tn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Wf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Wf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Tn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:Le(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function Sl(e){let t;try{t=await B$.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return V$(r)}function zf(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}function Gf(e,t){if(zf(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}xt();K();var lb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ub="comet-state.yaml",db="state.json";function Ai(e,t){if(!lb.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Jf.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function El(e,t){return Jf.join(Ai(e,t),ub)}function Yr(e,t){return Jf.join(Et(e,t),db)}async function ko(e,t){try{let r=await z$.readFile(El(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function ft(e,t){return Vr(El(e,t))}async function Uf(e){let t=await ft(e.paths,e.name),r=Yr(e.paths,e.name);try{let i=await Sl(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}function Qf(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ji=Qf();function yb(e){ji=e}var Ii={exec:()=>null};function On(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 M(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(_e.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var G$=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),_e={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:On(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:On(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:On(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:On(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:On(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:On(e=>new RegExp(`^ {0,${e}}>`))},J$=/^(?:[ \t]*(?:\n|$))+/,U$=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,K$=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,xo=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Y$=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zf=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Nb=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,bb=M(Nb).replace(/bull/g,Zf).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(),X$=M(Nb).replace(/bull/g,Zf).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(),eh=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Q$=/^[^\n]+/,th=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Z$=M(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",th).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),e0=M(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Zf).getRegex(),_l="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",rh=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,t0=M("^ {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",rh).replace("tag",_l).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),kb=e=>M(eh).replace("hr",xo).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",_l).getRegex(),r0=kb(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),i0=kb(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),n0=M(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",i0).getRegex(),ih={blockquote:n0,code:U$,def:Z$,fences:K$,heading:Y$,hr:xo,html:t0,lheading:bb,list:e0,newline:J$,paragraph:r0,table:Ii,text:Q$},pb=M("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",xo).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",_l).getRegex(),a0={...ih,lheading:X$,table:pb,paragraph:M(eh).replace("hr",xo).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",pb).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",_l).getRegex()},o0={...ih,html:M(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",rh).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:Ii,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:M(eh).replace("hr",xo).replace("heading",` *#{1,6} *[^
|
|
191
|
+
]`).replace("lheading",bb).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},s0=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,c0=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Sb=/^( {2,}|\\)\n(?!\s*$)/,l0=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,vr=/[\p{P}\p{S}]/u,Hn=/[\s\p{P}\p{S}]/u,Co=/[^\s\p{P}\p{S}]/u,u0=M(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Hn).getRegex(),d0=/[\p{Pi}\p{Ps}"']/u,Eb=/(?!~)[\p{P}\p{S}]/u,p0=/(?!~)[\s\p{P}\p{S}]/u,f0=/(?:[^\s\p{P}\p{S}]|~)/u,h0=M(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",G$?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),xb=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,m0=M(xb,"u").replace(/punct/g,vr).getRegex(),v0=M(xb,"u").replace(/punct/g,Eb).getRegex(),g0=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,w0=M(g0,"u").replace(/openQuote/g,d0).replace(/punct/g,vr).getRegex(),Cb="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",y0=M(Cb,"gu").replace(/notPunctSpace/g,Co).replace(/punctSpace/g,Hn).replace(/punct/g,vr).getRegex(),N0=M(Cb,"gu").replace(/notPunctSpace/g,f0).replace(/punctSpace/g,p0).replace(/punct/g,Eb).getRegex(),b0="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",k0=M(b0,"gu").replace(/notPunctSpace/g,Co).replace(/punctSpace/g,Hn).replace(/punct/g,vr).getRegex(),S0=M("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Co).replace(/punctSpace/g,Hn).replace(/punct/g,vr).getRegex(),E0="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",x0=M(E0,"gu").replace(/notPunctSpace/g,Co).replace(/punctSpace/g,Hn).replace(/punct/g,vr).getRegex(),C0=M(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,vr).getRegex(),R0="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",P0=M(R0,"gu").replace(/notPunctSpace/g,Co).replace(/punctSpace/g,Hn).replace(/punct/g,vr).getRegex(),_0=M(/\\(punct)/,"gu").replace(/punct/g,vr).getRegex(),A0=M(/^<(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(),I0=M(rh).replace("(?:-->|$)","-->").getRegex(),T0=M("^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",I0).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Cl=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,j0=M(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Cl).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Rb=M(/^!?\[(label)\]\[(ref)\]/).replace("label",Cl).replace("ref",th).getRegex(),Pb=M(/^!?\[(ref)\](?:\[\])?/).replace("ref",th).getRegex(),$0=M("reflink|nolink(?!\\()","g").replace("reflink",Rb).replace("nolink",Pb).getRegex(),fb=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,nh={_backpedal:Ii,anyPunctuation:_0,autolink:A0,blockSkip:h0,br:Sb,code:c0,del:Ii,delLDelim:Ii,delRDelim:Ii,emStrongLDelim:m0,emStrongRDelimAst:y0,emStrongRDelimUnd:S0,escape:s0,link:j0,nolink:Pb,punctuation:u0,reflink:Rb,reflinkSearch:$0,tag:T0,text:l0,url:Ii},O0={...nh,emStrongLDelim:w0,emStrongRDelimAst:k0,emStrongRDelimUnd:x0,link:M(/^!?\[(label)\]\((.*?)\)/).replace("label",Cl).getRegex(),reflink:M(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Cl).getRegex()},Kf={...nh,emStrongRDelimAst:N0,emStrongLDelim:v0,delLDelim:C0,delRDelim:P0,url:M(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",fb).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:M(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",fb).getRegex()},H0={...Kf,br:M(Sb).replace("{2,}","*").getRegex(),text:M(Kf.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},xl={normal:ih,gfm:a0,pedantic:o0},So={normal:nh,gfm:Kf,breaks:H0,pedantic:O0},D0={"&":"&","<":"<",">":">",'"':""","'":"'"},hb=e=>D0[e];function Xt(e,t){if(t){if(_e.escapeTest.test(e))return e.replace(_e.escapeReplace,hb)}else if(_e.escapeTestNoEncode.test(e))return e.replace(_e.escapeReplaceNoEncode,hb);return e}function mb(e){try{e=encodeURI(e).replace(_e.percentDecode,"%")}catch{return null}return e}function vb(e,t){let r=e.replace(_e.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split(_e.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(_e.slashPipe,"|");return i}function Xr(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 gb(e){let t=e.split(`
|
|
192
|
+
`),r=t.length-1;for(;r>=0&&_e.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
193
|
+
`)}function B0(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 F0(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 wb(e,t,r,i,n){let a=t.href,o=t.title||null,s=e[1].replace(n.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";i.state.inLink=!0;let l=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),p=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(p){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function L0(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
|
|
194
|
+
`).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(`
|
|
195
|
+
`)}var Rl=class{options;rules;lexer;constructor(e){this.options=e||ji}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]:gb(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=L0(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=Xr(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:Xr(t[0],`
|
|
196
|
+
`),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:Xr(t[0],`
|
|
197
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Xr(t[0],`
|
|
198
|
+
`).split(`
|
|
199
|
+
`),i="",n="",a=[];for(;r.length>0;){let o=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),o=!0;else if(!o)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
|
|
200
|
+
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
201
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
202
|
+
${l}`:l,n=n?`${n}
|
|
203
|
+
${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=d,r.length===0)break;let p=a.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let f=p,m=r.join(`
|
|
204
|
+
`),h=f.raw+`
|
|
205
|
+
`+m.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(h);a[a.length-1]=v,i=`${i}
|
|
206
|
+
${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="list"){let f=p,m=f.raw+`
|
|
207
|
+
`+r.join(`
|
|
208
|
+
`),h=this.list(m);a[a.length-1]=h,i=i.substring(0,i.length-p.raw.length)+h.raw,n=n.substring(0,n.length-f.raw.length)+h.raw,r=m.substring(a.at(-1).raw.length).split(`
|
|
209
|
+
`);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 c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let d=F0(t[2].split(`
|
|
210
|
+
`,1)[0],t[1].length),p=e.split(`
|
|
211
|
+
`,1)[0],f=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):f?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=t[1].length),f&&this.rules.other.blankLine.test(p)&&(l+=p+`
|
|
212
|
+
`,e=e.substring(p.length+1),c=!0),!c){let h=this.rules.other.nextBulletRegex(m),v=this.rules.other.hrRegex(m),g=this.rules.other.fencesBeginRegex(m),b=this.rules.other.headingBeginRegex(m),k=this.rules.other.htmlBeginRegex(m),N=this.rules.other.blockquoteBeginRegex(m);for(;e;){let x=e.split(`
|
|
213
|
+
`,1)[0],w;if(p=x,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),w=p):w=p.replace(this.rules.other.tabCharGlobal," "),g.test(p)||b.test(p)||k.test(p)||N.test(p)||h.test(p)||v.test(p))break;if(w.search(this.rules.other.nonSpaceChar)>=m||!p.trim())u+=`
|
|
214
|
+
`+w.slice(m);else{if(f||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(d)||b.test(d)||v.test(d))break;u+=`
|
|
215
|
+
`+p}f=!p.trim(),l+=x+`
|
|
216
|
+
`,e=e.substring(x.length+1),d=w.slice(m)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let c of n.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,n.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=gb(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:Xr(t[0],`
|
|
217
|
+
`),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=vb(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
218
|
+
`):[],a={type:"table",raw:Xr(t[0],`
|
|
219
|
+
`),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(vb(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:Xr(t[0],`
|
|
220
|
+
`),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)===`
|
|
221
|
+
`?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=Xr(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=B0(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)),wb(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 wb(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,c=0,l=i[0][0],u=r===l,d=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+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)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let p=[...i[0]][0].length,f=e.slice(0,n+i.index+p+o);if(Math.min(n,o)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(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,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(i=c.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 l=[...i[0]][0].length,u=e.slice(0,n+i.index+l+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(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}}}},ht=class Yf{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ji,this.options.tokenizer=this.options.tokenizer||new Rl,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:_e,block:xl.normal,inline:So.normal};this.options.pedantic?(r.block=xl.pedantic,r.inline=So.pedantic):this.options.gfm&&(r.block=xl.gfm,this.options.breaks?r.inline=So.breaks:r.inline=So.gfm),this.tokenizer.rules=r}static get rules(){return{block:xl,inline:So}}static lex(t,r){return new Yf(r).lex(t)}static lexInline(t,r){return new Yf(r).inlineTokens(t)}lex(t){t=t.replace(_e.carriageReturn,`
|
|
222
|
+
`),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(_e.tabCharGlobal," ").replace(_e.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+=`
|
|
223
|
+
`: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(`
|
|
224
|
+
`)?"":`
|
|
225
|
+
`)+a.raw,s.text+=`
|
|
226
|
+
`+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(`
|
|
227
|
+
`)?"":`
|
|
228
|
+
`)+a.raw,s.text+=`
|
|
229
|
+
`+a.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},r.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),r.push(a);continue}let o=t;if(this.options.extensions?.startBlock){let s=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(o=t.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);i&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
|
|
230
|
+
`)?"":`
|
|
231
|
+
`)+a.raw,s.text+=`
|
|
232
|
+
`+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(`
|
|
233
|
+
`)?"":`
|
|
234
|
+
`)+a.raw,s.text+=`
|
|
235
|
+
`+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,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;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(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,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 c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},Pl=class{options;parser;constructor(e){this.options=e||ji}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(_e.notSpaceStart)?.[0],n=e.replace(_e.endingNewline,"")+`
|
|
236
|
+
`;return i?'<pre><code class="language-'+Xt(i)+'">'+(r?n:Xt(n,!0))+`</code></pre>
|
|
237
|
+
`:"<pre><code>"+(r?n:Xt(n,!0))+`</code></pre>
|
|
238
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
239
|
+
${this.parser.parse(e)}</blockquote>
|
|
240
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
241
|
+
`}hr(e){return`<hr>
|
|
242
|
+
`}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+`>
|
|
243
|
+
`+i+"</"+n+`>
|
|
244
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
245
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
246
|
+
`}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>
|
|
247
|
+
<thead>
|
|
248
|
+
`+t+`</thead>
|
|
249
|
+
`+i+`</table>
|
|
250
|
+
`}tablerow({text:e}){return`<tr>
|
|
251
|
+
${e}</tr>
|
|
252
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
253
|
+
`}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>${Xt(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=mb(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+Xt(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=mb(e);if(n===null)return Xt(r);e=n;let a=`<img src="${e}" alt="${Xt(r)}"`;return t&&(a+=` title="${Xt(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Xt(e.text)}},ah=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}},It=class Xf{options;renderer;textRenderer;constructor(t){this.options=t||ji,this.options.renderer=this.options.renderer||new Pl,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ah}static parse(t,r){return new Xf(r).parse(t)}static parseInline(t,r){return new Xf(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}},Eo=class{options;block;constructor(e){this.options=e||ji}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?ht.lex:ht.lexInline}provideParser(e=this.block){return e?It.parse:It.parseInline}},q0=class{defaults=Qf();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=It;Renderer=Pl;TextRenderer=ah;Lexer=ht;Tokenizer=Rl;Hooks=Eo;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 Pl(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new Rl(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new Eo;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=n[o];Eo.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&Eo.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,l);return c.call(n,d)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,l);return d===!1&&(d=await c.apply(n,l)),d})();let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ht.lex(e,t??this.defaults)}parser(e,t){return It.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?ht.lex:ht.lexInline)(o,n),c=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(c,n.walkTokens));let l=await(n.hooks?await n.hooks.provideParser(e):e?It.parse:It.parseInline)(c,n);return n.hooks?await n.hooks.postprocess(l):l})().catch(a);try{n.hooks&&(t=n.hooks.preprocess(t));let o=(n.hooks?n.hooks.provideLexer(e):e?ht.lex:ht.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?It.parse:It.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+=`
|
|
254
|
+
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Xt(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},Ti=new q0;function X(e,t){return Ti.parse(e,t)}X.options=X.setOptions=function(e){return Ti.setOptions(e),X.defaults=Ti.defaults,yb(X.defaults),X};X.getDefaults=Qf;X.defaults=ji;function M0(...e){return Ti.use(...e),X.defaults=Ti.defaults,yb(X.defaults),X}X.use=M0;X.walkTokens=function(e,t){return Ti.walkTokens(e,t)};X.parseInline=Ti.parseInline;X.Parser=It;X.parser=It.parse;X.Renderer=Pl;X.TextRenderer=ah;X.Lexer=ht;X.lexer=ht.lex;X.Tokenizer=Rl;X.Hooks=Eo;X.parse=X;var Q2=X.options,Z2=X.setOptions,eG=X.walkTokens,tG=X.parseInline;var rG=It.parse,iG=ht.lex;oe();at();de();var Gb=ir(Bt(),1);import{promises as EO}from"node:fs";import Tt from"node:path";pt();at();de();Qe();K();xt();Tl();Tl();Oi();ti();pt();Ic();oe();de();Dl();Re();K();qb();Oi();ti();Bl();pt();Qe();Bl();Ua();K();var Fl=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function ph(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}import bO from"node:path";pt();Qe();Re();Oi();ti();async function Ll(e){let t=ph(e.parent),r=nr(e.paths.projectRoot,t);if(!r)return null;let i=nr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Cr(e.paths.projectRoot).map(o=>bO.resolve(o)).find(o=>we(o).currentBranch===t);if(!n)return null;let a=Ol({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return ch(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function fh(e,t){let r=Tt.normalize(Tt.resolve(e)),i=Tt.normalize(Tt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function xO(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function CO(e){let t=xO(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function hh(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return CO(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function mh(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function RO(e){let t=Cr(e.projectRoot);t.some(i=>fh(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Tt.resolve(n)))]){let n=await xe(i);n&&r.push({projectRoot:i,paths:await Vt(i,n.native.artifact_root),parent:fh(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function PO(e,t){let r=Tt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Vr(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _O(e,t){let r;try{r=await EO.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Tt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Vr(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function AO(e,t,r){let i=Tt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Tt.sep}`))return null;let n=i.split(Tt.sep).join("/");try{let a=(0,Gb.parseDocument)(Je(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ze(a.toJS({mapAsMap:!1}))}catch{return null}}function IO(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function zb(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Io(e){let t=Tt.join(e.paths.changesDir,e.state.name),r=await hh(t),i=null,n;try{n=await Qt({changeDir:t,validation:Zr(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await et(e.paths,e.state.name,{diagnostics:!0});if(g){let b=Hl(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(k=>({...k,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=mh({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Qr){let g=await et(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let x=await Ll({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await ei(e.paths,x))}}if(g){let N=Hl(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let b=new Map(n.contract.children.map(N=>[N.name,N])),k=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==N.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of k){if(N.status!=="ready")continue;b.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:k,readyChildren:k.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await RO(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let k of await _O(g,l)){let N={...k,source:g,committedState:AO(g,k.file,b)};u.set(k.state.name,[...u.get(k.state.name)??[],N])}for(let k of l){let N=await PO(g,k);N&&d.set(k,[...d.get(k)??[],{source:g,state:N}])}}let p=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===g.name&&zb(w,o));if(b){p.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let k=u.get(g.name)?.[0];if(k){p.set(g.name,{kind:"blocked",phase:k.state.phase,projectRoot:k.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?p.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&p.set(g.name,IO(N[0].state,N[0].source,o))}let f=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,h=g=>{let b=m.get(g);if(b)return b;let k=f.get(g),x=k.depends_on.map(h).every(({status:O})=>O==="done"),w=p.get(g),S=w?.kind==="active"&&x?k.depends_on.filter(O=>!(u.get(O)??[]).some(({source:T,committedState:Q})=>fh(T.projectRoot,w.projectRoot)&&Q?.name===O&&zb(Q,o))):[],E,y=w?.message??null;w?.kind==="done"?(E=x?"done":"blocked",x||(y=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(E=x&&S.length===0?"active":"blocked",x?S.length>0&&(y=`Native child ${g} does not include merged dependencies: ${S.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?E="blocked":(E=s&&x?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:k.summary,dependsOn:[...k.depends_on],covers:[...k.covers],status:E,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:y};return m.set(g,C),C},v=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}Mc();xt();Ri();Ro();jl();Re();Zp();Vp();xt();Ri();oe();yi();Ro();K();yi();si();Qe();var $k=ir(Bt(),1);cr();var pK=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 wK=256*1024;xt();Ri();ti();var XH=dc("en",{compact:!0});Qe();Re();Oi();ti();xt();Ri();pt();Ic();de();import Wn from"node:path";pt();cr();oe();var j6=8*1024*1024;Dl();Re();Ri();K();function eD(e,t){let r=Wn.relative(Wn.resolve(e),Wn.resolve(t));if(Wn.isAbsolute(r)||r===".."||r.startsWith(`..${Wn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Wn.sep).join("/");return Lb(e,i),i}function Bk(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:eD(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var rY=1024*1024*1024;Re();jl();Ro();ti();Re();ti();Re();ff();var J9=16*1024;async function Fk(e){let t=await Pf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Si(t.selection.change),t.selection)}async function Lk(e,t){return Ce(e,`select change ${t}`,async()=>{Si(t),await ko(e,t)?await ft(e,t):await Yt(e,t),await _f(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}K();async function qk(e,t){let r=[],i=Y(e,t.name),n=Mr(i,dt.stateRef),a;try{a=await Pn(i)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&r.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Mr(i,a.trajectoryRef),s=await $N(e,t.name);if(s.status==="repairable")return r.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await _i(i,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Mr(i,a.checkpointRef);try{let u=await ml(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Cn();import bD from"path";import{isDeepStrictEqual as Mh}from"util";oe();Ut();Ua();Re();K();Ct();Hi();de();de();var zn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var tD=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function rD(e,t){return e<t?-1:e>t?1:0}function iD(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!tD.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(rD)}function Oh(e=[]){return iD(e,"Native repair failed check IDs",zn.maxFailedCheckIds,!0)}function Mk(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function nD(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Mk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Mk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Hh(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(nD(i,a))break;r+=1,i=a}return r}zl();Li();function Dh(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var Vk="repairStagnation",rt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},oD=/^[a-f0-9]{64}$/u;var sD=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),cD=["data","runId","sequence","timestamp","type"],Wk=["disposition","overrideSummaryHash","signatureHash"],lD=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],zk=12;function Fh(e,t){return e<t?-1:e>t?1:0}function Gk(e,t,r){let i=Object.keys(e).sort(Fh);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function Kl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Jo(e,t){if(typeof e!="string"||!oD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function uD(e){if(!Array.isArray(e)||e.length>zn.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Fh)}function Jk(e){if(typeof e!="string"||e.length===0||e.length>rt.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Bh(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>rt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>rt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>rt.maxTextCharacters&&(!n||e.length>rt.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>rt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>rt.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Bh(s,t+1,r,`${i}[${c}]`));return}let a=Kl(e,i),o=Object.keys(a);if(o.length>rt.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>rt.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>rt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Bh(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function dD(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function pD(e,t,r){let i=Kl(e,`Native repair trajectory event ${t+1}`);if(Gk(i,cD,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(dD(i.timestamp),typeof i.type!="string"||!sD.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(Jk(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Bh(i.data,0,n,"Native trajectory event data"),Kl(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Lh(e){let t=Kl(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Fh),i=r.length===Wk.length&&r.every((l,u)=>l===Wk[u]);i||Gk(t,lD,"Native repair trajectory projection");let n=Jo(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Jo(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Jo(t.contractHash,"Native repair trajectory contract hash"),s=uD(t.failedAcceptanceIds),c=Oh(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function fD(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function hD(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??zk;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Hh({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<zn.warningAtConsecutiveFailures?"continue":a<zn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function mD(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??zk;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Uk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>rt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Jk(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=pD(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>rt.maxTotalDataNodes||c>rt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let p=d.data,f=Object.hasOwn(p,"repairScopeHash")?Jo(p.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(p,"implementationScopeHash")?Jo(p.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(p,Vk)){if(i?.contractHash===null&&d.type==="state_transitioned"&&p.previousPhase==="build"&&p.nextPhase==="verify"&&(f!==null&&n!==null&&f!==n||f===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=f,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Lh(p[Vk]);if(fD(p,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&f!==null&&n!==null&&f!==n&&(r.length=0,o=0),f!==null&&(n=f),hD(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&f!==null&&n!==null&&f!==n)throw new Error("Native repair override cannot cross implementation scope progress");mD(m,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>zn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function Kk(e){return Uk(e).history}function Yk(e){let t=Uk(e).latestProjection;return t?{...t}:null}Ut();var Gn={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:[]},qh=ee("comet-native-runtime:v3:scope-reopen"),vD=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];function Xk(e){return e.skillVersion===Gn.definition.metadata.version&&e.skillHash===qh||vD.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Ut();Ut();function Qk(e){return ee(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}Xa();var iS=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],kD=new Set(iS),nS=new Set([...iS,"minimum_runtime_version","revision"]),SD=new Set([...nS,"operation"]),Vh=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),ED=new Set([...Vh,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Wh=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Gh(e,t){return bD.join(Y(e,t),"transition.json")}function Xl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Jh(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function Yl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function zh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!ED.has(u)),a=[...Vh].find(u=>!Object.hasOwn(r,u)),o=Vh.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Dh(r.summary,"Native transition journal event summary"),mt(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(r.noCodeReason!==null&&(Dh(r.noCodeReason,"Native transition journal event no-code reason"),mt(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Lh(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function xD(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return zh({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return zh(e,t)}function Uh(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let i=r?xD(e.eventData,e.evidenceHash):zh(e.eventData,e.evidenceHash),n=If(e.nextRun),a=e.previousRun===null?null:If(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function Zk(e,t,r=!1){if(e.skill!==Gn.definition.metadata.name||(r?!Xk(e):e.skillVersion!==Gn.definition.metadata.version||e.skillHash!==qh)||e.orchestration!==Gn.definition.orchestration.mode||e.pendingRef!==dt.pendingRef||e.trajectoryRef!==dt.trajectoryRef||e.contextRef!==dt.contextRef||e.artifactsRef!==dt.artifactsRef||e.checkpointRef!==dt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function eS(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function tS(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Kh(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(Zk(o,"next Run",i||a!==null),tS(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Zk(a,"previous Run",!0),tS(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Mh(eS(a),eS(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function CD(e,t,r){return ee(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function aS(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function rS(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Yh(e,t,r,i,n=!1){let a=r.eventData,o=rS(e),s=rS(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(i==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Mh(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(i==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Mh(e.spec_changes,t.spec_changes),l=Qk({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||r.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(i==="spec-rebase"){let c=CD(e.name,a.summary,t.spec_changes),l=ee(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function RD(e,t){let r=Xl(e);if(Jh(r,SD),r.schema!==pn)throw new Error(`Expected Native transition schema ${pn}`);let i=Yl(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${pn} minimum_runtime_version must be ${3}`);let n=Yl(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Uh(r,t),o=Gt(r.previousState),s=Gt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Yh(o,s,a,r.operation),Kh(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:pn,minimum_runtime_version:3,revision:n,operation:r.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function PD(e,t){let r=Xl(e);if(Jh(r,kD),r.schema!==Ya)throw new Error(`Expected Native transition schema ${Ya}`);let i=Uh(r,t,!0),n=Ei(r.previousState),a=Ei(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Yh(n,a,i,aS(n,a,i.eventData),!0),Kh(n,a,i,!0),{schema:Ya,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function _D(e,t){let r=Xl(e);if(Jh(r,nS),r.schema!==fn)throw new Error(`Expected Native transition schema ${fn}`);if(Yl(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${fn} minimum_runtime_version must be 2`);let n=Yl(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Uh(r,t,!0),o=xi(r.previousState),s=xi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Yh(o,s,a,aS(o,s,a.eventData),!0),Kh(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:fn,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function AD(e,t){let r=Xl(e);if(r.schema===pn)return{status:"current",journal:RD(r,t)};if(r.schema===Ya)return{status:"migration-required",journal:PD(r,t)};if(r.schema===fn)return{status:"migration-required",journal:_D(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function ID(e,t){let r=Gh(e,t),i=Ne(e,r);await V(i,r);try{let n=await Gr({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return AD(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function oS(e,t){let r=await ID(e,t);if(!r)return null;if(r.status==="migration-required")throw new Wh(t);return r.journal}var TD=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function jD(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function $D(e){return e?e.map(jD).join(" "):null}function OD(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function vt(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function HD(e){return e.map(t=>vt(t,[],null))}function DD(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[vt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(vt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(vt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),vt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(vt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(vt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),vt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ie(e,t){let r=t.commandArgs===void 0?OD(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?$D(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??HD(t.requiredInputs??[])}}function Ql(e){let r=(e.findings??[]).filter(d=>!_n(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||TD.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Ie(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ie(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[vt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Ie(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ie(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ie(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[vt("summary",["--summary"],"<summary>")]});if(n)return Ie(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[vt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Ie(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Ie(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[vt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ie(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ie(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=DD(e.state);return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Uo from"path";K();var sS=8,BD={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function FD(e){let t=BD[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:_n(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function LD(e,t,r){if(!r.path)return null;let i;if(Uo.isAbsolute(r.path)?i=Uo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Uo.resolve(ke(e,t.name),...r.path.split(/[\\/]/u)):i=Uo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Uo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function qD(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Xh(e){return e.findings.map(t=>{let r=FD(t.code);return{code:t.code,message:t.message,severity:r.severity,path:LD(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:qD(r.retry,e.state,t.code),repairCommand:r.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function Qh(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,sS),truncated:t.length>sS}}oe();import Jn from"path";Ut();K();Ct();Ha();Hi();var Ko={maxArtifacts:128},Un=/^[a-f0-9]{64}$/u;function Zl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function eu(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function ci(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function cS(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function MD(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Jn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Jn.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function lS(e,t){return Jn.join(Y(e,t),"checkpoints","progress.json")}function Yo(e,t){return Jn.join(Y(e,t),"checkpoint-journal.json")}function uS(e,t,r){if(!Un.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Jn.join(Y(e,t),"checkpoints","manifests",`${r}.json`)}function VD(e){if(!Un.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function em(e,t,r){let i=await Gr({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function WD(e,t){let r=Zl(e,`checkpoint manifest artifact ${t}`);eu(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=MD(ci(r.path,`checkpoint artifact ${t} path`,4096)),n=Ft(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!Un.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Zh(r.size,`checkpoint artifact ${t} size`)}}function tm(e,t){let r=Zl(e,"Native checkpoint manifest");if(eu(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Ko.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(WD),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Zh(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function dS(e){return ee(JSON.stringify(tm(e,e.change)))}function pS(e,t){let r=Zl(e,"Native progress checkpoint");if(eu(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=cS(r.previousRevision,"Native checkpoint previousRevision"),a=cS(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ci(r.manifestHash,"Native checkpoint manifestHash",64);if(!Un.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=VD(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ci(r.inputHash,"Native checkpoint inputHash",64);if(!Un.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ci(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Zh(r.artifactCount,"Native checkpoint artifactCount");if(u>Ko.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ci(r.summary,"Native checkpoint summary"),p=ci(r.nextAction,"Native checkpoint nextAction");if(mt(d)!==d||mt(p)!==p)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ci(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:p,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function zD(e,t){let r=Zl(e,"Native checkpoint journal");if(eu(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=Gt(r.previousState),n=Gt(r.nextState),a=pS(r.checkpoint,t),o=tm(r.manifest,t),s=ci(r.inputHash,"Native checkpoint journal inputHash",64),c=ee(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Un.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==dS(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:i,nextState:n,checkpoint:a,manifest:o}}async function GD(e,t,r){let i=Jn.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,i)||q(e.nativeRoot,i)||q(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=rp(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await hf({root:e.projectRoot,file:i,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function JD(e,t){let r=lS(e,t),i=Ne(e,r);await V(i,r);try{return pS(await em(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function UD(e,t,r){let i=uS(e,t,r),n=Ne(e,i);await V(n,i);let a=await em(n,i,"Native checkpoint manifest"),o=tm(a,t);if(fS(e,o),dS(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function rm(e,t){let r=Yo(e,t),i=Ne(e,r);await V(i,r);try{let n=zD(await em(i,r,"Native checkpoint journal"),t);return fS(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function fS(e,t){for(let r of t.artifacts){let i=rp(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function hS(e){let t;try{t=await JD(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:lS(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await UD(e.paths,e.name,t.manifestHash);let a=ee(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await GD(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:uS(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var mS=240,vS=8,tu=50;function gS(e){let t=Array.from(e);return t.length<=mS?e:`${t.slice(0,mS-1).join("")}…`}function KD(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function YD(e){let t=[...new Set(e.map(KD))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,vS),reasonCount:e.length,codesTruncated:t.length>vS};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,tu),reasonsTruncated:e.length>tu}}}async function wS(e){let t=null;try{let s=await rm(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Yo(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Yo(e.paths,e.state.name)}}let r=await hS({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=YD(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ko.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:gS(r.checkpoint.summary),nextAction:gS(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ko.maxArtifacts}}import{promises as KB}from"node:fs";import DS from"node:path";de();import yS from"node:path";var XD="comet.native.archive-preflight.v1",QD="comet.native.archive-preflight.v1",ZD="comet.native.archive-operation.v1",eB=/^[a-f0-9]{64}$/u,NS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ru(e,t){return e<t?-1:e>t?1:0}function rB(e,t){if(typeof e!="string"||!eB.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kr(e,t){return e===null?null:rB(e,t)}function iB(e,t){let r=yS.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||yS.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function nB(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function aB(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function oB(e,t){if(!NS.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let r=kr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=kr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=kr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:r,actualBaseHash:i,proposedHash:n}}function sB(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:kr(e.contractHash,"Native archive contract hash"),acceptanceHash:kr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:kr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:kr(e.reportHash,"Native archive report hash"),envelopeHash:kr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:kr(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(r=>r===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function cB(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!tB.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(ru);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function lB(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ru)}function bS(e){if(!NS.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(oB).sort((l,u)=>ru(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let r=t.map(l=>({...l,operationHash:j(ZD,l)})),i=sB(e.evidence),n=aB(e.workspace),a=[...new Set([...cB(e.findingCodes??[]),...lB({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(ru),o=nB(e.revision),s=iB(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:r,evidence:i,workspace:n,findingCodes:a};return{schema:XD,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:j(QD,c)}}at();de();import{createHash as uB}from"node:crypto";import kS from"node:path";var dB="comet.native.conflict-radar.v1",Ke=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}),pB="comet.native.conflict-radar.v1",fB="comet.native.conflict-radar-signals.v1",hB=/^[a-f0-9]{64}$/u,xS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mB=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),vB=new Set(["capability","operation","baseHash"]),gB=new Set(["path","kind"]);function Kn(e,t){return e<t?-1:e>t?1:0}function im(e){return Buffer.byteLength(e,"utf8")}function nm(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function am(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(im(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function wB(e,t){let r=am(e,t,Ke.maxArtifactPathBytes),i=kS.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||kS.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function CS(e,t){if(typeof e!="string"||!hB.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yB(e,t){let r=nm(e,vB,t),i=am(r.capability,`${t} capability`,Ke.maxCapabilityBytes);if(!xS.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:CS(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function NB(e,t){let r=nm(e,gB,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:wB(r.path,`${t} path`),kind:r.kind}}function bB(e,t){let r=nm(e,mB,`Conflict radar change ${t}`),i=am(r.name,`Conflict radar change ${t} name`,Ke.maxNameBytes);if(!xS.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>Ke.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>Ke.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>yB(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>Kn(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>NB(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>Kn(c.path,l.path)||Kn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:CS(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function kB(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ke.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(bB).sort((n,a)=>Kn(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Ke.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ke.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function SB(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function EB(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function xB(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function CB(e,t){let r=[],i=uB("sha256").update(`${fB}
|
|
255
|
+
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(aa(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Ke.maxSignalsPerRelationship&&r.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(SB(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=EB(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:xB(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function SS(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function RB(e,t){return SS(e.classification)-SS(t.classification)||Kn(e.left,t.left)||Kn(e.right,t.right)}function ES(e,t,r,i){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:dB,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function RS(e){let t=kB(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(CB(t[s],t[c]));r.sort(RB);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(pB,{changes:t,relationships:i}),a=r.slice(0,Ke.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=ES(t,r,a,n);for(;a.length>0&&im(JSON.stringify(o))>Ke.maxSerializedBytes;)a=a.slice(0,-1),o=ES(t,r,a,n);if(im(JSON.stringify(o))>Ke.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}si();Ct();var PB=4096;async function _B(e,t=Ke.maxChanges){try{let r=await so({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function PS(e,t){let r=await Yt(e,t),[i,n]=await Promise.all([r.implementation_scope?Jl(e,t,r.implementation_scope):null,mr(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function iu(e,t,r={}){let n=(await _B(e,PB)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await PS(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await PS(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=RS([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}Qe();K();to();at();si();Cn();Li();zl();import{execFile as LB}from"node:child_process";Gi();ea();dh();import{promisify as qB}from"node:util";Re();oe();_h();K();Lt();import{constants as om,promises as gt}from"node:fs";import Yn from"node:path";var IB=/^[a-f0-9]{64}$/u,TB=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function jB(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nu(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function $B(e,t){let r=Yn.resolve(e),i=Yn.resolve(t);if(!q(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...Yn.relative(r,i).split(Yn.sep).filter(Boolean)]){o&&(a=Yn.join(a,o));let s=await gt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await gt.realpath(a);if(n.length>0&&!q(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function AS(e){for(let t of e){let r=await gt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!jB(t,r)||await gt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function OB(e){if(!IB.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function HB(e){let t=TB.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function DB(e,t,r){return Mr(Y(e,t),OB(r))}async function BB(e,t,r){let i=await $B(r,Yn.dirname(e)),n=await gt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([gt.realpath(t),gt.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":om.O_RDONLY|om.O_NOFOLLOW|om.O_NONBLOCK,c=await gt.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),gt.lstat(e),gt.realpath(e)]);if(await AS(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!nu(n,l)||!nu(l,u))throw new Error("Native check receipt changed while opening");let p=[],f=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=await c.read(m,0,m.length,null);if(b.bytesRead===0)break;f+=b.bytesRead,p.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,g]=await Promise.all([c.stat(),gt.lstat(e),gt.realpath(e)]);if(await AS(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!nu(l,h)||!nu(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(p,f).toString("utf8"))}finally{await c.close()}}async function IS(e,t,r){let i=HB(r),n=Y(e,t),a=DB(e,t,i),o=Ne(e,a);await V(o,a);let s=Ck(await BB(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}si();Re();Hi();var Xo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Cn();Lo();Li();var a5=64*1024;var o5=3600*1e3;var s5=qB(LB);var MB=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function TS(e,t){let r=[];for(let i of MB){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function jS(e){if(e.receipt.kind!=="static-inspection")return null;let t=await IS(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}Lo();var li=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}};function VB(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function WB(e){let t=VB(e.bundle.baseline),r=await Rf(e.paths,t,{origin:"explicit",now:e.now});return Sh({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function OS(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await qo(e.paths,e.state.name,e.state.implementation_scope),r=await In({changeDir:ke(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await WB({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function HS(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await OS(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function zB(e){let t=await re({root:ke(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:xy(t.text)}}function GB(e){let{receipt:t,implementationScope:r}=e,i=[],n=kh({baseline:r.baseline,current:r.current,declaredArtifacts:r.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function JB(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Th(e.implementationScope.scope.declaredArtifacts)}}async function $S(e){let t=await Mo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=TS(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new li([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await jS({paths:e.paths,state:e.state,receipt:t});if(n){let a=GB({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function UB(e){let t=JB({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await $S({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof li)return r.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await $S({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof li)return r.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new li(r)}function sm(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function cm(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:sm(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([OS(e),Vn(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:sm(e.state.verification_result,"stale"),envelope:null};let i=await zB({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await UB({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:sm(e.state.verification_result,"invalid"),envelope:null}}}function YB(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function BS(e){try{return await KB.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function XB(e,t){try{return(await re({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function QB(e,t,r){let i=wo(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=DS.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await XB(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await re({root:ke(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function ZB(e,t){return BS(Gh(e,t))}async function lm(e){let t=e.now??new Date,r=await Yt(e.paths,e.name),i=await mr(e.paths,e.name),n=await xe(e.paths.projectRoot),a=YB(r.name,t),o=DS.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,p,f]=await Promise.all([Promise.all(r.spec_changes.map(m=>QB(e.paths,r.name,m))),cm({paths:e.paths,state:r,now:t}),iu(e.paths,r.name),bl(e.paths,r.name),GN(e.paths,r.name),ZB(e.paths,r.name),BS(o)]);return bS({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||p,targetRef:a,targetExists:f,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}K();si();Lo();Li();async function eF(e,t){let r=Y(e,t.name),i=await Pn(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await ml(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await _i(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function tF(e,t){let r=await eF(e,t);return{committed:r,latest:Yk(r),history:Kk(r)}}async function FS(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await tF(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}si();Ct();K();function Qo(e,t){try{return za(e,t)}catch{return}}var Zo=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function iF(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function nF(e){return(await Fk(e))?.change??null}function aF(e,t,r=!1,i){return Ql({state:e,archiveReady:t,evidenceRetreat:r}).command}async function oF(e,t){let r=ke(e,t.name),i=[...(await kl(r,t.brief)).findings,...(await tb(e,t)).findings,...await qk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await ol(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await bN(e,n);a.complete||i.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await In({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await oS(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await qf(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function um(e,t,r){let i=await nF(e)===t,n=await Rp(e,t),a=await ho(e,t),o;try{let y=await Df(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:Qo(e,t),phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,artifacts:Qo(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,artifacts:Qo(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:y.message}}if(n.status!=="available"){let y={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=Xh({paths:e,state:o,findings:[y]}),O=Ql({state:o,findings:C});return{name:o.name,artifacts:Qo(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:Qh(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await wS({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await FS(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await In({changeDir:ke(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Q=await Vn(e,o.name,o.verification_evidence);for(let Te of Q.acceptanceTrace.entries)C.set(Te.acceptanceId,Te.status==="failed"?"failed":Te.status==="missing"?"missing":"satisfied")}let O=ky({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),T=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...T?{nextPageCommand:iF(T),nextPageArgs:T}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await iu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let p=[];try{let y=await mr(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await An({paths:e,identity:y});C.state==="drifted"&&C.code&&p.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await wl({paths:e,identity:y});p.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{p.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let f=[],m=!1;if(o.phase==="verify"){let y=await HS({paths:e,state:o});m=y.freshness!=="fresh",f.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,v=[];if(o.phase==="archive")try{h=await lm({paths:e,name:o.name}),v.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await oF(e,o),...s.findings,...d,...p,...f,...l,...v].filter((y,C,O)=>O.findIndex(T=>T.code===y.code&&T.path===y.path)===C),b=Xh({paths:e,state:o,findings:g}),k=b.filter(y=>!_n(y.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,x=m||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),w=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),S=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=b.find(y=>y.severity==="error");return{name:o.name,artifacts:Qo(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:w||S?null:aF(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:Qh(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Ql({state:o,findings:b,archiveReady:N,evidenceRetreat:x,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:tu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function LS(e){let t;try{t=await mf({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await rF.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Zo.maxChanges))throw new Error(`Native status exceeds ${Zo.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}K();var pm=ir(Bt(),1);pt();de();at();xt();import{promises as sF}from"node:fs";import dm from"node:path";var au=class extends Error{};async function su(e,t){let r=await re({root:e.nativeRoot,ref:dm.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,pm.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new au("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:ze(i)}}async function MS(e,t,r){let i;try{i=await sF.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=dm.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await su(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof au)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function ou(e){return j("comet.native.status-record.v1",e)}function qS(e){let t=dm.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Je(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=ze((0,pm.parse)(Je(e.projectRoot,["show",`${r}:${t}`])));return ou(i)===ou(e.state)?r:null}catch{return null}}function VS(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=qS(e),i=qS(t);if(!r||!i)return!1;try{return Je(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function WS(e,t){return e.state.archived&&t.state.archived&&ou(e.state)===ou(t.state)}import ZS from"node:path";import{promises as zS}from"node:fs";import cF from"node:path";de();var lF=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),uF=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),dF=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),pF=new Set(["status","summary"]);function cu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function lu(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function fF(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Mi(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function hF(e,t,r,i){let n=cu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=lu(n,lF,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=cu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=lu(o,uF,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=cu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=lu(c,pF,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let p=cu(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:m,...h}=p,v=lu(h,dF,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],b=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(b)||m!==void 0&&m!==j("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(p.name!==g.name||p.summary!==g.summary||!fF(p.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let k=g.depends_on.length===0?"ready":"pending";if(p.status!==k)return`Native Supervisor child ${g.name} has progressed beyond its initial ${k} status`;if(p.baseCommit!==null||p.candidateCommit!==null||p.verifiedCommit!==null||p.integrationCommit!==null||p.verification!==null||p.blocker!==null||p.projectRoot!==null||p.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((p.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(p.checks)||p.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function GS(e){let t=Ao(e.paths,e.state.name),r;try{let c=await zS.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Mi(t,"","Native Supervisor overlay is not a regular file");r=await zS.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Mi(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Mi(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=cF.join(e.paths.changesDir,e.state.name),a;try{a=await Qt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Mi(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await et(e.paths,e.state.name)}catch(c){return Mi(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Mi(t,r,"Native Supervisor overlay disappeared during inspection");let s=hF(i,e.state,a.contract,o);return s?Mi(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}io();Oi();function Se(e,t,r){return e.language==="zh-CN"?r:t}function mF(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:Se(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:Se(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Se(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(Se(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(Se(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"){let a=i==="confirmed"?Se(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Se(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} ${Se(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:Se(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(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:Se(e,"Accept the result","接受结果"),agentInstruction:Se(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=$l)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(Se(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(Se(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function vF(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 gF(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:Se(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Se(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function YS(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Vi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function JS(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function wF(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function US(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function yF(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function NF(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function rr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:YS({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Vi("summary","--summary"),wF(e.name,e.flag)]}}function KS(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:Se(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function bF(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function uu(e){return[rr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),rr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function kF(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 es(e,t,r={}){let i=yF(t)&&e.coordination_mode===void 0,n=mF(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:[Vi("summary","--summary")],commandAlternatives:i?Cy.map(s=>{let c=rr({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,US("coordination-mode","--coordination-mode",[s])]}}):[rr({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:[Vi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=rr({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],rr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...uu({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:[Vi("summary","--summary")],commandAlternatives:[rr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),rr({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:[Vi("summary","--summary")],commandAlternatives:[rr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...uu({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:[Vi("summary","--summary")],commandAlternatives:uu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:uu({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?YS({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:NF({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[JS()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=$l)??null,p=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:Se(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&p===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:p!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:p!==null?[p]:[Vi("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=JS();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Se(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:kF([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=KS(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>bF(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:KS(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[US("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...gF(e)],userCommunication:vF(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[rr({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 XS from"node:path";function QS(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function fm(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:QS(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:QS(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>XS.relative(t.projectRoot,XS.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}K();function eE(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function tE(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function rE(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:xF(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:CF(i,r)}))]:[]]}function iE(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function SF(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=Gf(e,t??null);if(n===void 0)return;let a=n==="confirmed";return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:a?"confirmed":"unconfirmed",...a?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function du(e,t,r=we(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:ZS.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function hm(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=fm(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...es(t),status:"blocked",disposition:"blocked",action:"archive",requiresUserDecision:!1,commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:null,agentInstruction:"Report the Git blocker and resolve it within the recorded delivery authorization, then retry the recorded Native workspace finish command. Ask the user only when new information or authorization is required; keep delivery pending until it succeeds."},runnerAction:{...es(t).runnerAction,kind:"none"}}:es(t),c=e.details?rE(t,null,[]):[],l=tE(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?eE(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:za(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:ZS.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:iE(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function EF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function pu(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function xF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:pu(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function CF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:pu(e.summary,t)??""}}async function nE(e){let t=await Uf(e),r=fm(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Io({paths:e.paths,state:t.state}),a=await GS({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await et(e.paths,e.name,{diagnostics:!0}),s=o?{...du(e.paths,t.state,e.gitContext),projectRoot:"."}:du(e.paths,t.state,e.gitContext),c=es(t.state,n,{verifierExecutionRef:zf(t.state,t.local),verifierStartup:Gf(t.state,t.localStatus==="available"?t.local:null),...t.local?{verificationCheckPlans:Bk(t.local,t.local.workspace.projectRoot)}:{}}),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?EF(e.paths,o):[],d=o?(()=>{let m=new Map(n?.children.map(w=>[w.name,w.status])??[]),h=w=>m.get(w.name)??w.status,v=o.children.filter(w=>h(w)==="pending"||h(w)==="ready").length,g=o.children.filter(w=>h(w)==="active"||h(w)==="verified").length,b=o.children.filter(w=>h(w)==="integrated"||h(w)==="archived").length,k=o.children.filter(w=>h(w)==="blocked"||h(w)==="needs-reverify").length,N=o.children.filter(w=>h(w)==="active"||h(w)==="blocked"||h(w)==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:pu(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let S=pu(w,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:b,blocked:k,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:b},risks:x,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&b===o.children.length?"parent-verification":v>0?"dispatch-ready-child":k>0?"resolve-blocker":"continue-supervisor"}})():null,p=e.details?(()=>{let m=o?.stateVersion??0,h=rE(t.state,o,u),v=tE(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?eE(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:m}})():null,f=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,artifacts:za(e.paths,t.state.name),phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:iE(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=SF(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...m?{verifierStartup:m}:{}}})(),...n?{childSummary:n.children.reduce((m,h)=>({...m,[h.status]:(m[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:p.supervisorStateVersion}:{},items:p.items,nextCursor:p.nextCursor,nextPageArgs:p.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",p.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}import{accessSync as eX,constants as tX,promises as mm}from"node:fs";import Xn from"node:path";oe();Ji();pt();Bl();Ji();var aE="comet.native.workspace-finish.v1",sE="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",cE=new RegExp(`^${sE}$`,"u"),PF=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,ts=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function oE(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function _F(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==aE||typeof t.name!="string"||!cE.test(t.name)||typeof t.transactionId!="string"||!PF.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Xn.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(i=>typeof i=="string"&&Xn.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!Xn.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");oE(r.commitMessage,"commit-message"),r.mergeMessage!==null&&oE(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!ts.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!Xn.posix.isAbsolute(i)&&!Xn.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!ts.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!ts.test(r.target)||!ts.test(r.source)||r.sha!==null&&!ts.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:aE,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function AF(e,t){if(!cE.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Xn.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function vm(e,t,r={}){let i=AF(e,t);try{let n=await mm.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=_F(JSON.parse(await mm.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function lE(e,t={}){let r;try{r=await mm.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${sE})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await vm(e,a[1],t);o&&i.push(o)}return i}function fu(e,t){let r=Wi.normalize(gm(e)),i=Wi.normalize(gm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function gm(e){let t=Wi.resolve(e);try{return IF.native(t)}catch{return t}}async function uE(e,t){let r=[];for(let i of await LS(e))t!==void 0&&i!==t||r.push({name:i,kind:await ko(e,i)?"portable":"legacy"});return r}async function TF(e,t){let r=Wi.resolve(e),i=cs(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>fu(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>Wi.resolve(l)).sort()){let l=fu(c,r)?r:c,u=gm(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let p=await xe(l);if(!p)continue;let f=await Vt(l,p.native.artifact_root);o.push({projectRoot:l,config:p,paths:f,gitContext:na(l,i)??we(l),changes:await uE(f,t)})}if(o.length===0){let c=await xe(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Vt(e,c.native.artifact_root);o.push({projectRoot:Wi.resolve(e),config:c,paths:l,gitContext:na(e,i)??we(e),changes:await uE(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await MS(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await vm(c.paths,t,{onError:l})].filter(u=>u!==null):await lE(c.paths,{onError:l})}return o}function dE(e,t){return e.workspace.bindingState==="aligned"?0:fu(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function jF(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:d,kind:p})=>{let f=d.finishJournalErrors?.find(({name:m})=>m===n);if(p==="portable")try{let m=await ft(d.paths,n);return{source:d,name:n,kind:p,workspace:du(d.paths,m,d.gitContext),portableStatus:null,inspectionError:f?.message??null,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}}catch(m){return{source:d,name:n,kind:p,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:d,name:n,kind:p,workspace:a.length>1?await ho(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:f?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:p})=>p.name===n).map(p=>{let f=hm({paths:d.paths,...p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null});return{source:d,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:d.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(f=>f.finishJournals?.some(({name:m})=>m===n)),p=d?.finishJournals?.find(({name:f})=>f===n);if(d&&p){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:p.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:p.result?.message??"Native workspace finish record is orphaned."},finishJournal:p});continue}}if(s.length>0){for(let p of o)if(p.kind==="portable")try{p.record=await su(p.source.paths,Wi.join(p.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(p=>[...o,...s.filter(f=>!WS(p.record,f.record))].every(f=>f.record&&VS(p.record,f.record)));if(d){i.push(d);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((d,p)=>dE(d,e)-dE(p,e)||d.source.projectRoot.localeCompare(p.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>Zo.maxChanges)throw new Error(`Native status discovery exceeds ${Zo.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}async function $F(e,t,r){let i=await ho(e.source.paths,e.name),n=null;try{n=await UN(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:um(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function pE(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return hm({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await nE({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return pE({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return $F(e,t,r)}async function fE(e){let{sources:t,candidates:r}=await OF(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>fu(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),um(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}return e.onSelectedRoot?.(r[0].source.projectRoot),pE(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function OF(e,t){let r=await TF(e,t),i=(await jF(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}Ma();import rs from"path";import{realpathSync as ZF}from"fs";function hE(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),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var Sr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mE(e){return e?e.command?`${Sr.next} ${e.command}`:e.ask_user?`${Sr.next} ${e.ask_user}`:null:null}function vE(e,t){let r=[e.summary],i=mE(e.next);return i&&r.push(i),e.user_message&&r.push("",Sr.relay,e.user_message),t!==void 0&&r.push("",Sr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
179
256
|
`)}
|
|
180
|
-
`}function
|
|
181
|
-
`)}
|
|
182
|
-
`)}}let r=t.continuation;if(
|
|
257
|
+
`}function gE(e,t,r){let i=[e.summary],n=mE(e.next);return n&&i.push(n),e.user_message&&i.push("",Sr.relay,e.user_message),i.push("",`${Sr.detail} ${t}`),r!==void 0&&i.push("",Sr.details,JSON.stringify(r,null,2)),i.join(`
|
|
258
|
+
`)}Ut();Ct();oe();Lt();K();Ct();Zc();oe();yi();si();var tQ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Ut();Ua();Re();K();Ct();Zc();var hu=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"},mu=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"};K();Qe();function L(e,t,r){return e==="zh-CN"?r:t}var wm={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function wE(e,t){return typeof e=="string"&&wm[e]?L(t,wm[e].en,wm[e].zh):typeof e=="string"?e:""}function ym(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 BF(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 yE(e,t){let r=[];e.failed>0&&r.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function NE(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 Nm(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function FF(e,t,r){return e==="done"?L(r,"complete","已完成"):e==="await-user"?L(r,"waiting for a user decision","等待用户决定"):e==="blocked"?L(r,"paused: needs attention","已暂停,需要处理"):t?L(r,"waiting for a user decision","等待用户决定"):L(r,"ready to continue","可继续推进")}function LF(e,t,r){let i=Nm(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=wE(e.phase,i),s=FF(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(yE(t,i));let c=e.userCommunication,l=bE(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function bE(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:L(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:L(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:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function qF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function MF(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=wE(e.phase,t),n=e.status==="await-user"?L(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?L(t,"paused","已暂停"):e.status==="done"?L(t,"complete","已完成"):L(t,"in progress","进行中"),a=ym(e.acceptance)?`${L(t,", ",",")}${yE(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function VF(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 WF(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 zF(e){if(e.healthy){let i=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=GF(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("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:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function GF(e){return NE(e)?bE(e,Nm(e)):void 0}function kE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(WF(t))return zF(t);if(qF(t)){let i=VF(t.items);return{summary:[t.total===t.items.length?L(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>MF(a,i))].join(`
|
|
259
|
+
`)}}let r=t.continuation;if(NE(r)){let i=Nm(r),n=LF(r,JF(t),KF(t,i));return UF(t)==="unconfirmed"?{...n,summary:`${n.summary}${L(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:L(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 JF(e){if(ym(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(ym(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return BF(r.acceptance)}return null}function UF(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 KF(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function SE(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:L("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:L("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:L("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:L("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:L("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:L("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:L("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:L("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:L("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}qc();Mc();var EE=["--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."],bm=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:EE,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
|
|
183
260
|
comet native spec remove <change-name> <capability>
|
|
184
261
|
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>]
|
|
185
262
|
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>]
|
|
186
|
-
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
|
|
187
|
-
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
|
|
263
|
+
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>]
|
|
264
|
+
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 vu(e,t){return`${e}:
|
|
188
265
|
${t.map(r=>` ${r}`).join(`
|
|
189
|
-
`)}`}function
|
|
190
|
-
${r.output}`),r.examples&&i.push("",
|
|
266
|
+
`)}`}function YF(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return bm[r]||t.length>1&&bm[t[0]]?.subcommands?r:t[0]}function XF(e=[]){let t=YF(e),r=bm[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",vu("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",vu("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...EE];return n&&n.length>0&&i.push("",vu("Options",n)),i.push("",`Output:
|
|
267
|
+
${r.output}`),r.examples&&i.push("",vu("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
191
268
|
`)}
|
|
192
|
-
`}}var
|
|
193
|
-
`}function
|
|
194
|
-
`}:e.error?{exitCode:e.exitCode,stderr:i?
|
|
195
|
-
${
|
|
269
|
+
`}}var QF=XF().usage;var cZ=10*1024*1024,ui=class extends Error{};function Sm(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new ui(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function CE(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new ui(`${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 ui(`${t} requires a value`);return e.splice(i,2),n}function RE(e){if(e.length>0)throw new ui(`Unexpected argument: ${e[0]}`)}function PE(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new ui(`${t} is required`);return r}function km(e,t){let r=rs.normalize(xE(e)),i=rs.normalize(xE(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function xE(e){let t=rs.resolve(e);try{return ZF.native(t)}catch{return t}}function eL(e,t){let r=rs.resolve(t,e),i=we(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=we(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!km(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||km(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:km(t,i.currentWorktreeRoot)?rs.resolve(t):i.currentWorktreeRoot}async function _E(e,t=process.cwd()){return e?eL(e,t):Ec(t)}function AE(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function Em(e){let t=await qw({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function IE(e){return JSON.stringify(e,null,2)+`
|
|
270
|
+
`}function TE(e,t,r){return{command:e,exitCode:0,data:t,text:r??IE(t)}}function tL(e,t){if(t instanceof vo)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof vn)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 ro)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof ui)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof hu)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 mu)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof yl)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 mo)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 Fl)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Nl)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 li)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Xo)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 jE(e,t){let r=tL(e,t),i=r.error;if(!i)return r;let n=SE({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function rL(e,t,r=!1){let i=e.envelope??kE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:hE(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}})+`
|
|
271
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?gE(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:vE(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==IE(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
272
|
+
${Sr.details}
|
|
196
273
|
${JSON.stringify(e.data,null,2)}
|
|
197
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function
|
|
274
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function iL(e,t,r=!1){let i=rL(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 $E(e,t,r=!1){return iL(e,t,r).output}async function OE(e,t){let r=PE(e,"change name");RE(e),await Em(t);let i=t,n=await fE({projectRoot:t,name:r,onSelectedRoot:a=>{i=a}});return await Lk((await Em(i)).paths,r),{...TE("select",{selected:r,...n}),executionCwd:i}}async function HE(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"),c,l;try{Sm(n,"--json"),Sm(n,"--verbose"),c=CE(n,"--project-root");let d=[...n,...a],p=async()=>{let f=await _E(c);return{executionCwd:f,...await t(d,f)}};l=AE(e,d)?await Am(p):await p()}catch(d){l=jE(e,d)}let u=$E(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
198
275
|
`)?"":`
|
|
199
|
-
`)),u.exitCode}process.exitCode=await
|
|
276
|
+
`)),u.exitCode}process.exitCode=await HE("select",OE);
|