@rpamis/comet 0.4.2 → 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/LICENSE +21 -21
- 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 +3 -1
- package/assets/skills/comet-classic/reference/scripts.md +17 -1
- package/assets/skills/comet-design/SKILL.md +0 -2
- package/assets/skills/comet-hotfix/SKILL.md +2 -3
- package/assets/skills/comet-native/SKILL.md +11 -8
- 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 +25 -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 +2 -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 +3 -1
- package/assets/skills-zh/comet-classic/reference/scripts.md +11 -1
- package/assets/skills-zh/comet-design/SKILL.md +0 -2
- package/assets/skills-zh/comet-hotfix/SKILL.md +2 -3
- package/assets/skills-zh/comet-native/SKILL.md +11 -8
- 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 +26 -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 +2 -1
- package/assets/skills-zh/comet-verify/SKILL.md +0 -2
- package/bin/comet-daemon-router.js +57 -13
- 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 +14 -2
- package/dist/app/commands/daemon-server.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +0 -1
- package/dist/app/commands/project-knowledge.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 +2 -0
- package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.js +90 -27
- 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 +15 -4
- package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.js +167 -66
- 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/project-knowledge/corpus.d.ts +5 -0
- package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
- package/dist/domains/project-knowledge/corpus.js +34 -9
- package/dist/domains/project-knowledge/corpus.js.map +1 -1
- package/dist/domains/project-knowledge/index-store.d.ts +5 -2
- package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/index-store.js +95 -52
- package/dist/domains/project-knowledge/index-store.js.map +1 -1
- package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-provider.js +14 -3
- package/dist/domains/project-knowledge/local-provider.js.map +1 -1
- package/dist/domains/project-knowledge/local-store.d.ts +2 -2
- package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-store.js +2 -2
- package/dist/domains/project-knowledge/local-store.js.map +1 -1
- package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
- package/dist/domains/project-knowledge/plugin.js +5 -4
- package/dist/domains/project-knowledge/plugin.js.map +1 -1
- package/dist/domains/project-knowledge/provider-factory.d.ts.map +1 -1
- package/dist/domains/project-knowledge/provider-factory.js +7 -5
- package/dist/domains/project-knowledge/provider-factory.js.map +1 -1
- package/dist/domains/project-knowledge/types.d.ts +1 -0
- package/dist/domains/project-knowledge/types.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +31 -3
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/workflow-contract/hook-target-scope.d.ts.map +1 -1
- package/dist/domains/workflow-contract/hook-target-scope.js +2 -1
- package/dist/domains/workflow-contract/hook-target-scope.js.map +1 -1
- package/dist/platform/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 +9 -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 +13 -0
- package/dist/platform/process/windows-process-broker.d.ts.map +1 -0
- package/dist/platform/process/windows-process-broker.js +150 -0
- package/dist/platform/process/windows-process-broker.js.map +1 -0
- 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,193 +1,270 @@
|
|
|
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 uS=Object.create;var Dl=Object.defineProperty;var dS=Object.getOwnPropertyDescriptor;var pS=Object.getOwnPropertyNames;var fS=Object.getPrototypeOf,hS=Object.prototype.hasOwnProperty;var zo=(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}},mS=(e,t)=>{for(var r in t)Dl(e,r,{get:t[r],enumerable:!0})},vS=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pS(t))!hS.call(e,n)&&n!==r&&Dl(e,n,{get:()=>t[n],enumerable:!(i=dS(t,n))||i.enumerable});return e};var Kt=(e,t,r)=>(r=e!=null?uS(fS(e)):{},vS(t||!e||!e.__esModule?Dl(r,"default",{value:e,enumerable:!0}):r,e));import{AsyncLocalStorage as gS}from"node:async_hooks";import{performance as Ph}from"node:perf_hooks";function Bl(e=0){wS+=1,yS+=e;let t=NS.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function zn(e){let t=Ph.now();try{return e()}finally{Bl(Ph.now()-t)}}var wS,yS,NS,Hi=I(()=>{"use strict";wS=0,yS=0,NS=new gS});var $D,Gn=I(()=>{"use strict";$D=["$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("; ")});var BD,Di=I(()=>{"use strict";Hi();Gn();BD=8*1024*1024});import{createHash as RS}from"crypto";function dt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function PS(e,t){t.has(e)&&dt("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)||dt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&dt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&dt("symbol properties are not supported"),`[${e.map(i=>Fl(i,t)).join(",")}]`}finally{t.delete(e)}}function _S(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&dt("only plain objects are supported"),t.has(e)&&dt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&dt("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))&&dt("accessor properties are not supported"),`${JSON.stringify(o)}:${Fl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Fl(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)||dt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?PS(e,t):_S(e,t);case"bigint":case"function":case"symbol":case"undefined":return dt(`${typeof e} values are not supported`)}return dt("unsupported value type")}function Yn(e){return Fl(e,new Set)}function T(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 RS("sha256").update(`${e}
|
|
5
|
+
${Yn(t)}`).digest("hex")}var ue=I(()=>{"use strict"});var W=R(ke=>{"use strict";var Ll=Symbol.for("yaml.alias"),Oh=Symbol.for("yaml.document"),Jo=Symbol.for("yaml.map"),Hh=Symbol.for("yaml.pair"),ql=Symbol.for("yaml.scalar"),Uo=Symbol.for("yaml.seq"),Xt=Symbol.for("yaml.node.type"),AS=e=>!!e&&typeof e=="object"&&e[Xt]===Ll,IS=e=>!!e&&typeof e=="object"&&e[Xt]===Oh,TS=e=>!!e&&typeof e=="object"&&e[Xt]===Jo,jS=e=>!!e&&typeof e=="object"&&e[Xt]===Hh,Dh=e=>!!e&&typeof e=="object"&&e[Xt]===ql,$S=e=>!!e&&typeof e=="object"&&e[Xt]===Uo;function Bh(e){if(e&&typeof e=="object")switch(e[Xt]){case Jo:case Uo:return!0}return!1}function OS(e){if(e&&typeof e=="object")switch(e[Xt]){case Ll:case Jo:case ql:case Uo:return!0}return!1}var HS=e=>(Dh(e)||Bh(e))&&!!e.anchor;ke.ALIAS=Ll;ke.DOC=Oh;ke.MAP=Jo;ke.NODE_TYPE=Xt;ke.PAIR=Hh;ke.SCALAR=ql;ke.SEQ=Uo;ke.hasAnchor=HS;ke.isAlias=AS;ke.isCollection=Bh;ke.isDocument=IS;ke.isMap=TS;ke.isNode=OS;ke.isPair=jS;ke.isScalar=Dh;ke.isSeq=$S});var Xn=R(Ml=>{"use strict";var ge=W(),Be=Symbol("break visit"),Fh=Symbol("skip children"),_t=Symbol("remove node");function Ko(e,t){let r=Lh(t);ge.isDocument(e)?Bi(null,e.contents,r,Object.freeze([e]))===_t&&(e.contents=null):Bi(null,e,r,Object.freeze([]))}Ko.BREAK=Be;Ko.SKIP=Fh;Ko.REMOVE=_t;function Bi(e,t,r,i){let n=qh(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Mh(e,i,n),Bi(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Bi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Be)return Be;o===_t&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=Bi("key",t.key,r,i);if(a===Be)return Be;a===_t&&(t.key=null);let o=Bi("value",t.value,r,i);if(o===Be)return Be;o===_t&&(t.value=null)}}return n}async function Yo(e,t){let r=Lh(t);ge.isDocument(e)?await Fi(null,e.contents,r,Object.freeze([e]))===_t&&(e.contents=null):await Fi(null,e,r,Object.freeze([]))}Yo.BREAK=Be;Yo.SKIP=Fh;Yo.REMOVE=_t;async function Fi(e,t,r,i){let n=await qh(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Mh(e,i,n),Fi(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Fi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Be)return Be;o===_t&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=await Fi("key",t.key,r,i);if(a===Be)return Be;a===_t&&(t.key=null);let o=await Fi("value",t.value,r,i);if(o===Be)return Be;o===_t&&(t.value=null)}}return n}function Lh(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 qh(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ge.isMap(t))return r.Map?.(e,t,i);if(ge.isSeq(t))return r.Seq?.(e,t,i);if(ge.isPair(t))return r.Pair?.(e,t,i);if(ge.isScalar(t))return r.Scalar?.(e,t,i);if(ge.isAlias(t))return r.Alias?.(e,t,i)}function Mh(e,t,r){let i=t[t.length-1];if(ge.isCollection(i))i.items[e]=r;else if(ge.isPair(i))e==="key"?i.key=r:i.value=r;else if(ge.isDocument(i))i.contents=r;else{let n=ge.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ml.visit=Ko;Ml.visitAsync=Yo});var Vl=R(Wh=>{"use strict";var Vh=W(),DS=Xn(),BS={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},FS=e=>e.replace(/[!,[\]{}]/g,t=>BS[t]),Qn=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+FS(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&&Vh.isNode(t.contents)){let a={};DS.visit(t.contents,(o,s)=>{Vh.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
|
+
`)}};Qn.defaultYaml={explicit:!1,version:"1.2"};Qn.defaultTags={"!!":"tag:yaml.org,2002:"};Wh.Directives=Qn});var Xo=R(Zn=>{"use strict";var zh=W(),LS=Xn();function qS(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 Gh(e){let t=new Set;return LS.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Jh(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function MS(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Gh(e));let o=Jh(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(zh.isScalar(o.node)||zh.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}}Zn.anchorIsValid=qS;Zn.anchorNames=Gh;Zn.createNodeAnchors=MS;Zn.findNewAnchor=Jh});var Wl=R(Uh=>{"use strict";function ea(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=ea(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=ea(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=ea(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=ea(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Uh.applyReviver=ea});var Nr=R(Yh=>{"use strict";var VS=W();function Kh(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Kh(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!VS.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}Yh.toJS=Kh});var Qo=R(Qh=>{"use strict";var WS=Wl(),Xh=W(),zS=Nr(),zl=class{constructor(t){Object.defineProperty(this,Xh.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(!Xh.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=zS.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?WS.applyReviver(a,{"":s},"",s):s}};Qh.NodeBase=zl});var ta=R(Zh=>{"use strict";var GS=Xo(),JS=Xn(),Li=W(),US=Qo(),KS=Nr(),Gl=class extends US.NodeBase{constructor(t){super(Li.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=[],JS.visit(t,{Node:(a,o)=>{(Li.isAlias(o)||Li.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||(KS.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=Zo(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(GS.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 Zo(e,t,r){if(Li.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Li.isCollection(t)){let i=0;for(let n of t.items){let a=Zo(e,n,r);a>i&&(i=a)}return i}else if(Li.isPair(t)){let i=Zo(e,t.key,r),n=Zo(e,t.value,r);return Math.max(i,n)}return 1}Zh.Alias=Gl});var de=R(Jl=>{"use strict";var YS=W(),XS=Qo(),QS=Nr(),ZS=e=>!e||typeof e!="function"&&typeof e!="object",br=class extends XS.NodeBase{constructor(t){super(YS.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:QS.toJS(this.value,t,r)}toString(){return String(this.value)}};br.BLOCK_FOLDED="BLOCK_FOLDED";br.BLOCK_LITERAL="BLOCK_LITERAL";br.PLAIN="PLAIN";br.QUOTE_DOUBLE="QUOTE_DOUBLE";br.QUOTE_SINGLE="QUOTE_SINGLE";Jl.Scalar=br;Jl.isScalarValue=ZS});var ra=R(tm=>{"use strict";var eE=ta(),oi=W(),em=de(),tE="tag:yaml.org,2002:";function rE(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 iE(e,t,r){if(oi.isDocument(e)&&(e=e.contents),oi.isNode(e))return e;if(oi.isPair(e)){let d=r.schema[oi.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 eE.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=tE+t.slice(2));let l=rE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new em.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[oi.MAP]:Symbol.iterator in Object(e)?o[oi.SEQ]:o[oi.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 em.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}tm.createNode=iE});var ts=R(es=>{"use strict";var nE=ra(),At=W(),aE=Qo();function Ul(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 nE.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 rm=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Kl=class extends aE.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=>At.isNode(i)||At.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(rm(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(At.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ul(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(At.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&&At.isScalar(a)?a.value:a:At.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!At.isPair(r))return!1;let i=r.value;return i==null||t&&At.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 At.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(At.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ul(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};es.Collection=Kl;es.collectionFromPath=Ul;es.isEmptyPath=rm});var ia=R(rs=>{"use strict";var oE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Yl(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var sE=(e,t,r)=>e.endsWith(`
|
|
7
|
+
`)?Yl(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
|
+
`+Yl(r,t):(e.endsWith(" ")?"":" ")+r;rs.indentComment=Yl;rs.lineComment=sE;rs.stringifyComment=oE});var nm=R(na=>{"use strict";var cE="flow",Xl="block",is="quoted";function lE(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===Xl&&(h=im(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===is&&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===Xl&&(h=im(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===is){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===is&&u[N]&&(b+=`${e[N]}\\`),b+=`
|
|
14
|
+
${t}${e.slice(N+1,x)}`)}return b}function im(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}na.FOLD_BLOCK=Xl;na.FOLD_FLOW=cE;na.FOLD_QUOTED=is;na.foldFlowLines=lE});var oa=R(am=>{"use strict";var pt=de(),kr=nm(),as=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),os=e=>/^(%|---|\.\.\.)/m.test(e);function uE(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 aa(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(os(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:kr.foldFlowLines(o,a,kr.FOLD_QUOTED,as(t,!1))}function Ql(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
20
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return aa(e,t);let r=t.indent||(os(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
21
|
+
${r}`)+"'";return t.implicitKey?i:kr.foldFlowLines(i,r,kr.FOLD_FLOW,as(t,!1))}function qi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=aa;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Ql:a&&!n?i=aa:i=r?Ql:aa}return i(e,t)}var Zl;try{Zl=new RegExp(`(^|(?<!
|
|
22
22
|
))
|
|
23
23
|
+(?!
|
|
24
|
-
|$)`,"g")}catch{
|
|
24
|
+
|$)`,"g")}catch{Zl=/\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 qi(r,i);let l=i.indent||(i.forceBlockIndent||os(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===pt.Scalar.BLOCK_FOLDED?!1:t===pt.Scalar.BLOCK_LITERAL?!0:!uE(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(Zl,`$&${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=as(i,!0);o!=="folded"&&t!==pt.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{w=!0});let E=kr.foldFlowLines(`${b}${x}${f}`,l,kr.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 dE(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 qi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
35
|
+
`)?qi(a,t):ns(e,t,r,i);if(!s&&!u&&n!==pt.Scalar.PLAIN&&a.includes(`
|
|
36
|
+
`))return ns(e,t,r,i);if(os(a)){if(c==="")return t.forceBlockIndent=!0,ns(e,t,r,i);if(s&&c===l)return qi(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 qi(a,t)}return s?d:kr.foldFlowLines(d,c,kr.FOLD_FLOW,as(t,!1))}function pE(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!==pt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=pt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case pt.Scalar.BLOCK_FOLDED:case pt.Scalar.BLOCK_LITERAL:return n||a?qi(o.value,t):ns(o,t,r,i);case pt.Scalar.QUOTE_DOUBLE:return aa(o.value,t);case pt.Scalar.QUOTE_SINGLE:return Ql(o.value,t);case pt.Scalar.PLAIN:return dE(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}am.stringifyString=pE});var sa=R(eu=>{"use strict";var fE=Xo(),Sr=W(),hE=ia(),mE=oa();function vE(e,t){let r=Object.assign({blockQuote:!0,commentString:hE.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 gE(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(Sr.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 wE(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Sr.isScalar(e)||Sr.isCollection(e))&&e.anchor;a&&fE.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 yE(e,t,r,i){if(Sr.isPair(e))return e.toString(t,r,i);if(Sr.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=Sr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=gE(t.doc.schema.tags,a));let o=wE(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):Sr.isScalar(a)?mE.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Sr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
38
|
+
${t.indent}${s}`:s}eu.createStringifyContext=vE;eu.stringify=yE});var lm=R(cm=>{"use strict";var Qt=W(),om=de(),sm=sa(),ca=ia();function NE({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=Qt.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(Qt.isCollection(e)||!Qt.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||Qt.isCollection(e)||(Qt.isScalar(e)?e.type===om.Scalar.BLOCK_FOLDED||e.type===om.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=sm.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+=ca.lineComment(v,r.indent,l(p)):h&&n&&n(),v;m&&(p=null),f?(p&&(v+=ca.lineComment(v,r.indent,l(p))),v=`? ${v}
|
|
39
|
+
${s}:`):(v=`${v}:`,p&&(v+=ca.lineComment(v,r.indent,l(p))));let g,b,k;Qt.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&&Qt.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!f&&Qt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,x=sm.stringify(t,r,()=>N=!0,()=>h=!0),w=" ";if(p||g||b){if(w=g?`
|
|
40
|
+
`:"",b){let S=l(b);w+=`
|
|
41
|
+
${ca.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&&Qt.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 j=x.indexOf(" ");S==="&"&&j!==-1&&j<E&&x[j+1]==="!"&&(j=x.indexOf(" ",j+1)),(j===-1||E<j)&&(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+=ca.lineComment(v,r.indent,l(k)):h&&n&&n(),v}cm.stringifyPair=NE});var ru=R(tu=>{"use strict";var um=zo("process");function bE(e,...t){e==="debug"&&console.log(...t)}function kE(e,t){(e==="debug"||e==="warn")&&(typeof um.emitWarning=="function"?um.emitWarning(t):console.warn(t))}tu.debug=bE;tu.warn=kE});var ds=R(us=>{"use strict";var ls=W(),dm=de(),ss="<<",cs={identify:e=>e===ss||typeof e=="symbol"&&e.description===ss,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new dm.Scalar(Symbol(ss)),{addToJSMap:pm}),stringify:()=>ss},SE=(e,t)=>(cs.identify(t)||ls.isScalar(t)&&(!t.type||t.type===dm.Scalar.PLAIN)&&cs.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===cs.tag&&r.default);function pm(e,t,r){let i=fm(e,r);if(ls.isSeq(i))for(let n of i.items)iu(e,t,n);else if(Array.isArray(i))for(let n of i)iu(e,t,n);else iu(e,t,i)}function iu(e,t,r){let i=fm(e,r);if(!ls.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 fm(e,t){return e&&ls.isAlias(t)?t.resolve(e.doc,e):t}us.addMergeToJSMap=pm;us.isMergeKey=SE;us.merge=cs});var au=R(vm=>{"use strict";var EE=ru(),hm=ds(),xE=sa(),mm=W(),nu=Nr();function CE(e,t,{key:r,value:i}){if(mm.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(hm.isMergeKey(e,r))hm.addMergeToJSMap(e,t,i);else{let n=nu.toJS(r,"",e);if(t instanceof Map)t.set(n,nu.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=RE(r,n,e),o=nu.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 RE(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(mm.isNode(e)&&r?.doc){let i=xE.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)+'..."'),EE.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)}vm.addPairToJSMap=CE});var Er=R(ou=>{"use strict";var gm=ra(),PE=lm(),_E=au(),ps=W();function AE(e,t,r){let i=gm.createNode(e,void 0,r),n=gm.createNode(t,void 0,r);return new fs(i,n)}var fs=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 _E.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?PE.stringifyPair(this,t,r,i):JSON.stringify(this)}};ou.Pair=fs;ou.createPair=AE});var su=R(ym=>{"use strict";var si=W(),wm=sa(),hs=ia();function IE(e,t,r){return(t.inFlow??e.flow?jE:TE)(e,t,r)}function TE({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(si.isNode(h))!d&&h.spaceBefore&&p.push(""),ms(r,p,h.commentBefore,d),h.comment&&(v=h.comment);else if(si.isPair(h)){let b=si.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&p.push(""),ms(r,p,b.commentBefore,d))}d=!1;let g=wm.stringify(h,u,()=>v=null,()=>d=!0);v&&(g+=hs.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
|
+
`+hs.indentComment(l(e),c),s&&s()):d&&o&&o(),f}function jE({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(si.isNode(h))h.spaceBefore&&d.push(""),ms(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(si.isPair(h)){let b=si.isNode(h.key)?h.key:null;b&&(b.spaceBefore&&d.push(""),ms(t,d,b.commentBefore,!1),b.comment&&(l=!0));let k=si.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=wm.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+=hs.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 ms({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=hs.indentComment(t(i),e);r.push(a.trimStart())}}ym.stringifyCollection=IE});var Cr=R(lu=>{"use strict";var $E=su(),OE=au(),HE=ts(),xr=W(),vs=Er(),DE=de();function la(e,t){let r=xr.isScalar(t)?t.value:t;for(let i of e)if(xr.isPair(i)&&(i.key===t||i.key===r||xr.isScalar(i.key)&&i.key.value===r))return i}var cu=class extends HE.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(xr.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(vs.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;xr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new vs.Pair(t,t?.value):i=new vs.Pair(t.key,t.value);let n=la(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);xr.isScalar(n.value)&&DE.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=la(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=la(this.items,t)?.value;return(!r&&xr.isScalar(n)?n.value:n)??void 0}has(t){return!!la(this.items,t)}set(t,r){this.add(new vs.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)OE.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!xr.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})),$E.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};lu.YAMLMap=cu;lu.findPair=la});var Mi=R(bm=>{"use strict";var BE=W(),Nm=Cr(),FE={collection:"map",default:!0,nodeClass:Nm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return BE.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Nm.YAMLMap.from(e,t,r)};bm.map=FE});var Rr=R(km=>{"use strict";var LE=ra(),qE=su(),ME=ts(),ws=W(),VE=de(),WE=Nr(),uu=class extends ME.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ws.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=gs(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=gs(t);if(typeof i!="number")return;let n=this.items[i];return!r&&ws.isScalar(n)?n.value:n}has(t){let r=gs(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=gs(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];ws.isScalar(n)&&VE.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(WE.toJS(a,String(n++),r));return i}toString(t,r,i){return t?qE.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(LE.createNode(s,void 0,i))}}return a}};function gs(e){let t=ws.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}km.YAMLSeq=uu});var Vi=R(Em=>{"use strict";var zE=W(),Sm=Rr(),GE={collection:"seq",default:!0,nodeClass:Sm.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return zE.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Sm.YAMLSeq.from(e,t,r)};Em.seq=GE});var ua=R(xm=>{"use strict";var JE=oa(),UE={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),JE.stringifyString(e,t,r,i)}};xm.string=UE});var ys=R(Pm=>{"use strict";var Cm=de(),Rm={identify:e=>e==null,createNode:()=>new Cm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Cm.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Rm.test.test(e)?e:t.options.nullStr};Pm.nullTag=Rm});var du=R(Am=>{"use strict";var KE=de(),_m={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new KE.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&_m.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Am.boolTag=_m});var Wi=R(Im=>{"use strict";function YE({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}Im.stringifyNumber=YE});var fu=R(Ns=>{"use strict";var XE=de(),pu=Wi(),QE={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:pu.stringifyNumber},ZE={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():pu.stringifyNumber(e)}},ex={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 XE.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:pu.stringifyNumber};Ns.float=ex;Ns.floatExp=ZE;Ns.floatNaN=QE});var mu=R(ks=>{"use strict";var Tm=Wi(),bs=e=>typeof e=="bigint"||Number.isInteger(e),hu=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function jm(e,t,r){let{value:i}=e;return bs(i)&&i>=0?r+i.toString(t):Tm.stringifyNumber(e)}var tx={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>hu(e,2,8,r),stringify:e=>jm(e,8,"0o")},rx={identify:bs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>hu(e,0,10,r),stringify:Tm.stringifyNumber},ix={identify:e=>bs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>hu(e,2,16,r),stringify:e=>jm(e,16,"0x")};ks.int=rx;ks.intHex=ix;ks.intOct=tx});var Om=R($m=>{"use strict";var nx=Mi(),ax=ys(),ox=Vi(),sx=ua(),cx=du(),vu=fu(),gu=mu(),lx=[nx.map,ox.seq,sx.string,ax.nullTag,cx.boolTag,gu.intOct,gu.int,gu.intHex,vu.floatNaN,vu.floatExp,vu.float];$m.schema=lx});var Bm=R(Dm=>{"use strict";var ux=de(),dx=Mi(),px=Vi();function Hm(e){return typeof e=="bigint"||Number.isInteger(e)}var Ss=({value:e})=>JSON.stringify(e),fx=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ss},{identify:e=>e==null,createNode:()=>new ux.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ss},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ss},{identify:Hm,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})=>Hm(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:Ss}],hx={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},mx=[dx.map,px.seq].concat(fx,hx);Dm.schema=mx});var yu=R(Fm=>{"use strict";var da=zo("buffer"),wu=de(),vx=oa(),gx={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof da.Buffer=="function")return da.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 da.Buffer=="function")s=o instanceof da.Buffer?o.toString("base64"):da.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=wu.Scalar.BLOCK_LITERAL),t!==wu.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===wu.Scalar.BLOCK_LITERAL?`
|
|
56
|
+
`:" ")}return vx.stringifyString({comment:e,type:t,value:s},i,n,a)}};Fm.binary=gx});var Cs=R(xs=>{"use strict";var Es=W(),Nu=Er(),wx=de(),yx=Rr();function Lm(e,t){if(Es.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Es.isPair(i)){if(Es.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Nu.Pair(new wx.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]=Ko.isPair(i)?i:new Ll.Pair(i)}}else t("Expected a sequence for this tag");return e}function Fh(e,t,r){let{replacer:i}=r,n=new US.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(Ll.createPair(s,c,r))}return n}var KS={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qh,createNode:Fh};Yo.createPairs=Fh;Yo.pairs=KS;Yo.resolvePairs=qh});var Ml=P(Vl=>{"use strict";var Lh=M(),Bl=dr(),Wn=gr(),YS=wr(),Bh=Xo(),Qr=class e extends YS.YAMLSeq{constructor(){super(),this.add=Wn.YAMLMap.prototype.add.bind(this),this.delete=Wn.YAMLMap.prototype.delete.bind(this),this.get=Wn.YAMLMap.prototype.get.bind(this),this.has=Wn.YAMLMap.prototype.has.bind(this),this.set=Wn.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(Lh.isPair(n)?(a=Bl.toJS(n.key,"",r),o=Bl.toJS(n.value,a,r)):a=Bl.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=Bh.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Qr.tag="tag:yaml.org,2002:omap";var XS={collection:"seq",identify:e=>e instanceof Map,nodeClass:Qr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Bh.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Lh.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Qr,r)},createNode:(e,t,r)=>Qr.from(e,t,r)};Vl.YAMLOMap=Qr;Vl.omap=XS});var Jh=P(Wl=>{"use strict";var Vh=le();function Mh({value:e,source:t},r){return t&&(e?Wh:zh).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Wh={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 Vh.Scalar(!0),stringify:Mh},zh={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 Vh.Scalar(!1),stringify:Mh};Wl.falseTag=zh;Wl.trueTag=Wh});var Gh=P(Qo=>{"use strict";var QS=le(),zl=Ai(),ZS={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:zl.stringifyNumber},eE={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():zl.stringifyNumber(e)}},tE={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 QS.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:zl.stringifyNumber};Qo.float=tE;Qo.floatExp=eE;Qo.floatNaN=ZS});var Kh=P(Jn=>{"use strict";var Uh=Ai(),zn=e=>typeof e=="bigint"||Number.isInteger(e);function Zo(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 Jl(e,t,r){let{value:i}=e;if(zn(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Uh.stringifyNumber(e)}var rE={identify:zn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Zo(e,2,2,r),stringify:e=>Jl(e,2,"0b")},iE={identify:zn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Zo(e,1,8,r),stringify:e=>Jl(e,8,"0")},nE={identify:zn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Zo(e,0,10,r),stringify:Uh.stringifyNumber},aE={identify:zn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Zo(e,2,16,r),stringify:e=>Jl(e,16,"0x")};Jn.int=nE;Jn.intBin=rE;Jn.intHex=aE;Jn.intOct=iE});var Ul=P(Gl=>{"use strict";var rs=M(),es=mr(),ts=gr(),Zr=class e extends ts.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;rs.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new es.Pair(t.key,null):r=new es.Pair(t,null),ts.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=ts.findPair(this.items,t);return!r&&rs.isPair(i)?rs.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=ts.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new es.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(es.createPair(o,null,i));return a}};Zr.tag="tag:yaml.org,2002:set";var oE={collection:"map",identify:e=>e instanceof Set,nodeClass:Zr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Zr.from(e,t,r),resolve(e,t){if(rs.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Zr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Gl.YAMLSet=Zr;Gl.set=oE});var Yl=P(is=>{"use strict";var sE=Ai();function Kl(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 Yh(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return sE.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 cE={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})=>Kl(e,r),stringify:Yh},lE={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=>Kl(e,!1),stringify:Yh},Xh={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(Xh.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=Kl(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$/,"")??""};is.floatTime=lE;is.intTime=cE;is.timestamp=Xh});var em=P(Zh=>{"use strict";var uE=Ri(),dE=Wo(),fE=_i(),pE=Vn(),hE=Fl(),Qh=Jh(),Xl=Gh(),ns=Kh(),mE=Ho(),vE=Ml(),gE=Xo(),wE=Ul(),Ql=Yl(),yE=[uE.map,fE.seq,pE.string,dE.nullTag,Qh.trueTag,Qh.falseTag,ns.intBin,ns.intOct,ns.int,ns.intHex,Xl.floatNaN,Xl.floatExp,Xl.float,hE.binary,mE.merge,vE.omap,gE.pairs,wE.set,Ql.intTime,Ql.floatTime,Ql.timestamp];Zh.schema=yE});var um=P(tu=>{"use strict";var nm=Ri(),NE=Wo(),am=_i(),bE=Vn(),kE=Il(),Zl=Tl(),eu=Ol(),SE=Th(),EE=Hh(),om=Fl(),Gn=Ho(),sm=Ml(),cm=Xo(),tm=em(),lm=Ul(),as=Yl(),rm=new Map([["core",SE.schema],["failsafe",[nm.map,am.seq,bE.string]],["json",EE.schema],["yaml11",tm.schema],["yaml-1.1",tm.schema]]),im={binary:om.binary,bool:kE.boolTag,float:Zl.float,floatExp:Zl.floatExp,floatNaN:Zl.floatNaN,floatTime:as.floatTime,int:eu.int,intHex:eu.intHex,intOct:eu.intOct,intTime:as.intTime,map:nm.map,merge:Gn.merge,null:NE.nullTag,omap:sm.omap,pairs:cm.pairs,seq:am.seq,set:lm.set,timestamp:as.timestamp},xE={"tag:yaml.org,2002:binary":om.binary,"tag:yaml.org,2002:merge":Gn.merge,"tag:yaml.org,2002:omap":sm.omap,"tag:yaml.org,2002:pairs":cm.pairs,"tag:yaml.org,2002:set":lm.set,"tag:yaml.org,2002:timestamp":as.timestamp};function CE(e,t,r){let i=rm.get(t);if(i&&!e)return r&&!i.includes(Gn.merge)?i.concat(Gn.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(rm.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(Gn.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?im[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(im).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},[])}tu.coreKnownTags=xE;tu.getTags=CE});var nu=P(dm=>{"use strict";var ru=M(),PE=Ri(),RE=_i(),_E=Vn(),os=um(),AE=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,iu=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?os.getTags(t,"compat"):t?os.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?os.coreKnownTags:{},this.tags=os.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,ru.MAP,{value:PE.map}),Object.defineProperty(this,ru.SCALAR,{value:_E.string}),Object.defineProperty(this,ru.SEQ,{value:RE.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?AE:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};dm.Schema=iu});var pm=P(fm=>{"use strict";var IE=M(),au=Fn(),Un=On();function jE(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=au.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Un.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(IE.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Un.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=au.stringify(e.contents,n,()=>s=null,c);s&&(l+=Un.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(au.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]=Es.isPair(i)?i:new Nu.Pair(i)}}else t("Expected a sequence for this tag");return e}function qm(e,t,r){let{replacer:i}=r,n=new yx.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(Nu.createPair(s,c,r))}return n}var Nx={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Lm,createNode:qm};xs.createPairs=qm;xs.pairs=Nx;xs.resolvePairs=Lm});var Su=R(ku=>{"use strict";var Mm=W(),bu=Nr(),pa=Cr(),bx=Rr(),Vm=Cs(),ci=class e extends bx.YAMLSeq{constructor(){super(),this.add=pa.YAMLMap.prototype.add.bind(this),this.delete=pa.YAMLMap.prototype.delete.bind(this),this.get=pa.YAMLMap.prototype.get.bind(this),this.has=pa.YAMLMap.prototype.has.bind(this),this.set=pa.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(Mm.isPair(n)?(a=bu.toJS(n.key,"",r),o=bu.toJS(n.value,a,r)):a=bu.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=Vm.createPairs(t,r,i),a=new this;return a.items=n.items,a}};ci.tag="tag:yaml.org,2002:omap";var kx={collection:"seq",identify:e=>e instanceof Map,nodeClass:ci,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Vm.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Mm.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new ci,r)},createNode:(e,t,r)=>ci.from(e,t,r)};ku.YAMLOMap=ci;ku.omap=kx});var Um=R(Eu=>{"use strict";var Wm=de();function zm({value:e,source:t},r){return t&&(e?Gm:Jm).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Gm={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 Wm.Scalar(!0),stringify:zm},Jm={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 Wm.Scalar(!1),stringify:zm};Eu.falseTag=Jm;Eu.trueTag=Gm});var Km=R(Rs=>{"use strict";var Sx=de(),xu=Wi(),Ex={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:xu.stringifyNumber},xx={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():xu.stringifyNumber(e)}},Cx={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 Sx.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:xu.stringifyNumber};Rs.float=Cx;Rs.floatExp=xx;Rs.floatNaN=Ex});var Xm=R(ha=>{"use strict";var Ym=Wi(),fa=e=>typeof e=="bigint"||Number.isInteger(e);function Ps(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 Cu(e,t,r){let{value:i}=e;if(fa(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Ym.stringifyNumber(e)}var Rx={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Ps(e,2,2,r),stringify:e=>Cu(e,2,"0b")},Px={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Ps(e,1,8,r),stringify:e=>Cu(e,8,"0")},_x={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Ps(e,0,10,r),stringify:Ym.stringifyNumber},Ax={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Ps(e,2,16,r),stringify:e=>Cu(e,16,"0x")};ha.int=_x;ha.intBin=Rx;ha.intHex=Ax;ha.intOct=Px});var Pu=R(Ru=>{"use strict";var Is=W(),_s=Er(),As=Cr(),li=class e extends As.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Is.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new _s.Pair(t.key,null):r=new _s.Pair(t,null),As.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=As.findPair(this.items,t);return!r&&Is.isPair(i)?Is.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=As.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new _s.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(_s.createPair(o,null,i));return a}};li.tag="tag:yaml.org,2002:set";var Ix={collection:"map",identify:e=>e instanceof Set,nodeClass:li,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>li.from(e,t,r),resolve(e,t){if(Is.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new li,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ru.YAMLSet=li;Ru.set=Ix});var Au=R(Ts=>{"use strict";var Tx=Wi();function _u(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 Qm(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Tx.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 jx={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})=>_u(e,r),stringify:Qm},$x={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=>_u(e,!1),stringify:Qm},Zm={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(Zm.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=_u(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$/,"")??""};Ts.floatTime=$x;Ts.intTime=jx;Ts.timestamp=Zm});var rv=R(tv=>{"use strict";var Ox=Mi(),Hx=ys(),Dx=Vi(),Bx=ua(),Fx=yu(),ev=Um(),Iu=Km(),js=Xm(),Lx=ds(),qx=Su(),Mx=Cs(),Vx=Pu(),Tu=Au(),Wx=[Ox.map,Dx.seq,Bx.string,Hx.nullTag,ev.trueTag,ev.falseTag,js.intBin,js.intOct,js.int,js.intHex,Iu.floatNaN,Iu.floatExp,Iu.float,Fx.binary,Lx.merge,qx.omap,Mx.pairs,Vx.set,Tu.intTime,Tu.floatTime,Tu.timestamp];tv.schema=Wx});var pv=R(Ou=>{"use strict";var ov=Mi(),zx=ys(),sv=Vi(),Gx=ua(),Jx=du(),ju=fu(),$u=mu(),Ux=Om(),Kx=Bm(),cv=yu(),ma=ds(),lv=Su(),uv=Cs(),iv=rv(),dv=Pu(),$s=Au(),nv=new Map([["core",Ux.schema],["failsafe",[ov.map,sv.seq,Gx.string]],["json",Kx.schema],["yaml11",iv.schema],["yaml-1.1",iv.schema]]),av={binary:cv.binary,bool:Jx.boolTag,float:ju.float,floatExp:ju.floatExp,floatNaN:ju.floatNaN,floatTime:$s.floatTime,int:$u.int,intHex:$u.intHex,intOct:$u.intOct,intTime:$s.intTime,map:ov.map,merge:ma.merge,null:zx.nullTag,omap:lv.omap,pairs:uv.pairs,seq:sv.seq,set:dv.set,timestamp:$s.timestamp},Yx={"tag:yaml.org,2002:binary":cv.binary,"tag:yaml.org,2002:merge":ma.merge,"tag:yaml.org,2002:omap":lv.omap,"tag:yaml.org,2002:pairs":uv.pairs,"tag:yaml.org,2002:set":dv.set,"tag:yaml.org,2002:timestamp":$s.timestamp};function Xx(e,t,r){let i=nv.get(t);if(i&&!e)return r&&!i.includes(ma.merge)?i.concat(ma.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(nv.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(ma.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?av[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(av).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},[])}Ou.coreKnownTags=Yx;Ou.getTags=Xx});var Bu=R(fv=>{"use strict";var Hu=W(),Qx=Mi(),Zx=Vi(),eC=ua(),Os=pv(),tC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Du=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Os.getTags(t,"compat"):t?Os.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Os.coreKnownTags:{},this.tags=Os.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Hu.MAP,{value:Qx.map}),Object.defineProperty(this,Hu.SCALAR,{value:eC.string}),Object.defineProperty(this,Hu.SEQ,{value:Zx.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?tC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};fv.Schema=Du});var mv=R(hv=>{"use strict";var rC=W(),Fu=sa(),va=ia();function iC(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=Fu.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(va.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(rC.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(va.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Fu.stringify(e.contents,n,()=>s=null,c);s&&(l+=va.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Fu.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
59
|
+
`)?(r.push("..."),r.push(va.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(va.indentComment(a(c),"")))}return r.join(`
|
|
60
60
|
`)+`
|
|
61
|
-
`}
|
|
61
|
+
`}hv.stringifyDocument=iC});var ga=R(vv=>{"use strict";var nC=ta(),zi=ts(),Xe=W(),aC=Er(),oC=Nr(),sC=Bu(),cC=mv(),Lu=Xo(),lC=Wl(),uC=ra(),qu=Vl(),Mu=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Xe.NODE_TYPE,{value:Xe.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 qu.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,{[Xe.NODE_TYPE]:{value:Xe.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=Xe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Gi(this.contents)&&this.contents.add(t)}addIn(t,r){Gi(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Lu.anchorNames(this);t.anchor=!r||i.has(r)?Lu.findNewAnchor(r||"a",i):r}return new nC.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}=Lu.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},h=uC.createNode(t,u,m);return s&&Xe.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 aC.Pair(n,a)}delete(t){return Gi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Gi(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Xe.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return zi.isEmptyPath(t)?!r&&Xe.isScalar(this.contents)?this.contents.value:this.contents:Xe.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Xe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zi.isEmptyPath(t)?this.contents!==void 0:Xe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=zi.collectionFromPath(this.schema,[t],r):Gi(this.contents)&&this.contents.set(t,r)}setIn(t,r){zi.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=zi.collectionFromPath(this.schema,Array.from(t),r):Gi(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 qu.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 qu.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 sC.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=oC.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"?lC.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 cC.stringifyDocument(this,t)}};function Gi(e){if(Xe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}vv.Document=Mu});var Na=R(ya=>{"use strict";var wa=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Vu=class extends wa{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Wu=class extends wa{constructor(t,r,i){super("YAMLWarning",t,r,i)}},dC=(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
|
+
`}};ya.YAMLError=wa;ya.YAMLParseError=Vu;ya.YAMLWarning=Wu;ya.prettifyError=dC});var ba=R(gv=>{"use strict";function pC(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}}gv.resolveProps=pC});var Hs=R(wv=>{"use strict";function zu(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(zu(t.key)||zu(t.value))return!0}return!1;default:return!0}}wv.containsNewline=zu});var Gu=R(yv=>{"use strict";var fC=Hs();function hC(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&fC.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}yv.flowIndentCheck=hC});var Ju=R(bv=>{"use strict";var Nv=W();function mC(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Nv.isScalar(a)&&Nv.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}bv.mapIncludes=mC});var Rv=R(Cv=>{"use strict";var kv=Er(),vC=Cr(),Sv=ba(),gC=Hs(),Ev=Gu(),wC=Ju(),xv="All mapping items must start at the same column";function yC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??vC.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=Sv.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",xv)),!h.anchor&&!h.tag&&!f){l=h.end,h.comment&&(s.comment?s.comment+=`
|
|
68
|
+
`+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||gC.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",xv);r.atKey=!0;let g=h.end,b=p?e(r,p,h,n):t(r,g,d,null,h,n);r.schema.compat&&Ev.flowIndentCheck(i.indent,p,n),r.atKey=!1,wC.mapIncludes(r,s.items,b)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let k=Sv.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&&Ev.flowIndentCheck(i.indent,m,n),c=N.range[2];let x=new kv.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 kv.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}Cv.resolveBlockMap=yC});var _v=R(Pv=>{"use strict";var NC=Rr(),bC=ba(),kC=Gu();function SC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??NC.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=bC.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&&kC.flowIndentCheck(i.indent,d,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}Pv.resolveBlockSeq=SC});var Ji=R(Av=>{"use strict";function EC(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}}Av.resolveEnd=EC});var $v=R(jv=>{"use strict";var xC=W(),CC=Er(),Iv=Cr(),RC=Rr(),PC=Ji(),Tv=ba(),_C=Hs(),AC=Ju(),Uu="Block collections are not allowed within flow collections",Ku=e=>e&&(e.type==="block-map"||e.type==="block-seq");function IC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Iv.YAMLMap:RC.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=Tv.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&&_C.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];xC.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],Ku(x)&&n(S.range,"BLOCK_IN_FLOW",Uu)}else{r.atKey=!0;let S=w.end,E=k?e(r,k,w,n):t(r,S,b,null,w,n);Ku(k)&&n(E.range,"BLOCK_IN_FLOW",Uu),r.atKey=!1;let y=Tv.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 j of N){if(j===y.found)break;if(j.type==="newline"){n(j,"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?Ku(x)&&n(C.range,"BLOCK_IN_FLOW",Uu):y.comment&&(E.comment?E.comment+=`
|
|
72
|
+
`+y.comment:E.comment=y.comment);let O=new CC.Pair(E,C);if(r.options.keepSourceTokens&&(O.srcToken=g),o){let j=l;AC.mapIncludes(r,j.items,E)&&n(S,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(O)}else{let j=new Iv.YAMLMap(r.schema);j.flow=!0,j.items.push(O);let Q=(C??E).range;j.range=[E.range[0],Q[1],Q[2]],l.items.push(j)}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=PC.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}jv.resolveFlowCollection=IC});var Hv=R(Ov=>{"use strict";var TC=W(),jC=de(),$C=Cr(),OC=Rr(),HC=Rv(),DC=_v(),BC=$v();function Yu(e,t,r,i,n,a){let o=r.type==="block-map"?HC.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?DC.resolveBlockSeq(e,t,r,i,a):BC.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 FC(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===$C.YAMLMap.tagName&&s==="map"||o===OC.YAMLSeq.tagName&&s==="seq")return Yu(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),Yu(e,t,r,n,o)}let l=Yu(e,t,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),t.options)??l,d=TC.isNode(u)?u:new jC.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Ov.composeCollection=FC});var Qu=R(Dv=>{"use strict";var Xu=de();function LC(e,t,r){let i=t.offset,n=qC(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Xu.Scalar.BLOCK_FOLDED:Xu.Scalar.BLOCK_LITERAL,o=t.source?MC(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===Xu.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 qC({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 MC(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}Dv.resolveBlockScalar=LC});var ed=R(Fv=>{"use strict";var Zu=de(),VC=Ji();function WC(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=Zu.Scalar.PLAIN,c=zC(a,l);break;case"single-quoted-scalar":s=Zu.Scalar.QUOTE_SINGLE,c=GC(a,l);break;case"double-quoted-scalar":s=Zu.Scalar.QUOTE_DOUBLE,c=JC(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=VC.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function zC(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}`),Bv(e)}function GC(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Bv(e.slice(1,-1)).replace(/''/g,"'")}function Bv(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 JC(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}=UC(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=KC[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+=YC(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 UC(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 KC={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
103
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function YC(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}}Fv.resolveFlowScalar=WC});var Mv=R(qv=>{"use strict";var ui=W(),Lv=de(),XC=Qu(),QC=ed();function ZC(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?XC.resolveBlockScalar(e,t,i):QC.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[ui.SCALAR]:c?l=eR(e.schema,n,c,r,i):t.type==="scalar"?l=tR(e,n,t,i):l=e.schema[ui.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??t,"TAG_RESOLVE_FAILED",p),e.options);u=ui.isScalar(d)?d:new Lv.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",p),u=new Lv.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 eR(e,t,r,i,n){if(r==="!")return e[ui.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[ui.SCALAR])}function tR({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[ui.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[ui.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}qv.composeScalar=ZC});var Wv=R(Vv=>{"use strict";function rR(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}Vv.emptyScalarPosition=rR});var Jv=R(rd=>{"use strict";var iR=ta(),nR=W(),aR=Hv(),zv=Mv(),oR=Ji(),sR=Wv(),cR={composeNode:Gv,composeEmptyNode:td};function Gv(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=lR(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=zv.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=aR.composeCollection(cR,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=td(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&&(!nR.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 td(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:sR.emptyScalarPosition(t,r,i),indent:-1,source:""},d=zv.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 lR({options:e},{offset:t,source:r,end:i},n){let a=new iR.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=oR.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}rd.composeEmptyNode=td;rd.composeNode=Gv});var Yv=R(Kv=>{"use strict";var uR=ga(),Uv=Jv(),dR=Ji(),pR=ba();function fR(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new uR.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=pR.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?Uv.composeNode(l,n,u,o):Uv.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=dR.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}Kv.composeDoc=fR});var nd=R(Zv=>{"use strict";var hR=zo("process"),mR=Vl(),vR=ga(),ka=Na(),Xv=W(),gR=Yv(),wR=Ji();function Sa(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 Qv(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 id=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Sa(r);a?this.warnings.push(new ka.YAMLWarning(o,i,n)):this.errors.push(new ka.YAMLParseError(o,i,n))},this.directives=new mR.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Qv(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(Xv.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Xv.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:Qv(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(hR.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Sa(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=gR.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 ka.YAMLParseError(Sa(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 ka.YAMLParseError(Sa(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=wR.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 ka.YAMLParseError(Sa(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 vR.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}}};Zv.Composer=id});var rg=R(Ds=>{"use strict";var yR=Qu(),NR=ed(),bR=Na(),eg=oa();function kR(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 bR.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return NR.resolveFlowScalar(e,t,i);case"block-scalar":return yR.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function SR(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=eg.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 tg(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 ER(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=eg.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">":xR(e,c);break;case'"':ad(e,c,"double-quoted-scalar");break;case"'":ad(e,c,"single-quoted-scalar");break;default:ad(e,c,"scalar")}}function xR(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}];tg(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 tg(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 ad(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})}}}Ds.createScalarToken=SR;Ds.resolveAsScalar=kR;Ds.setScalarValue=ER});var ng=R(ig=>{"use strict";var CR=e=>"type"in e?Fs(e):Bs(e);function Fs(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Fs(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Bs(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Bs(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Bs(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 Bs({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Fs(t)),r)for(let a of r)n+=a.source;return i&&(n+=Fs(i)),n}ig.stringify=CR});var cg=R(sg=>{"use strict";var od=Symbol("break visit"),RR=Symbol("skip children"),ag=Symbol("remove item");function di(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),og(Object.freeze([]),e,t)}di.BREAK=od;di.SKIP=RR;di.REMOVE=ag;di.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};di.parentCollection=(e,t)=>{let r=di.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 og(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=og(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===od)return od;s===ag&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}sg.visit=di});var Ls=R(Fe=>{"use strict";var sd=rg(),PR=ng(),_R=cg(),cd="\uFEFF",ld="",ud="",dd="",AR=e=>!!e&&"items"in e,IR=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function TR(e){switch(e){case cd:return"<BOM>";case ld:return"<DOC>";case ud:return"<FLOW_END>";case dd:return"<SCALAR>";default:return JSON.stringify(e)}}function jR(e){switch(e){case cd:return"byte-order-mark";case ld:return"doc-mode";case ud:return"flow-error-end";case dd: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}Fe.createScalarToken=sd.createScalarToken;Fe.resolveAsScalar=sd.resolveAsScalar;Fe.setScalarValue=sd.setScalarValue;Fe.stringify=PR.stringify;Fe.visit=_R.visit;Fe.BOM=cd;Fe.DOCUMENT=ld;Fe.FLOW_END=ud;Fe.SCALAR=dd;Fe.isCollection=AR;Fe.isScalar=IR;Fe.prettyToken=TR;Fe.tokenType=jR});var hd=R(ug=>{"use strict";var Ea=Ls();function ft(e){switch(e){case void 0:case" ":case`
|
|
121
|
+
`:case"\r":case" ":return!0;default:return!1}}var lg=new Set("0123456789ABCDEFabcdef"),$R=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qs=new Set(",[]{}"),OR=new Set(` ,[]{}
|
|
122
|
+
\r `),pd=e=>!e||OR.has(e),fd=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==="...")&&ft(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]===Ea.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 Ea.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==="...")&&ft(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&&!ft(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===":")&&ft(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(pd),"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("..."))&&ft(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Ea.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(pd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ft(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=>ft(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 Ea.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(ft(a)||t&&qs.has(a))break;r=i}else if(ft(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&&qs.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&&qs.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Ea.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(pd),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ft(i)||r&&qs.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(;!ft(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($R.has(r))r=this.buffer[++t];else if(r==="%"&&lg.has(this.buffer[t+1])&&lg.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)}};ug.Lexer=fd});var vd=R(dg=>{"use strict";var md=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}}}};dg.LineCounter=md});var wd=R(vg=>{"use strict";var HR=zo("process"),pg=Ls(),DR=hd();function Pr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function fg(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 mg(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 Ms(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 Ui(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 Vs(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 hg(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Pr(t.start,"explicit-key-ind")&&!Pr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,mg(t.value)?t.value.end?Vs(t.value.end,t.sep):t.value.end=t.sep:Vs(t.start,t.sep),delete t.sep)}var gd=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 DR.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,HR.env.LOG_TOKENS&&console.log("|",pg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=pg.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"&&hg(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&&fg(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":{fg(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=Ms(this.peek(2)),i=Ui(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)){Vs(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(Pr(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(mg(r.key)&&!Pr(r.sep,"newline")){let o=Ui(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(Pr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ui(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]}):Pr(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&&!Pr(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)){Vs(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||Pr(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=Ms(i),a=Ui(n);hg(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=ps(t),i=$i(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=ps(t),i=$i(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())}}};hv.Parser=Du});var yv=P(na=>{"use strict";var mv=Eu(),pC=Kn(),ia=Qn(),hC=kl(),mC=M(),vC=Hu(),vv=qu();function gv(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new vC.LineCounter||null,prettyErrors:t}}function gC(e,t={}){let{lineCounter:r,prettyErrors:i}=gv(t),n=new vv.Parser(r?.addNewLine),a=new mv.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(ia.prettifyError(e,r)),s.warnings.forEach(ia.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function wv(e,t={}){let{lineCounter:r,prettyErrors:i}=gv(t),n=new vv.Parser(r?.addNewLine),a=new mv.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 ia.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(ia.prettifyError(e,r)),o.warnings.forEach(ia.prettifyError(e,r))),o}function wC(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=wv(e,r);if(!n)return null;if(n.warnings.forEach(a=>hC.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 yC(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 mC.isDocument(e)&&!i?e.toString(r):new pC.Document(e,i,r).toString(r)}na.parse=wC;na.parseAllDocuments=gC;na.parseDocument=wv;na.stringify=yC});var Ct=P(J=>{"use strict";var NC=Eu(),bC=Kn(),kC=nu(),Fu=Qn(),SC=Tn(),Nr=M(),EC=mr(),xC=le(),CC=gr(),PC=wr(),RC=ds(),_C=$u(),AC=Hu(),IC=qu(),ms=yv(),Nv=_n();J.Composer=NC.Composer;J.Document=bC.Document;J.Schema=kC.Schema;J.YAMLError=Fu.YAMLError;J.YAMLParseError=Fu.YAMLParseError;J.YAMLWarning=Fu.YAMLWarning;J.Alias=SC.Alias;J.isAlias=Nr.isAlias;J.isCollection=Nr.isCollection;J.isDocument=Nr.isDocument;J.isMap=Nr.isMap;J.isNode=Nr.isNode;J.isPair=Nr.isPair;J.isScalar=Nr.isScalar;J.isSeq=Nr.isSeq;J.Pair=EC.Pair;J.Scalar=xC.Scalar;J.YAMLMap=CC.YAMLMap;J.YAMLSeq=PC.YAMLSeq;J.CST=RC;J.Lexer=_C.Lexer;J.LineCounter=AC.LineCounter;J.Parser=IC.Parser;J.parse=ms.parse;J.parseAllDocuments=ms.parseAllDocuments;J.parseDocument=ms.parseDocument;J.stringify=ms.stringify;J.visit=Nv.visit;J.visitAsync=Nv.visitAsync});import Lu from"path";function $C(e){return e.toLowerCase().startsWith(".env")}function Pt(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>$C(i))?"environment-file":r.some(i=>TC.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>jC.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function Bu(e,t){let r=Pt(t);if(r)return r;let i=Lu.resolve(e.projectRoot,...t.split("/")),n=Lu.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===Lu.resolve(e.configFile)?"native-runtime":null}var jC,TC,aa=I(()=>{"use strict";jC=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),TC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function br(e){return e!==0&&e!==0n&&e!=="0"}function Ke(e,t){return br(e.dev)&&br(t.dev)&&br(e.ino)&&br(t.ino)}function z(e,t){let r=br(e.dev)&&br(t.dev);if(r&&e.dev!==t.dev)return!1;let i=br(e.ino)&&br(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var oa=I(()=>{"use strict"});var Rt=I(()=>{"use strict";oa()});import{createHash as OC}from"node:crypto";import{promises as lt}from"node:fs";import Ye from"node:path";import{TextDecoder as HC}from"node:util";function Vu(e,t){let r=Ye.relative(e,t);return r===""||!Ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ye.sep}`)}function DC(e){let t=Ye.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})||Ye.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=Pt(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 qC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function FC(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vs(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bv(e){let t=await lt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await lt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function LC(e,t){let r=Ye.resolve(e),i=Ye.resolve(t);if(!Vu(r,i))throw new Error("Native artifact path is outside its root");let n=[await bv(r)],a=r;for(let o of Ye.relative(r,i).split(Ye.sep).filter(Boolean)){a=Ye.join(a,o);let s=await bv(a);if(!Vu(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function kv(e){for(let t of e){let r=await lt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!FC(t,r)||await lt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=DC(e.ref),r=e.maxBytes===null?null:qC(e.maxBytes??Mu),i=Ye.resolve(e.root,...t.split("/")),n=await LC(e.root,Ye.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await lt.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 lt.realpath(i);if(!Vu(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await lt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),lt.lstat(i),lt.realpath(i)]);if(await kv(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!vs(a,c)||!vs(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(),lt.lstat(i),lt.realpath(i)]);if(await kv(n),!h.isFile()||h.isSymbolicLink()||v!==o||!vs(c,m)||!vs(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),b;try{b=new HC("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:OC("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var Mu,Xe=I(()=>{"use strict";aa();Rt();Mu=1024*1024});import{promises as zu}from"node:fs";async function Ju(e,t){let r;for(let i=0;i<=Wu.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Wu.length||!BC.has(a??""))throw n;await new Promise(o=>setTimeout(o,Wu[i]))}throw r}async function Gu(e,t){await Ju(()=>zu.rename(e,t),`rename ${t}`)}async function Uu(e){await Ju(()=>zu.unlink(e),`unlink ${e}`)}async function Ku(e,t){await Ju(()=>zu.link(e,t),`link ${t}`)}var BC,Wu,Yu=I(()=>{"use strict";BC=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Wu=[50,100,200]});import{randomUUID as VC}from"crypto";import{promises as Ce}from"fs";import ut from"path";function gs(e,t){let r=ut.relative(e,t);return r===""||!ut.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ut.sep}`)}function MC(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ws(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function WC(e,t){return ws(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Sv(e){let t=await Ce.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 Ce.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Oi(e){for(let t of e){let r=await Ce.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!MC(t,r)||await Ce.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function zC(e,t,r){let[i,n]=await Promise.all([Ce.lstat(e),Ce.realpath(e),r?Oi(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!ws(i,t)||r&&!gs(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function JC(e,t){let r=ut.resolve(e),i=ut.resolve(t);if(!gs(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Sv(r)],a=ut.relative(r,i).split(ut.sep).filter(Boolean),o=r;for(let s of a){await Oi(n),o=ut.join(o,s);try{await Ce.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Sv(o);if(!gs(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Oi(n),n}async function GC(e){let t;try{t=await Ce.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 UC(e,t,r={}){let i=ut.dirname(e),n=r.containedRoot?await JC(r.containedRoot,i):null;n||await Ce.mkdir(i,{recursive:!0});let a=ut.join(i,`.${ut.basename(e)}.${VC()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Ce.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Ce.lstat(a),Ce.realpath(a)]);if(await Oi(n),!l.isFile()||l.isSymbolicLink()||!ws(s,l)||!gs(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(),!ws(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 zC(a,c,n),await r.beforeCommit?.(),n){await Oi(n);let l=await Ce.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!WC(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await Ku(a,e),await Uu(a)):await Gu(a,e),await GC(i)}catch(l){if(await o?.close(),!n)await Ce.rm(a,{force:!0});else try{await Oi(n),await Ce.rm(a,{force:!0})}catch{}throw l}}async function _t(e,t,r={}){await UC(e,t,r)}async function He(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=Ms(t),i=Ui(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=Ms(t),i=Ui(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())}}};vg.Parser=gd});var bg=R(Ca=>{"use strict";var gg=nd(),BR=ga(),xa=Na(),FR=ru(),LR=W(),qR=vd(),wg=wd();function yg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new qR.LineCounter||null,prettyErrors:t}}function MR(e,t={}){let{lineCounter:r,prettyErrors:i}=yg(t),n=new wg.Parser(r?.addNewLine),a=new gg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(xa.prettifyError(e,r)),s.warnings.forEach(xa.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Ng(e,t={}){let{lineCounter:r,prettyErrors:i}=yg(t),n=new wg.Parser(r?.addNewLine),a=new gg.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 xa.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(xa.prettifyError(e,r)),o.warnings.forEach(xa.prettifyError(e,r))),o}function VR(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Ng(e,r);if(!n)return null;if(n.warnings.forEach(a=>FR.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 WR(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 LR.isDocument(e)&&!i?e.toString(r):new BR.Document(e,i,r).toString(r)}Ca.parse=VR;Ca.parseAllDocuments=MR;Ca.parseDocument=Ng;Ca.stringify=WR});var It=R(J=>{"use strict";var zR=nd(),GR=ga(),JR=Bu(),yd=Na(),UR=ta(),_r=W(),KR=Er(),YR=de(),XR=Cr(),QR=Rr(),ZR=Ls(),eP=hd(),tP=vd(),rP=wd(),Ws=bg(),kg=Xn();J.Composer=zR.Composer;J.Document=GR.Document;J.Schema=JR.Schema;J.YAMLError=yd.YAMLError;J.YAMLParseError=yd.YAMLParseError;J.YAMLWarning=yd.YAMLWarning;J.Alias=UR.Alias;J.isAlias=_r.isAlias;J.isCollection=_r.isCollection;J.isDocument=_r.isDocument;J.isMap=_r.isMap;J.isNode=_r.isNode;J.isPair=_r.isPair;J.isScalar=_r.isScalar;J.isSeq=_r.isSeq;J.Pair=KR.Pair;J.Scalar=YR.Scalar;J.YAMLMap=XR.YAMLMap;J.YAMLSeq=QR.YAMLSeq;J.CST=ZR;J.Lexer=eP.Lexer;J.LineCounter=tP.LineCounter;J.Parser=rP.Parser;J.parse=Ws.parse;J.parseAllDocuments=Ws.parseAllDocuments;J.parseDocument=Ws.parseDocument;J.stringify=Ws.stringify;J.visit=kg.visit;J.visitAsync=kg.visitAsync});import Nd from"path";function aP(e){return e.toLowerCase().startsWith(".env")}function Tt(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>aP(i))?"environment-file":r.some(i=>nP.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>iP.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function bd(e,t){let r=Tt(t);if(r)return r;let i=Nd.resolve(e.projectRoot,...t.split("/")),n=Nd.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===Nd.resolve(e.configFile)?"native-runtime":null}var iP,nP,Ra=I(()=>{"use strict";iP=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),nP=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Ar(e){return e!==0&&e!==0n&&e!=="0"}function Qe(e,t){return Ar(e.dev)&&Ar(t.dev)&&Ar(e.ino)&&Ar(t.ino)}function G(e,t){let r=Ar(e.dev)&&Ar(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Ar(e.ino)&&Ar(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Pa=I(()=>{"use strict"});var jt=I(()=>{"use strict";Pa()});import{createHash as oP}from"node:crypto";import{promises as ht}from"node:fs";import Ze from"node:path";import{TextDecoder as sP}from"node:util";function kd(e,t){let r=Ze.relative(e,t);return r===""||!Ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ze.sep}`)}function cP(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=Tt(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 lP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function uP(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zs(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Sg(e){let t=await ht.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ht.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function dP(e,t){let r=Ze.resolve(e),i=Ze.resolve(t);if(!kd(r,i))throw new Error("Native artifact path is outside its root");let n=[await Sg(r)],a=r;for(let o of Ze.relative(r,i).split(Ze.sep).filter(Boolean)){a=Ze.join(a,o);let s=await Sg(a);if(!kd(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Eg(e){for(let t of e){let r=await ht.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!uP(t,r)||await ht.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ne(e){let t=cP(e.ref),r=e.maxBytes===null?null:lP(e.maxBytes??Sd),i=Ze.resolve(e.root,...t.split("/")),n=await dP(e.root,Ze.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ht.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 ht.realpath(i);if(!kd(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ht.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),ht.lstat(i),ht.realpath(i)]);if(await Eg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!zs(a,c)||!zs(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(),ht.lstat(i),ht.realpath(i)]);if(await Eg(n),!h.isFile()||h.isSymbolicLink()||v!==o||!zs(c,m)||!zs(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),b;try{b=new sP("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:oP("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var Sd,et=I(()=>{"use strict";Ra();jt();Sd=1024*1024});import{promises as xd}from"node:fs";async function Cd(e,t){let r;for(let i=0;i<=Ed.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Ed.length||!pP.has(a??""))throw n;await new Promise(o=>setTimeout(o,Ed[i]))}throw r}async function Rd(e,t){await Cd(()=>xd.rename(e,t),`rename ${t}`)}async function Pd(e){await Cd(()=>xd.unlink(e),`unlink ${e}`)}async function _d(e,t){await Cd(()=>xd.link(e,t),`link ${t}`)}var pP,Ed,Ad=I(()=>{"use strict";pP=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Ed=[50,100,200]});import{randomUUID as fP}from"crypto";import{promises as Ae}from"fs";import mt from"path";function Gs(e,t){let r=mt.relative(e,t);return r===""||!mt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${mt.sep}`)}function hP(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Js(e,t){return G({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function mP(e,t){return Js(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function xg(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 Ki(e){for(let t of e){let r=await Ae.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!hP(t,r)||await Ae.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function vP(e,t,r){let[i,n]=await Promise.all([Ae.lstat(e),Ae.realpath(e),r?Ki(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Js(i,t)||r&&!Gs(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function gP(e,t){let r=mt.resolve(e),i=mt.resolve(t);if(!Gs(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await xg(r)],a=mt.relative(r,i).split(mt.sep).filter(Boolean),o=r;for(let s of a){await Ki(n),o=mt.join(o,s);try{await Ae.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await xg(o);if(!Gs(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ki(n),n}async function wP(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 yP(e,t,r={}){let i=mt.dirname(e),n=r.containedRoot?await gP(r.containedRoot,i):null;n||await Ae.mkdir(i,{recursive:!0});let a=mt.join(i,`.${mt.basename(e)}.${fP()}.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 Ki(n),!l.isFile()||l.isSymbolicLink()||!Js(s,l)||!Gs(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(),!Js(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 vP(a,c,n),await r.beforeCommit?.(),n){await Ki(n);let l=await Ae.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!mP(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await _d(a,e),await Pd(a)):await Rd(a,e),await wP(i)}catch(l){if(await o?.close(),!n)await Ae.rm(a,{force:!0});else try{await Ki(n),await Ae.rm(a,{force:!0})}catch{}throw l}}async function $t(e,t,r={}){await yP(e,t,r)}async function Ie(e,t,r={}){await $t(e,JSON.stringify(t,null,2)+`
|
|
144
|
+
`,r)}var ae=I(()=>{"use strict";Ad();jt()});function kP(e,t){return Id[e][t]}function Us(e){return Cg.get(e.trim().toLocaleLowerCase("en-US"))??null}function Rg(e){return Td.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ks(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${kP(e,i)}
|
|
145
145
|
`).join(`
|
|
146
|
-
`)}var Xu,KC,YC,Ev,Qu,ri=I(()=>{"use strict";Xu={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:"验证预期"}},KC={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:"结论"}},YC={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:"结论"}},Ev=new Map,Qu=new Map;for(let e of Object.keys(Xu)){for(let[t,r]of Object.entries(Xu[e]))Ev.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(KC[e]))Qu.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(YC[e]))Qu.set(r.toLocaleLowerCase("en-US"),t)}});import kr from"path";function iP(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||kr.posix.isAbsolute(r)||kr.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 Hi(e){let t=iP(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Tv(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 Ss(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||kr.posix.isAbsolute(i)||kr.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 zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function $v(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 Es(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>bs)throw new Error(`${t} exceeds ${bs} 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>ks)throw new Error(`${t} contains more than ${ks} wildcard tokens`);return e}function Av(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=>Es(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function sa(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 Iv(e,t,r){let i=sa(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 nP(e){if(e===void 0)return{...Qe,include:[...Qe.include],exclude:[...Qe.exclude]};let t=zt(e,"native.snapshot");return{include:Av(t.include,"native.snapshot.include",Qe.include),exclude:Av(t.exclude,"native.snapshot.exclude",Qe.exclude),max_files:sa(t.max_files,Qe.max_files,"native.snapshot.max_files"),max_total_bytes:sa(t.max_total_bytes,Qe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:sa(t.max_duration_ms,Qe.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:sa(t.max_selection_records,Qe.max_selection_records,"native.snapshot.max_selection_records")}}function aP(e){if(e===void 0)return;let t=zt(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=zt(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:Hi(i),toArtifactRoot:Hi(n),stage:a,...o?{cleanup:o}:{}}}function oP(e){if(e===void 0)return;let t=zt(e,"native.finish");if(t.pull_request===void 0)return{};let r=zt(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(kr.posix.isAbsolute(i[0])||kr.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??ZC;if(!Number.isSafeInteger(n)||n<1||n>_v)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${_v}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function sP(e,t={}){let r=zt(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??jv;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=aP(r.pending_root_move),l=oP(r.finish);return{artifact_root:Hi(i),language:$v(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:nP(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function cP(e){let t=zt(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:Tv(t.artifact_layout),language:$v(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function lP(e){let r=zt(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)=>Ss(i,`hook.allow_paths[${n}]`)))]}}function uP(e){if(e===void 0)return{...Zu};let t=zt(e,"memory"),r=t.learning??Zu.learning,i=t.retrieval??Zu.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 td(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function dP(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")||kr.posix.isAbsolute(r)||kr.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>Cv)throw new Error(`${t} exceeds ${Cv} 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>Pv)throw new Error(`${t} contains more than ${Pv} wildcard tokens`);return r}function fP(e){let t=td(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)=>dP(n,`knowledge.local.include[${a}]`)))],max_file_mb:Iv(t.max_file_mb,Rv.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Iv(t.max_total_mb,Rv.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 pP(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 hP(e){let t=td(e,"knowledge.remote"),r=pP(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 mP(e){if(e===void 0)return{...QC};let t=td(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:fP(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:hP(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 vP(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function gP(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 la(e,t={}){let r=(0,ed.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=vP(n.ambient_resume),o=n.hook===void 0?void 0:lP(n.hook),s=uP(n.memory),c=mP(n.knowledge),l=n.native===void 0?void 0:sP(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:cP(n.classic),d=gP(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}:{}}}var ed,ca,bs,ks,Cv,Pv,jv,Zu,Rv,QC,ZC,_v,eP,tP,rP,Qe,Sr=I(()=>{"use strict";ed=Bt(Ct(),1),ca=Number.MAX_SAFE_INTEGER,bs=1024,ks=64,Cv=1024,Pv=64,jv=5,Zu={learning:!0,retrieval:!0},Rv={include:[],max_file_mb:1,max_total_mb:32},QC={provider:"local"},ZC=12e4,_v=6e5,eP=[".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/**"],tP=["**/.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"],rP=[...eP,...tP].sort((e,t)=>e.localeCompare(t,"en")),Qe={include:["**/*"],exclude:[...rP],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as xs,promises as ii}from"fs";function rd(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ov(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ua(e){return{dev:e.dev,ino:e.ino,birthtime:rd(e)}}function Cs(e,t){let r=ua(e),i=ua(t);return Ke(r,i)?z(r,i):z(r,i)&&rd(e)===rd(t)&&Ov(e)===Ov(t)&&e.size===t.size}async function Di(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 ii.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new At("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new At("too-large",`${i} exceeds ${t} bytes`);let o=await ii.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ua(a)});let s=process.platform==="win32"?xs.O_RDONLY:xs.O_RDONLY|xs.O_NOFOLLOW|xs.O_NONBLOCK,c;try{c=await ii.open(e,s)}catch(l){throw l.code==="ELOOP"?new At("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),ii.lstat(e,{bigint:n}),ii.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Cs(a,l)||!Cs(a,u))throw new At("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ua(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 At("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}),ii.lstat(e,{bigint:n}),ii.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Cs(a,h)||!Cs(a,v))throw new At("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:ua(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:g}}finally{await c.close()}}var At,da=I(()=>{"use strict";oa();At=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Ps}from"fs";import Er from"path";function wP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function id(e,t){let r=Er.relative(e,t);return r===""||!Er.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Er.sep}`)}async function Hv(e,t){let r=Er.resolve(e),i=await Ps.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ps.realpath(r)}async function Dv(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Er.join(n,r[a]);let o;try{o=await Ps.lstat(n)}catch(u){if(wP(u))return{exists:!1,kind:"missing"};throw u}let s=Er.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 Ps.realpath(n);if(!id(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 qi(e,t,r){let i=Ss(t,r.label),n=Er.resolve(e),a=await Hv(n,r.label),o=i.split("/"),s=Er.resolve(n,...o);if(!id(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Dv(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Jt(e,t,r,i){let n=await qi(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 Hv(n.projectRoot,i.label);return Di(n.target,r,{...i,verify:async(o,s)=>{if(!id(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Dv(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var xr=I(()=>{"use strict";da();Sr()});import{createHash as yP}from"crypto";function NP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Rs(e,t={}){return(await _s(e,t)).document}async function bP(e){try{return(await Jt(e,fa,ca,{label:fa})).bytes}catch(t){if(NP(t))return null;throw t}}function kP(e){return e?{exists:!0,sha256:yP("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function _s(e,t={}){let r=await bP(e);return{document:r?la(r.toString("utf8"),t):null,identity:kP(r)}}async function nd(e){return(await Rs(e))?.config??null}var fa,Fi=I(()=>{"use strict";Sr();xr();fa=".comet/config.yaml"});var Li=I(()=>{"use strict";Yu();oa()});var yD,ad=I(()=>{"use strict";Li();Fi();xr();yD=16*1024});var cd=I(()=>{"use strict";Li();Sr();Fi();xr();ad()});import{existsSync as Fv,promises as Cr}from"fs";import q from"path";import PP from"os";async function ld(e){try{return await Cr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function _P(e){try{let t=await Cr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Vi(e,t){let r=q.relative(e,t);return r===""||!q.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${q.sep}`)}async function Bi(e){let t=[],r=e;for(;!await ld(r);){let n=q.dirname(r);if(n===r)break;t.push(q.basename(r)),r=n}let i=await Cr.realpath(r);return q.resolve(i,...t.reverse())}async function ud(e){try{return(await Cr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function fd(e){let t=q.resolve(e);try{(await Cr.stat(t)).isDirectory()||(t=q.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=q.resolve(PP.homedir());for(;;){if(!(t===i&&r!==i)){let o=q.join(t,...dd.split("/")),s=t===r||await _P(o);if(await ld(o)&&s)return t}if(await ld(q.join(t,".git")))return t;let a=q.dirname(t);if(a===t)return r;t=a}}function pd(e){return Hi(e)}async function AP(e,t){let r=pd(t),i=q.resolve(e,...r.split("/")),n=await Cr.realpath(e),a=await Bi(i);if(!Vi(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Gt(e,t){let r=pd(t),i=await AP(e,r),n=q.join(i,"comet");if(await ud(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Bi(i),Bi(n)]);if(!Vi(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 ud(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Cr.realpath(s),Bi(c)]);if(!Vi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:q.join(e,...dd.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 hd(e){if(!RP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function dt(e,t){hd(t);let r=q.join(e.changesRuntimeDir,t);if(!B(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Bv(e,t){hd(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=dt(e,t);if(Fv(r))return r;let i=Bv(e,t);return Fv(i)?i:r}function ha(e,t){hd(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 Lv(e){try{let t=await Cr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function md(e,t){let r=dt(e,t),i=Bv(e,t),[n,a]=await Promise.all([Lv(r),Lv(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 Pr(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 ve(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 Vi(q.resolve(e),q.resolve(t))}async function U(e,t){let r=q.resolve(e),i=q.resolve(t);if(!Vi(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await ud(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Bi(r),Bi(i)]);if(!Vi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var dd,RP,G=I(()=>{"use strict";Sr();dd=".comet/config.yaml",RP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});async function Pe(e){let t=(await Rs(e))?.config??null;return t?.native?t:null}var vd,As,Me=I(()=>{"use strict";Sr();Fi();cd();ce();G();vd=Qe,As=Es});var LD,Is=I(()=>{"use strict";LD=["$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("; ")});var MD,js=I(()=>{"use strict";Is();MD=8*1024*1024});var Ts=I(()=>{"use strict";js()});import{AsyncLocalStorage as OP}from"async_hooks";var QD,ZD,eq,ma=I(()=>{"use strict";da();Ts();G();Rt();QD=16*1024,ZD=900*1e3,eq=new OP});var zv,gd=I(()=>{"use strict";zv=Bt(Ct(),1)});var Ut,Rr,_r,Mi,Wi,va,ga=I(()=>{"use strict";Ut="comet.native.v3",Rr="comet.native.v2",_r="comet.native.v1",Mi="comet.native.transition.v3",Wi="comet.native.transition.v2",va="comet.native.transition.v1"});import HP from"node:path";function ya(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Kv(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 Ji(e){if(!Uv.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Yv(e){if(!Uv.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Xv(e,t){if(e.length===0||HP.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function WP(e,t){let r=ya(e,`spec_changes[${t}]`);if(Kv(r,FP,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Yv(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"&&Xv(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"||!yd.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"||!yd.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 zP(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 Nd(e,t){if(Kv(e,t,It),typeof e.name!="string")throw new Error("Native change name is required");if(Ji(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"||!LP.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&&!BP.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(WP),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"||!VP.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"&&Xv(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!zP(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 ni(e){let t=ya(e,It);if(t.schema!==_r)throw new Error(`Expected ${_r}`);return{schema:_r,...Nd(t,DP)}}function wa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function wd(e,t,r){if(e===null)return null;let i=typeof e=="string"?MP.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 JP(e){if(e==null)return null;if(typeof e!="string"||!yd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function GP(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 ai(e){let t=ya(e,It);if(t.schema!==Rr)throw new Error(`Expected ${Rr}`);if(wa(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Rr} minimum_runtime_version must be 2`);return{schema:Rr,minimum_runtime_version:2,revision:wa(t.revision,"Native v2 revision"),...Nd(t,Gv)}}function jt(e){let t=ya(e,It);if(t.schema!==Ut){if(t.schema===_r||t.schema===Rr){let o=t.schema===_r?ni(t):ai(t);throw new zi(o.name,o.schema)}throw new Kt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=wa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Kt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=wa(t.revision,"Native revision"),n=Nd(t,qP),a=JP(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ut,minimum_runtime_version:3,revision:i,verification_protocol:GP(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:wd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:wd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:wd(t.partial_allowance,"Native partial_allowance","allowances")}}function $s(e){let t=ya(e,It);if(t.schema===_r){let n=ni(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ut}`}}if(t.schema===Rr){let n=ai(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ut}`}}if(t.schema!==Ut){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 Kt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=wa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Kt(t.schema,r).message};let i=jt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Jv,DP,Gv,qP,FP,LP,BP,VP,It,yd,Uv,MP,zi,Kt,Os=I(()=>{"use strict";ga();Jv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],DP=new Set(Jv),Gv=new Set([...Jv,"minimum_runtime_version","revision"]),qP=new Set([...Gv,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),FP=new Set(["capability","operation","source","base_hash"]),LP=new Set(["shape","build","verify","archive"]),BP=new Set(["implicit","confirmed"]),VP=new Set(["pending","pass","fail"]),It="comet-state.yaml",yd=/^[a-f0-9]{64}$/u,Uv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MP=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,zi=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"},Kt=class extends Error{constructor(r,i){super(r!==Ut||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 Qv from"node:path";function eR(e,t){return e<t?-1:e>t?1:0}function tg(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 rg(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 tR(e){if(!QP.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=ZP.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 rR(e,t){let r=tg(e.text,Yt.maxTextBytes),i=e.context.slice(0,Yt.maxContextItems).map(n=>tg(n,Yt.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 ng(e){let t=tR({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(eR),n=i.slice(0,Yt.maxFailedCheckIds),a=e.criteria.slice(t,t+Yt.maxItems);for(let c of a){let l=[...r,rR(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?rg(e.acceptanceHash,u):null,limits:{...Yt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Yt.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?rg(e.acceptanceHash,o):null,limits:{...Yt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Yt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function kd(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 bd(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 ig(e){return e.includes("-->")||e.includes("--!>")}function*Gi(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
146
|
+
`)}var Id,NP,bP,Cg,Td,pi=I(()=>{"use strict";Id={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:"验证预期"}},NP={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:"结论"}},bP={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:"结论"}},Cg=new Map,Td=new Map;for(let e of Object.keys(Id)){for(let[t,r]of Object.entries(Id[e]))Cg.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(NP[e]))Td.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(bP[e]))Td.set(r.toLocaleLowerCase("en-US"),t)}});import Ir from"path";function PP(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ir.posix.isAbsolute(r)||Ir.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 Yi(e){let t=PP(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Og(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 Qs(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||Ir.posix.isAbsolute(i)||Ir.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 Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hg(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 Zs(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>Ys)throw new Error(`${t} exceeds ${Ys} 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>Xs)throw new Error(`${t} contains more than ${Xs} wildcard tokens`);return e}function Tg(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=>Zs(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function _a(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 jg(e,t,r){let i=_a(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 _P(e){if(e===void 0)return{...tt,include:[...tt.include],exclude:[...tt.exclude]};let t=Zt(e,"native.snapshot");return{include:Tg(t.include,"native.snapshot.include",tt.include),exclude:Tg(t.exclude,"native.snapshot.exclude",tt.exclude),max_files:_a(t.max_files,tt.max_files,"native.snapshot.max_files"),max_total_bytes:_a(t.max_total_bytes,tt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:_a(t.max_duration_ms,tt.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:_a(t.max_selection_records,tt.max_selection_records,"native.snapshot.max_selection_records")}}function AP(e){if(e===void 0)return;let t=Zt(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=Zt(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:Yi(i),toArtifactRoot:Yi(n),stage:a,...o?{cleanup:o}:{}}}function IP(e){if(e===void 0)return;let t=Zt(e,"native.finish");if(t.pull_request===void 0)return{};let r=Zt(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(Ir.posix.isAbsolute(i[0])||Ir.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??EP;if(!Number.isSafeInteger(n)||n<1||n>Ig)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ig}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function TP(e,t={}){let r=Zt(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??$g;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=AP(r.pending_root_move),l=IP(r.finish);return{artifact_root:Yi(i),language:Hg(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:_P(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function jP(e){let t=Zt(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:Og(t.artifact_layout),language:Hg(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function $P(e){let r=Zt(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)=>Qs(i,`hook.allow_paths[${n}]`)))]}}function OP(e){if(e===void 0)return{...jd};let t=Zt(e,"memory"),r=t.learning??jd.learning,i=t.retrieval??jd.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 Od(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function HP(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")||Ir.posix.isAbsolute(r)||Ir.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>Pg)throw new Error(`${t} exceeds ${Pg} 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>_g)throw new Error(`${t} contains more than ${_g} wildcard tokens`);return r}function DP(e){let t=Od(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)=>HP(n,`knowledge.local.include[${a}]`)))],max_file_mb:jg(t.max_file_mb,Ag.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:jg(t.max_total_mb,Ag.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 BP(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 FP(e){let t=Od(e,"knowledge.remote"),r=BP(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 LP(e){if(e===void 0)return{...SP};let t=Od(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:DP(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:FP(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 qP(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function MP(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 Ia(e,t={}){let r=(0,$d.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=qP(n.ambient_resume),o=n.hook===void 0?void 0:$P(n.hook),s=OP(n.memory),c=LP(n.knowledge),l=n.native===void 0?void 0:TP(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:jP(n.classic),d=MP(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}:{}}}var $d,Aa,Ys,Xs,Pg,_g,$g,jd,Ag,SP,EP,Ig,xP,CP,RP,tt,Tr=I(()=>{"use strict";$d=Kt(It(),1),Aa=Number.MAX_SAFE_INTEGER,Ys=1024,Xs=64,Pg=1024,_g=64,$g=5,jd={learning:!0,retrieval:!0},Ag={include:[],max_file_mb:1,max_total_mb:32},SP={provider:"local"},EP=12e4,Ig=6e5,xP=[".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/**"],CP=["**/.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"],RP=[...xP,...CP].sort((e,t)=>e.localeCompare(t,"en")),tt={include:["**/*"],exclude:[...RP],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as ec,promises as fi}from"fs";function Hd(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Dg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ta(e){return{dev:e.dev,ino:e.ino,birthtime:Hd(e)}}function tc(e,t){let r=Ta(e),i=Ta(t);return Qe(r,i)?G(r,i):G(r,i)&&Hd(e)===Hd(t)&&Dg(e)===Dg(t)&&e.size===t.size}async function Xi(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 fi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ot("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ot("too-large",`${i} exceeds ${t} bytes`);let o=await fi.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ta(a)});let s=process.platform==="win32"?ec.O_RDONLY:ec.O_RDONLY|ec.O_NOFOLLOW|ec.O_NONBLOCK,c;try{c=await fi.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ot("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),fi.lstat(e,{bigint:n}),fi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!tc(a,l)||!tc(a,u))throw new Ot("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Ta(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 Ot("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}),fi.lstat(e,{bigint:n}),fi.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!tc(a,h)||!tc(a,v))throw new Ot("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Ta(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:g}}finally{await c.close()}}var Ot,ja=I(()=>{"use strict";Pa();Ot=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as rc}from"fs";import jr from"path";function VP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Dd(e,t){let r=jr.relative(e,t);return r===""||!jr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jr.sep}`)}async function Bg(e,t){let r=jr.resolve(e),i=await rc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return rc.realpath(r)}async function Fg(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=jr.join(n,r[a]);let o;try{o=await rc.lstat(n)}catch(u){if(VP(u))return{exists:!1,kind:"missing"};throw u}let s=jr.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 rc.realpath(n);if(!Dd(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 Qi(e,t,r){let i=Qs(t,r.label),n=jr.resolve(e),a=await Bg(n,r.label),o=i.split("/"),s=jr.resolve(n,...o);if(!Dd(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Fg(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Ht(e,t,r,i){let n=await Qi(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 Bg(n.projectRoot,i.label);return Xi(n.target,r,{...i,verify:async(o,s)=>{if(!Dd(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Fg(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var er=I(()=>{"use strict";ja();Tr()});import{createHash as WP}from"crypto";function zP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ic(e,t={}){return(await nc(e,t)).document}async function GP(e){try{return(await Ht(e,$a,Aa,{label:$a})).bytes}catch(t){if(zP(t))return null;throw t}}function JP(e){return e?{exists:!0,sha256:WP("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function nc(e,t={}){let r=await GP(e);return{document:r?Ia(r.toString("utf8"),t):null,identity:JP(r)}}async function Bd(e){return(await ic(e))?.config??null}var $a,Zi=I(()=>{"use strict";Tr();er();$a=".comet/config.yaml"});var en=I(()=>{"use strict";Ad();Pa()});var oL,Fd=I(()=>{"use strict";en();Zi();er();oL=16*1024});var Md=I(()=>{"use strict";en();Tr();Zi();er();Fd()});import{existsSync as qg,promises as $r}from"fs";import B from"path";import QP from"os";async function Vd(e){try{return await $r.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function e_(e){try{let t=await $r.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function rn(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function tn(e){let t=[],r=e;for(;!await Vd(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await $r.realpath(r);return B.resolve(i,...t.reverse())}async function Wd(e){try{return(await $r.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gd(e){let t=B.resolve(e);try{(await $r.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(QP.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...zd.split("/")),s=t===r||await e_(o);if(await Vd(o)&&s)return t}if(await Vd(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function Jd(e){return Yi(e)}async function t_(e,t){let r=Jd(t),i=B.resolve(e,...r.split("/")),n=await $r.realpath(e),a=await tn(i);if(!rn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function tr(e,t){let r=Jd(t),i=await t_(e,r),n=B.join(i,"comet");if(await Wd(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([tn(i),tn(n)]);if(!rn(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 Wd(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([$r.realpath(s),tn(c)]);if(!rn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...zd.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 Ud(e){if(!ZP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vt(e,t){Ud(t);let r=B.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Vg(e,t){Ud(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=vt(e,t);if(qg(r))return r;let i=Vg(e,t);return qg(i)?i:r}function Ha(e,t){Ud(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 Mg(e){try{let t=await $r.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Kd(e,t){let r=vt(e,t),i=Vg(e,t),[n,a]=await Promise.all([Mg(r),Mg(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 Or(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 we(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 rn(B.resolve(e),B.resolve(t))}async function K(e,t){let r=B.resolve(e),i=B.resolve(t);if(!rn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Wd(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([tn(r),tn(i)]);if(!rn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var zd,ZP,U=I(()=>{"use strict";Tr();zd=".comet/config.yaml",ZP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});async function Te(e){let t=(await ic(e))?.config??null;return t?.native?t:null}var Yd,ac,Je=I(()=>{"use strict";Tr();Zi();Md();ae();U();Yd=tt,ac=Zs});import{createHash as i_,randomUUID as PL}from"node:crypto";var n_,AL,zg=I(()=>{"use strict";Di();n_=`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
|
+
}`,AL=i_("sha256").update(n_).digest("hex")});var oc=I(()=>{"use strict";Di();zg()});import{AsyncLocalStorage as o_}from"async_hooks";var qL,ML,VL,Da=I(()=>{"use strict";ja();oc();U();jt();qL=16*1024,ML=900*1e3,VL=new o_});var Jg,Xd=I(()=>{"use strict";Jg=Kt(It(),1)});var rr,Hr,Dr,nn,an,Ba,Fa=I(()=>{"use strict";rr="comet.native.v3",Hr="comet.native.v2",Dr="comet.native.v1",nn="comet.native.transition.v3",an="comet.native.transition.v2",Ba="comet.native.transition.v1"});import s_ from"node:path";function qa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xg(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 sn(e){if(!Yg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Qg(e){if(!Yg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Zg(e,t){if(e.length===0||s_.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function m_(e,t){let r=qa(e,`spec_changes[${t}]`);if(Xg(r,u_,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Qg(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"&&Zg(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"||!Zd.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"||!Zd.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 ep(e,t){if(Xg(e,t,Dt),typeof e.name!="string")throw new Error("Native change name is required");if(sn(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&&!p_.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(m_),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"&&Zg(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 hi(e){let t=qa(e,Dt);if(t.schema!==Dr)throw new Error(`Expected ${Dr}`);return{schema:Dr,...ep(t,c_)}}function La(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Qd(e,t,r){if(e===null)return null;let i=typeof e=="string"?h_.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 g_(e){if(e==null)return null;if(typeof e!="string"||!Zd.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 mi(e){let t=qa(e,Dt);if(t.schema!==Hr)throw new Error(`Expected ${Hr}`);if(La(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Hr} minimum_runtime_version must be 2`);return{schema:Hr,minimum_runtime_version:2,revision:La(t.revision,"Native v2 revision"),...ep(t,Kg)}}function Bt(e){let t=qa(e,Dt);if(t.schema!==rr){if(t.schema===Dr||t.schema===Hr){let o=t.schema===Dr?hi(t):mi(t);throw new on(o.name,o.schema)}throw new ir(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=La(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ir(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=La(t.revision,"Native revision"),n=ep(t,l_),a=g_(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:rr,minimum_runtime_version:3,revision:i,verification_protocol:w_(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Qd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Qd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Qd(t.partial_allowance,"Native partial_allowance","allowances")}}function sc(e){let t=qa(e,Dt);if(t.schema===Dr){let n=hi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${rr}`}}if(t.schema===Hr){let n=mi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${rr}`}}if(t.schema!==rr){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 ir(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=La(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new ir(t.schema,r).message};let i=Bt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Ug,c_,Kg,l_,u_,d_,p_,f_,Dt,Zd,Yg,h_,on,ir,cc=I(()=>{"use strict";Fa();Ug=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],c_=new Set(Ug),Kg=new Set([...Ug,"minimum_runtime_version","revision"]),l_=new Set([...Kg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),u_=new Set(["capability","operation","source","base_hash"]),d_=new Set(["shape","build","verify","archive"]),p_=new Set(["implicit","confirmed"]),f_=new Set(["pending","pass","fail"]),Dt="comet-state.yaml",Zd=/^[a-f0-9]{64}$/u,Yg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,h_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,on=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"},ir=class extends Error{constructor(r,i){super(r!==rr||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 ew from"node:path";function x_(e,t){return e<t?-1:e>t?1:0}function iw(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 nw(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 C_(e){if(!S_.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=E_.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 R_(e,t){let r=iw(e.text,nr.maxTextBytes),i=e.context.slice(0,nr.maxContextItems).map(n=>iw(n,nr.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 ow(e){let t=C_({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(x_),n=i.slice(0,nr.maxFailedCheckIds),a=e.criteria.slice(t,t+nr.maxItems);for(let c of a){let l=[...r,R_(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?nw(e.acceptanceHash,u):null,limits:{...nr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>nr.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?nw(e.acceptanceHash,o):null,limits:{...nr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>nr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function rp(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 tp(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 aw(e){return e.includes("-->")||e.includes("--!>")}function*cn(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
147
160
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
148
|
-
`,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=
|
|
149
|
-
`),[],i)),"Brief",i)}function
|
|
150
|
-
`),
|
|
151
|
-
`).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=og(o),c=cR(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function cR(e){let t=og([...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 UP,KP,YP,XP,QP,ZP,Yt,Na,Zv,eg,ba=I(()=>{"use strict";ri();se();UP="comet.native.acceptance.v1",KP=/^acceptance-[a-f0-9]{64}$/u,YP=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),XP=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,QP=/^[a-f0-9]{64}$/u,ZP=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;Yt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Na=Object.freeze({maxCriteria:1024}),Zv="<!-- comet-native:acceptance-evidence:start -->",eg="<!-- comet-native:acceptance-evidence:end -->"});var Pd=I(()=>{"use strict";ba()});function Rd(){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 Ui,Ds,cg,ka=I(()=>{"use strict";Ui="comet.native.v4",Ds="comet.native.local-execution.v4",cg=["multi-session","single-session"]});var Td={};Qb(Td,{NativePortableStateVersionConflictError:()=>Sa,appendNativePortableHistory:()=>Ea,compareAndSwapNativePortableState:()=>dg,createNativePortableState:()=>ug,parseNativePortableState:()=>qe,readNativePortableState:()=>Ar,writeNativePortableState:()=>jd});import{promises as lR}from"node:fs";function Re(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _e(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ge(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 Ad(e,t){return e===null?null:ge(e,t)}function Id(e,t){let r=ge(e,t);if(!pR.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Ki(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ie(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 mR(e,t){return e===null?null:ie(e,t,Number.MIN_SAFE_INTEGER)}function ue(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Tt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Bs(e,t){return Tt(e,t,(r,i)=>ge(r,`${t}[${i}]`))}function oi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Yi(e,t){let r=ge(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Fs(e,t,r=!1){let i=ge(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 Ze(e,t){let r=Re(e,t);return _e(r,new Set(["text","truncated"]),t),{text:ge(r.text,`${t}.text`,{empty:!0}),truncated:Ki(r.truncated,`${t}.truncated`)}}function vR(e,t){let r=`Native spec_changes[${t}]`,i=Re(e,r);_e(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ge(i.capability,`${r}.capability`);if(!dR.test(n))throw new Error(`${r}.capability is invalid`);let a=ue(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Fs(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Fs(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:Id(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 gR(e){let t="Native workspace",r=Re(e,t);_e(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ue(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ad(r.change_branch,`${t}.change_branch`),a=Ad(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ue(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 wR(e){let t="Native loop",r=Re(e,t);_e(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=Bs(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);oi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ue(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ue(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ie(r.goal_cycle,`${t}.goal_cycle`,1),iteration:ie(r.iteration,`${t}.iteration`),attempt:ie(r.attempt,`${t}.attempt`),retry_epoch:ie(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ie(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ie(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ie(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Ad(r.next_action,`${t}.next_action`)}}function yR(e,t){let r=`Native acceptance[${t}]`,i=Re(e,r);_e(i,new Set(["id","source","text","result","reason"]),r);let n=ge(i.id,`${r}.id`);if(!fR.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Fs(i.source,`${r}.source`),text:ge(i.text,`${r}.text`),result:ue(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ze(i.reason,`${r}.reason`)}}function NR(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Re(e,r);return _e(i,new Set(["name","result","note"]),r),{name:Ze(i.name,`${r}.name`),result:ue(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ze(i.note,`${r}.note`)}}function bR(e){let t="Native builder_handoff",r=Re(e,t);_e(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=Bs(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);oi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Re(r.review,`${t}.review`);return n&&_e(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ge(r.candidate_id,`${t}.candidate_id`),identity_provider:ge(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ge(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ie(r.iteration,`${t}.iteration`,1),summary:Ze(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Tt(r.checks,`${t}.checks`,NR),checks_truncated:Ki(r.checks_truncated,`${t}.checks_truncated`),known_limits:Tt(r.known_limits,`${t}.known_limits`,(a,o)=>Ze(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Ki(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ue(n.status,["passed"],`${t}.review.status`),summary:Ze(n.summary,`${t}.review.summary`),reviewer_execution_ref:ge(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Yi(r.submitted_at,`${t}.submitted_at`)}}function kR(e,t){let r=`Native blockers[${t}]`,i=Re(e,r);_e(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Bs(i.acceptance_ids,`${r}.acceptance_ids`);return oi(n,`${r}.acceptance_ids`),{owner:ue(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ze(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ue(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function SR(e,t){let r=`Native verification.checks[${t}]`,i=Re(e,r);return _e(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ge(i.id,`${r}.id`),name:Ze(i.name,`${r}.name`),argv_display:Tt(i.argv_display,`${r}.argv_display`,(n,a)=>Ze(n,`${r}.argv_display[${a}]`)),argv_truncated:Ki(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Fs(i.cwd_ref,`${r}.cwd_ref`,!0),status:ue(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:mR(i.exit_code,`${r}.exit_code`),duration_ms:ie(i.duration_ms,`${r}.duration_ms`)}}function ER(e){let t="Native verification",r=Re(e,t);_e(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Tt(r.checks,`${t}.checks`,SR);oi(i.map(a=>a.id),`${t}.checks IDs`);let n=ge(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ge(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ge(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ie(r.iteration,`${t}.iteration`,1),attempt:ie(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ue(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ue(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ze(r.summary,`${t}.summary`),risks:Tt(r.risks,`${t}.risks`,(a,o)=>Ze(a,`${t}.risks[${o}]`)),risks_truncated:Ki(r.risks_truncated,`${t}.risks_truncated`),completed_at:Yi(r.completed_at,`${t}.completed_at`)}}function lg(e,t){let r=`Native history[${t}]`,i=Re(e,r);_e(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Bs(i.unresolved_ids,`${r}.unresolved_ids`);return oi(n,`${r}.unresolved_ids`),{goal_cycle:ie(i.goal_cycle,`${r}.goal_cycle`,1),iteration:ie(i.iteration,`${r}.iteration`),attempt:ie(i.attempt,`${r}.attempt`),outcome:ue(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ze(i.summary,`${r}.summary`),completed_at:Yi(i.completed_at,`${r}.completed_at`)}}function xR(e){let t="Native history_overflow.outcome_counts",r=Re(e,t),i=["pass","fail","blocked","execution-error","recovery"];return _e(r,new Set(i),t),{pass:ie(r.pass,`${t}.pass`),fail:ie(r.fail,`${t}.fail`),blocked:ie(r.blocked,`${t}.blocked`),"execution-error":ie(r["execution-error"],`${t}.execution-error`),recovery:ie(r.recovery,`${t}.recovery`)}}function CR(e){let t="Native history_overflow",r=Re(e,t);_e(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=ie(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Yi(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Yi(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=xR(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 PR(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 RR(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 qe(e){let t=Re(e,"Native portable state");if(_e(t,hR,"Native portable state"),t.schema!==Ui)throw new Error(`Native portable state schema must be ${Ui}`);let r=ge(t.name,"Native state name");if(!uR.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=Tt(t.spec_changes,"Native spec_changes",vR);oi(i.map(s=>s.capability),"Native spec change capabilities");let n=Tt(t.acceptance,"Native acceptance",yR);oi(n.map(s=>s.id),"Native acceptance IDs");let a=Tt(t.history,"Native history",lg);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ui,name:r,language:ue(t.language,["en","zh-CN"],"Native state language"),phase:ue(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ue(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ie(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:Id(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Id(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ue(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:gR(t.workspace),loop:wR(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:bR(t.builder_handoff),blockers:Tt(t.blockers,"Native blockers",kR),verification:t.verification===null?null:ER(t.verification),history:a,history_overflow:CR(t.history_overflow),verification_result:ue(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ue(t.verification_report,["verification.md"],"Native verification_report"),archived:Ki(t.archived,"Native archived"),created_at:Yi(t.created_at,"Native created_at")};return PR(o),RR(o),o}function ug(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return qe({schema:Ui,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:Rd(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Ea(e,t){let r=qe(e),i=lg(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 qe({...r,history:n,history_overflow:a})}function _R(e,t){let r=(0,Ls.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 Ar(e){let t=await lR.readFile(e,"utf8");return qe(_R(t,"Native portable state"))}async function jd(e,t,r={}){let i=qe(t);await _t(e,(0,Ls.stringify)(i),r)}async function AR(e,t){let r=qs.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);qs.set(e,a),await r;try{return await t()}finally{i(),qs.get(e)===a&&qs.delete(e)}}async function dg(e){return AR(e.file,async()=>{let t=ie(e.expectedStateVersion,"Native expected state version",1),r=qe(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Ar(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Sa(t,i.state_version);return await jd(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ar(e.file);if(n.state_version!==t)throw new Sa(t,n.state_version)}}),r})}var Ls,uR,dR,fR,pR,hR,Sa,qs,ft=I(()=>{"use strict";Ls=Bt(Ct(),1);ce();ka();uR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,fR=/^A[1-9][0-9]*$/u,pR=/^[a-f0-9]{64}$/u,hR=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"]),Sa=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"};qs=new Map});var si=I(()=>{"use strict"});var fg=I(()=>{"use strict";Os();Pd();ft();si();ka();ga()});var pg,Aq,Iq,$d=I(()=>{"use strict";Xe();gd();fg();pg="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Aq=new RegExp(`^portable-archive-(${pg})\\.json$`,"u"),Iq=new RegExp(`^portable-migration-(${pg})\\.json$`,"u")});import{createHash as hg}from"node:crypto";import{constants as Ir,promises as de}from"node:fs";import Fe from"node:path";import{TextDecoder as TR}from"node:util";function Xi(e,t){let r=Fe.relative(e,t);return r===""||!Fe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Fe.sep}`)}function mg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function $R(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vg(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function jr(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 Vs(e,t){let r=await de.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await de.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Ms(e,t,r){let i=Fe.resolve(e),n=Fe.resolve(t);if(!Xi(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Vs(i,r)],o=i;for(let s of Fe.relative(i,n).split(Fe.sep).filter(Boolean)){await Ae(a,r),o=Fe.join(o,s);let c=await Vs(o,r);if(!Xi(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ae(a,r),a}async function Ae(e,t){for(let r of e){let i=await de.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!$R(r,i)||await de.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function OR(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 ci(e){let t=e.maxBytes===null?null:mg(e.maxBytes),r=Fe.resolve(e.file),i=await Ms(e.root,Fe.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Vs(Fe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ae(i,e.label);let a=await de.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=vg(a),s=await de.realpath(r);if(!Xi(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Xi(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ir.O_RDONLY:Ir.O_RDONLY|Ir.O_NOFOLLOW|Ir.O_NONBLOCK,l=await de.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([de.lstat(r),de.realpath(r)]);if(await Ae(i,e.label),await Ae(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!jr(o,u)||!jr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await OR(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),de.lstat(r),de.realpath(r)]);if(await Ae(i,e.label),await Ae(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!jr(o,m)||!jr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:hg("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Od(e){let t=Fe.resolve(e.file),r=await Ms(e.root,Fe.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>Vs(Fe.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ae(r,e.label);let n=await de.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=vg(n),o=await de.realpath(t);if(!Xi(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>Xi(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Ir.O_RDONLY:Ir.O_RDONLY|Ir.O_NOFOLLOW|Ir.O_NONBLOCK,c=await de.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([de.lstat(t),de.realpath(t)]);if(await Ae(r,e.label),await Ae(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!jr(a,l)||!jr(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=hg("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(),de.lstat(t),de.realpath(t)]);if(await Ae(r,e.label),await Ae(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!jr(a,h)||!jr(a,v))throw new Error(`${e.label} changed while reading`);return{hash:f.digest("hex"),size:p}}finally{await c.close()}}async function gg(e){let t=await ci(e),r;try{r=new TR("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 Ca(e){let t=await Ms(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await de.readdir(e.directory,{withFileTypes:!0});else{let i=mg(e.maxEntries);r=[];let n=await de.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 Ae(t,e.label),{entries:r,verify:()=>Ae(t,e.label)}}async function Hd(e){let t=await Ms(e.root,e.directory,e.label);return{verify:()=>Ae(t,e.label)}}var pt=I(()=>{"use strict";ce();Rt()});import{TextDecoder as DR}from"util";var Gq,Ws=I(()=>{"use strict";ce();G();pt();Gq=new DR("utf-8",{fatal:!0})});var Ne=I(()=>{"use strict";Me();ma();$d();Ws()});import{createHash as kg}from"crypto";import{createReadStream as FR}from"fs";async function Dd(e){let t=kg("sha256");for await(let r of FR(e))t.update(r);return t.digest("hex")}function Q(e){return kg("sha256").update(e).digest("hex")}var $t=I(()=>{"use strict"});import{createHash as Ks}from"crypto";import{spawn as Ig}from"node:child_process";import{promises as ee}from"fs";import F from"path";function Tg(e){let t=e.deadlineMs??i_;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 ht(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return ht(e)>=1}function qd(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 en(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function s_(e,t){let r={...o_,...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 c_(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=Ig(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),n_),u.unref()}catch{d(!1)}});for(let s=0;s<a_;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 Wd(e,t,r,i){let n=ht(e);if(n<1)throw qd();let a=e.gitProcess,o=Ig(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=c_(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?qd(m.error):qd()}return{code:p,spawnError:s}});return{child:o,completion:f}}function $g(e,t){let r={...Md,...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 Js(e,t,r,i=Bd){let{child:n,completion:a}=Wd(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>=rn)return;let m=rn-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 Fd(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Ra(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}=Wd(e,t,r,i.stdin!==void 0),c=[],l=Ks("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>=rn)return;let x=rn-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 Gs(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 l_(e,t,r){if(r.length===0)return new Set;let i=await Ra(e,t,["check-ignore","--no-index","-z","--stdin"],{...Md,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=Gs(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function u_(e,t,r){let{child:i,completion:n}=Wd(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>=rn)return;let d=rn-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 tn(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 d_(e,t){return e.map(r=>{let i=tn(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function f_(e){let t=F.resolve(e);for(;;){try{return await ee.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 p_(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function Og(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=tn(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(p=>[`:(exclude)${p}`,`:(exclude)${p}/**`]),...p_(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await Ra(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await Ra(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let f=await Ra(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:f}}function Hg(e){return{stageBefore:Fd(e.stagedBefore),combined:Fd(e.combined),stageAfter:Fd(e.stagedAfter)}}async function Dg(e,t,r=Md,i={},n){let a=F.resolve(t.projectRoot);if(!await f_(a))return null;let o;try{o=await Js(e,a,["rev-parse","--is-inside-work-tree"])}catch(S){throw en(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 Og(e,t,r,i,n)}catch(S){throw en(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=Gs(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=tn(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(Gs),v=d_(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:Hg(s)}}function $r(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Sg(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function h_(e,t){return!$r(e.stageBefore,e.stageAfter)||!$r(e.stageAfter,t.stageBefore)||!$r(e.combined,t.combined)||!$r(t.stageBefore,t.stageAfter)}async function qg(e,t,r,i,n,a){let o;try{o=await Og(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw en(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=Hg(o),l=Sg(s)||Sg(c),u=h_(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
|
|
152
|
-
${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function
|
|
153
|
-
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):
|
|
154
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:
|
|
155
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function
|
|
161
|
+
`,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=tp(l,t);else if(r)aw(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=tp(l,null);if(d!==null)t=d;else{let p=l.trimStart();if(p.startsWith("<!--")&&!aw(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 P_(e){return[...cn(e)].map(({line:t,body:r})=>({line:t,body:r}))}function lc(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function __(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function ip(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-${T(y_,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function np(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 A_(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of cn(e)){n=s+1;let c=o?rp(a):null;c?.level===1&&(Us(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 ap(e,t="brief.md",r=Ma.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=A_(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of cn(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 cn(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(),np(o.map(l=>ip("brief-example",t,l.join(`
|
|
162
|
+
`),[],i)),"Brief",i)}function op(e,t="spec.md",r=Ma.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({...ip("spec-scenario",t,[s.title,...s.body].join(`
|
|
163
|
+
`),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of cn(e)){let d=u?rp(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(),np(a,"Specification",i)}function sw(e,t="spec.md",r=Ma.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(ip("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 cn(e)){let p=d?rp(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||tp(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(),np(n,"Specification mandatory requirements",i)}function I_(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||__(r)||ew.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=ew.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(!k_.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function T_(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=>!b_.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function cw(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=T_(r,i),a=n.acceptance_id;if(typeof a!="string"||!N_.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 I_(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 lw(e){let t=P_(e);if(t.some(({line:l,body:u})=>!u&&(l===tw||l===rw)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===tw?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===rw?[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(`
|
|
164
|
+
`).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=cw(o),c=j_(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function j_(e){let t=cw([...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 y_,N_,b_,k_,S_,E_,nr,Ma,tw,rw,Va=I(()=>{"use strict";pi();ue();y_="comet.native.acceptance.v1",N_=/^acceptance-[a-f0-9]{64}$/u,b_=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),k_=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,S_=/^[a-f0-9]{64}$/u,E_=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;nr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ma=Object.freeze({maxCriteria:1024}),tw="<!-- comet-native:acceptance-evidence:start -->",rw="<!-- comet-native:acceptance-evidence:end -->"});var sp=I(()=>{"use strict";Va()});function cp(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 Wa({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var Wa,uc=I(()=>{"use strict";Wa=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 lp(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 up(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}]`;cp(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:lp(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>lp(o,`${n}.evidence`)),note:lp(i.note,`${n}.note`)}})}function dp(e,t){if(!t)throw new ln(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 ln(o,s)}var ln,dc=I(()=>{"use strict";uc();ln=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 pp(){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 un,pc,uw,za=I(()=>{"use strict";un="comet.native.v4",pc="comet.native.local-execution.v4",uw=["multi-session","single-session"]});var gp={};mS(gp,{NativePortableStateVersionConflictError:()=>Ga,appendNativePortableHistory:()=>Ja,compareAndSwapNativePortableState:()=>fw,createNativePortableState:()=>pw,parseNativePortableState:()=>qe,readNativePortableState:()=>Br,writeNativePortableState:()=>vp});import{promises as $_}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 $e(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 hp(e,t){return e===null?null:ye(e,t)}function mp(e,t){let r=ye(e,t);if(!B_.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function dn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function oe(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 L_(e,t){return e===null?null:oe(e,t,Number.MIN_SAFE_INTEGER)}function pe(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 vc(e,t){return Ft(e,t,(r,i)=>ye(r,`${t}[${i}]`))}function vi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function pn(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 hc(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 $e(r,new Set(["text","truncated"]),t),{text:ye(r.text,`${t}.text`,{empty:!0}),truncated:dn(r.truncated,`${t}.truncated`)}}function q_(e,t){let r=`Native spec_changes[${t}]`,i=je(e,r);$e(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ye(i.capability,`${r}.capability`);if(!H_.test(n))throw new Error(`${r}.capability is invalid`);let a=pe(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:hc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:hc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:mp(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 M_(e){let t="Native workspace",r=je(e,t);$e(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=pe(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=hp(r.change_branch,`${t}.change_branch`),a=hp(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:pe(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 V_(e){let t="Native loop",r=je(e,t);$e(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=vc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);vi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:pe(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:pe(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:oe(r.goal_cycle,`${t}.goal_cycle`,1),iteration:oe(r.iteration,`${t}.iteration`),attempt:oe(r.attempt,`${t}.attempt`),retry_epoch:oe(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:oe(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:oe(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:oe(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:hp(r.next_action,`${t}.next_action`)}}function W_(e,t){let r=`Native acceptance[${t}]`,i=je(e,r);$e(i,new Set(["id","source","text","result","reason"]),r);let n=ye(i.id,`${r}.id`);if(!D_.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:hc(i.source,`${r}.source`),text:ye(i.text,`${r}.text`),result:pe(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:rt(i.reason,`${r}.reason`)}}function z_(e,t){let r=`Native builder_handoff.checks[${t}]`,i=je(e,r);return $e(i,new Set(["name","result","note"]),r),{name:rt(i.name,`${r}.name`),result:pe(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:rt(i.note,`${r}.note`)}}function G_(e){let t="Native builder_handoff",r=je(e,t);$e(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=vc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);vi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:je(r.review,`${t}.review`);return n&&$e(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:oe(r.iteration,`${t}.iteration`,1),summary:rt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:up(r.acceptance_review)},checks:Ft(r.checks,`${t}.checks`,z_),checks_truncated:dn(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:dn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:pe(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:pn(r.submitted_at,`${t}.submitted_at`)}}function J_(e,t){let r=`Native blockers[${t}]`,i=je(e,r);$e(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=vc(i.acceptance_ids,`${r}.acceptance_ids`);return vi(n,`${r}.acceptance_ids`),{owner:pe(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:rt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:pe(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function U_(e,t){let r=`Native verification.checks[${t}]`,i=je(e,r);return $e(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:dn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:hc(i.cwd_ref,`${r}.cwd_ref`,!0),status:pe(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:L_(i.exit_code,`${r}.exit_code`),duration_ms:oe(i.duration_ms,`${r}.duration_ms`)}}function K_(e){let t="Native verification",r=je(e,t);$e(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`,U_);vi(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:oe(r.iteration,`${t}.iteration`,1),attempt:oe(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":pe(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:pe(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:dn(r.risks_truncated,`${t}.risks_truncated`),completed_at:pn(r.completed_at,`${t}.completed_at`)}}function dw(e,t){let r=`Native history[${t}]`,i=je(e,r);$e(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=vc(i.unresolved_ids,`${r}.unresolved_ids`);return vi(n,`${r}.unresolved_ids`),{goal_cycle:oe(i.goal_cycle,`${r}.goal_cycle`,1),iteration:oe(i.iteration,`${r}.iteration`),attempt:oe(i.attempt,`${r}.attempt`),outcome:pe(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:rt(i.summary,`${r}.summary`),completed_at:pn(i.completed_at,`${r}.completed_at`)}}function Y_(e){let t="Native history_overflow.outcome_counts",r=je(e,t),i=["pass","fail","blocked","execution-error","recovery"];return $e(r,new Set(i),t),{pass:oe(r.pass,`${t}.pass`),fail:oe(r.fail,`${t}.fail`),blocked:oe(r.blocked,`${t}.blocked`),"execution-error":oe(r["execution-error"],`${t}.execution-error`),recovery:oe(r.recovery,`${t}.recovery`)}}function X_(e){let t="Native history_overflow",r=je(e,t);$e(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=oe(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:pn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:pn(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=Y_(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 Q_(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&&dp(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 Z_(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 qe(e){let t=je(e,"Native portable state");if($e(t,F_,"Native portable state"),t.schema!==un)throw new Error(`Native portable state schema must be ${un}`);let r=ye(t.name,"Native state name");if(!O_.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",q_);vi(i.map(s=>s.capability),"Native spec change capabilities");let n=Ft(t.acceptance,"Native acceptance",W_);vi(n.map(s=>s.id),"Native acceptance IDs");let a=Ft(t.history,"Native history",dw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:un,name:r,language:pe(t.language,["en","zh-CN"],"Native state language"),phase:pe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:pe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:oe(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:mp(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:mp(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:pe(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:M_(t.workspace),loop:V_(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:G_(t.builder_handoff),blockers:Ft(t.blockers,"Native blockers",J_),verification:t.verification===null?null:K_(t.verification),history:a,history_overflow:X_(t.history_overflow),verification_result:pe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:pe(t.verification_report,["verification.md"],"Native verification_report"),archived:dn(t.archived,"Native archived"),created_at:pn(t.created_at,"Native created_at")};return Q_(o),Z_(o),o}function pw(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return qe({schema:un,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:pp(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Ja(e,t){let r=qe(e),i=dw(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 qe({...r,history:n,history_overflow:a})}function eA(e,t){let r=(0,mc.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 Br(e){let t=await $_.readFile(e,"utf8");return qe(eA(t,"Native portable state"))}async function vp(e,t,r={}){let i=qe(t);await $t(e,(0,mc.stringify)(i),r)}async function tA(e,t){let r=fc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);fc.set(e,a),await r;try{return await t()}finally{i(),fc.get(e)===a&&fc.delete(e)}}async function fw(e){return tA(e.file,async()=>{let t=oe(e.expectedStateVersion,"Native expected state version",1),r=qe(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Br(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ga(t,i.state_version);return await vp(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Br(e.file);if(n.state_version!==t)throw new Ga(t,n.state_version)}}),r})}var mc,O_,H_,D_,B_,F_,Ga,fc,gt=I(()=>{"use strict";dc();mc=Kt(It(),1);ae();za();O_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,H_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,D_=/^A[1-9][0-9]*$/u,B_=/^[a-f0-9]{64}$/u,F_=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"]),Ga=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"};fc=new Map});var gi=I(()=>{"use strict"});var hw=I(()=>{"use strict";cc();sp();gt();gi();za();Fa()});var mw,Sq,Eq,wp=I(()=>{"use strict";et();Xd();hw();mw="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Sq=new RegExp(`^portable-archive-(${mw})\\.json$`,"u"),Eq=new RegExp(`^portable-migration-(${mw})\\.json$`,"u")});import{createHash as vw}from"node:crypto";import{constants as Fr,promises as fe}from"node:fs";import Me from"node:path";import{TextDecoder as nA}from"node:util";function fn(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function gw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function aA(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ww(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Lr(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 gc(e,t){let r=await fe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await fe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function wc(e,t,r){let i=Me.resolve(e),n=Me.resolve(t);if(!fn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await gc(i,r)],o=i;for(let s of Me.relative(i,n).split(Me.sep).filter(Boolean)){await Oe(a,r),o=Me.join(o,s);let c=await gc(o,r);if(!fn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Oe(a,r),a}async function Oe(e,t){for(let r of e){let i=await fe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!aA(r,i)||await fe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function oA(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 wi(e){let t=e.maxBytes===null?null:gw(e.maxBytes),r=Me.resolve(e.file),i=await wc(e.root,Me.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>gc(Me.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Oe(i,e.label);let a=await fe.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=ww(a),s=await fe.realpath(r);if(!fn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>fn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,l=await fe.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([fe.lstat(r),fe.realpath(r)]);if(await Oe(i,e.label),await Oe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!Lr(o,u)||!Lr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await oA(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),fe.lstat(r),fe.realpath(r)]);if(await Oe(i,e.label),await Oe(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Lr(o,m)||!Lr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:vw("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function yp(e){let t=Me.resolve(e.file),r=await wc(e.root,Me.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>gc(Me.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Oe(r,e.label);let n=await fe.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=ww(n),o=await fe.realpath(t);if(!fn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>fn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Fr.O_RDONLY:Fr.O_RDONLY|Fr.O_NOFOLLOW|Fr.O_NONBLOCK,c=await fe.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([fe.lstat(t),fe.realpath(t)]);if(await Oe(r,e.label),await Oe(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Lr(a,l)||!Lr(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=vw("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(),fe.lstat(t),fe.realpath(t)]);if(await Oe(r,e.label),await Oe(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!Lr(a,h)||!Lr(a,v))throw new Error(`${e.label} changed while reading`);return{hash:p.digest("hex"),size:f}}finally{await c.close()}}async function yw(e){let t=await wi(e),r;try{r=new nA("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 Ka(e){let t=await wc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await fe.readdir(e.directory,{withFileTypes:!0});else{let i=gw(e.maxEntries);r=[];let n=await fe.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 Oe(t,e.label),{entries:r,verify:()=>Oe(t,e.label)}}async function Np(e){let t=await wc(e.root,e.directory,e.label);return{verify:()=>Oe(t,e.label)}}var wt=I(()=>{"use strict";ae();jt()});import{TextDecoder as cA}from"util";var Lq,yc=I(()=>{"use strict";ae();U();wt();Lq=new cA("utf-8",{fatal:!0})});var Se=I(()=>{"use strict";Je();Da();wp();yc()});import{createHash as Ew}from"crypto";import{createReadStream as uA}from"fs";async function bp(e){let t=Ew("sha256");for await(let r of uA(e))t.update(r);return t.digest("hex")}function ee(e){return Ew("sha256").update(e).digest("hex")}var Lt=I(()=>{"use strict"});import{createHash as Ec}from"crypto";import{spawn as $w}from"node:child_process";import{promises as re}from"fs";import F from"path";import{performance as xw}from"node:perf_hooks";function Hw(e){let t=e.deadlineMs??PA;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 yt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return yt(e)>=1}function kp(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 vn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function TA(e,t){let r={...IA,...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 jA(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=$w(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),_A),u.unref()}catch{d(!1)}});for(let s=0;s<AA;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 Pp(e,t,r,i){let n=yt(e);if(n<1)throw kp();let a=e.gitProcess,o=xw.now(),s=$w(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=jA(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?kp(h.error):kp()}return{code:m,spawnError:c}}).finally(()=>Bl(xw.now()-o));return{child:s,completion:f}}function Dw(e,t){let r={...Rp,...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 bc(e,t,r,i=xp){let{child:n,completion:a}=Pp(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>=wn)return;let m=wn-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 Sp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Xa(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}=Pp(e,t,r,i.stdin!==void 0),c=[],l=Ec("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>=wn)return;let x=wn-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 kc(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 $A(e,t,r){if(r.length===0)return new Set;let i=await Xa(e,t,["check-ignore","--no-index","-z","--stdin"],{...Rp,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=kc(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function OA(e,t,r){let{child:i,completion:n}=Pp(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>=wn)return;let d=wn-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 gn(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 HA(e,t){return e.map(r=>{let i=gn(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function DA(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 BA(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function Bw(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=gn(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`]),...BA(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await Xa(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await Xa(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let p=await Xa(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:p}}function Fw(e){return{stageBefore:Sp(e.stagedBefore),combined:Sp(e.combined),stageAfter:Sp(e.stagedAfter)}}async function Lw(e,t,r=Rp,i={},n){let a=F.resolve(t.projectRoot);if(!await DA(a))return null;let o;try{o=await bc(e,a,["rev-parse","--is-inside-work-tree"])}catch(k){throw vn(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 Bw(e,t,r,i,n)}catch(k){throw vn(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=kc(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=gn(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(kc),v=HA(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:Fw(s)}}function Mr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Cw(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function FA(e,t){return!Mr(e.stageBefore,e.stageAfter)||!Mr(e.stageAfter,t.stageBefore)||!Mr(e.combined,t.combined)||!Mr(t.stageBefore,t.stageAfter)}async function qw(e,t,r,i,n,a){let o;try{o=await Bw(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw vn(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=Fw(o),l=Cw(s)||Cw(c),u=FA(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
|
|
165
|
+
${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function qA(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Rw(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=()=>yt(e.execution)>=1?!0:(f=!0,h=!0,!1),g=N=>{let x=Buffer.from(`${N.type}\0${N.path}`,"utf8"),w=Ec("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")}`)&LA,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 re.opendir(N)}catch(C){if(!v())return;if(!me(C)&&!he(C)||N===t&&me(C))throw C;m||=he(C),f||=me(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(!me(Z)&&!he(Z)||N===t&&me(Z))throw Z;m||=he(Z),f||=me(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),j=VA(t,O);if(O===n||O===a||Nt(r,O)||Nt(i,O)||e.denylist.some(Z=>Nt(Z,O))||Tt(j)!==null)continue;if(!v())break;let Q;try{Q=await re.lstat(O)}catch(Z){if(!v())break;if(!me(Z)&&!he(Z))throw Z;if(m=!0,g({path:j,type:"other"}),s.push({path:j,size:null,type:"file",reason:me(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(j),h||!v())break;continue}if(!v())break;let Pe=qA(Q);if(Pe==="directory"){if(JA(e.policy,j))continue;if(!v())break;let Z;try{Z=await re.realpath(O)}catch(Pt){if(!v())break;if(!me(Pt)&&!he(Pt))throw Pt;if(m=!0,g({path:j,type:Pe}),s.push({path:j,size:null,type:"directory",reason:me(Pt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(j),h||!v())break;continue}if(!v())break;if(!q(e.physicalProjectRoot,Z)||Nt(e.physicalNativeRoot,Z))continue;if(g({path:j,type:Pe}),await e.hooks?.afterNode?.(j),!v()||(await b(O),h))break;continue}if(g({path:j,type:Pe}),await e.hooks?.afterNode?.(j),!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
|
|
166
|
+
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):ee(`comet.native.physical-selection.v1
|
|
167
|
+
${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 Mw(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 MA(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!Mw(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 Vw(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function Pw(e,t){let i=(await bc(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Ow.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return ee(`gitlink:${i}`)}async function _w(e,t){let r=await Pw(e,t),i=await OA(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Pw(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function Ya(e,t){if(Tt(t)!==null)return!1;let r=F.resolve(e.projectRoot,...t.split("/"));return!Nt(F.resolve(e.nativeRoot),r)&&!Nt(F.resolve(e.runtimeDir),r)}function VA(e,t){return F.relative(e,t).split(F.sep).join("/")}function WA(e,t){return t.map(r=>F.resolve(e,...r.split(/[\\/]/u)))}function Nt(e,t){let r=F.resolve(e),i=F.resolve(t);return i===r||q(r,i)}function me(e){return RA.has(e.code??"")}function he(e){return e.code==="ENOENT"}function zA(e,t){return ee(`comet.native.snapshot-policy.v1
|
|
168
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Ep(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 GA(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Aw(e){let t=ac(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?GA(n):void 0;if(a&&!a())return!1;let o=Ep(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=Ep(r,c,a),o===null||o.size===0)return!1}return Ep(r,o,a)?.has(r.length)??!1}}function Ww(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ac(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>ac(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=zA(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(Aw),excludeMatchers:r.map(Aw),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 JA(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Iw(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 Sc(e,t,r){let i=JSON.stringify(r);return ee(`${e}
|
|
156
169
|
${Buffer.byteLength(t)}:${t}
|
|
157
|
-
${Buffer.byteLength(i)}:${i}`)}function Vg(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Mg(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!Vg(r))return e.splice(t,1),r}return null}function Tr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function S_(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await ee.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=Ks("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()||!Tr(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()||!Tr(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 et(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Zi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ot(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Wg(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 E_(e,t){let r=et(e,`Native snapshot entry ${t}`);tt(r,YR,`Native snapshot entry ${t}`);let i=Wg(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Ys.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:Ot(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!jg.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function x_(e,t){let r=et(e,`Native snapshot omission ${t}`);if(tt(r,XR,`Native snapshot omission ${t}`),!e_.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!t_.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Wg(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Ot(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function C_(e){let t=et(e,"Native snapshot omission overflow");if(tt(t,QR,"Native snapshot omission overflow"),typeof t.hash!="string"||!Ys.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:Zi(t.count,"Native snapshot omission overflow count")}}function Qi(e,t){let r=et(e,t);if(tt(r,GR,t),typeof r.hash!="string"||!Ys.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=Ot(r.recordCount,`${t} recordCount`),n=Ot(r.storedRecordCount,`${t} storedRecordCount`),a=Ot(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 _g(e){let t=et(e,"Native Git selection evidence");if(tt(t,JR,"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=Qi(t.stageBefore,"Native Git selection stageBefore"),i=Qi(t.combined,"Native Git selection combined"),n=Qi(t.stageAfter,"Native Git selection stageAfter"),a=Qi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Qi(t.finalCombined,"Native Git selection finalCombined"),s=Qi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!$r(r,n)||!$r(n,a)||!$r(i,o)||!$r(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 Ag(e,t){let r=et(e,t);if(tt(r,KR,t),typeof r.hash!="string"||!Ys.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=Ot(r.visitedNodeCount,`${t} visitedNodeCount`),n=Ot(r.recordCount,`${t} recordCount`),a=Ot(r.storedRecordCount,`${t} storedRecordCount`),o=Ot(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 P_(e){let t=et(e,"Native physical selection evidence");if(tt(t,UR,"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=Ag(t.before,"Native physical selection before"),i=Ag(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Fg(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 li(e){let t=et(e,"Native content snapshot manifest");if(tt(t,BR,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!ZR.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=et(t.capture,"Native content snapshot capture");if(tt(w,WR,"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:_g(w.gitSelection),E=w.physicalSelection===void 0?void 0:P_(w.physicalSelection),y=null;if(w.projection!==void 0){let C=et(w.projection,"Native content snapshot projection");if(tt(C,zR,"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:_g(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=et(t.limits,"Native content snapshot limits");tt(i,VR,"Native content snapshot limits");let n={maxFiles:Zi(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Zi(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Zi(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Zi(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Zi(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=et(t.policy,"Native snapshot policy");if(tt(w,MR,"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=Bg({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(E_),s=t.omitted.map(x_),c=Ot(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:C_(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>Vd||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 zg(e,t,r={}){let i=li(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=Tg(r),o=$g(r.gitSelectionLimits),s=await Dg(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(Lg(s).filter(k=>Pa(e,k))),l=[...s.gitlinks].filter(k=>c.has(k)),u=[...s.nestedRepositories].filter(k=>Pa(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 l_(a,n,m),v=i.entries.filter(k=>!f(k.path)&&!p(k.path)&&Pa(e,k.path)&&(c.has(k.path)||!h.has(k.path)));await qg(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)||!Pa(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=Us(N,"git-selection",{source:"git-selection",...s.overflow}));let x=k=>{S+=1,N=Us(N,"omission",k)};for(;b.length>Vd;){let k=Mg(b);if(k===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(k)}return li({...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 R_(e,t){if(!LR.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(K(e,t),"baseline-manifest.json")}async function Jg(e,t={}){let r={maxFiles:t.limits?.maxFiles??zs.maxFiles,maxFileBytes:t.limits?.maxFileBytes??zs.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??zs.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??zs.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=Bg(t.policy),n=Tg({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=$g(t.gitSelectionLimits,t.maxSelectionRecords),o=s_(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 ee.realpath(s),l=F.resolve(e.nativeRoot),u=await ee.realpath(l),d=F.resolve(e.runtimeDir),f=F.resolve(e.configFile),p=F.join(s,".comet","current-change.json"),m=y_(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=Us(x,"omission",_)},C=_=>{if(S+=1,v.length<Vd){v.push(_);return}if(Vg(_)){let A=Mg(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=Us(x,"git-selection",{source:"git-selection",..._})},T=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[V]=h.splice($,1);w-=V.size,g.delete(_),C(A)},Ee=async(_,A,$,V)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let Z;try{Z=await ee.realpath(_)}catch(R){if(!H(n))return;if(!pe(R)&&!fe(R))throw R;C({path:A,size:$.size,type:"file",reason:fe(R)?"changed-during-read":"unreadable"});return}if(!H(n)||!B(c,Z)||mt(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 W,D,ae;try{if(W=await S_(Z,$.size,$,n),W.status==="budget-exhausted"||!H(n))return;if(W.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(ae=await ee.realpath(_),!H(n)))return;D=await ee.lstat(_)}catch(R){if(!H(n))return;if(!pe(R)&&!fe(R))throw R;C({path:A,size:$.size,type:"file",reason:fe(R)?"changed-during-read":"unreadable"});return}if(H(n)){if(W.bytes!==$.size||ae!==Z||!Tr($,W.finalStat)||!Tr(W.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:W.hash,size:D.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:Z,stat:D})}},X=async(_,A,$)=>{if(!H(n))return;let V,Z,W;try{if(V=await ee.readlink(_,{encoding:"buffer"}),!H(n)||(W=await ee.lstat(_),!H(n)))return;Z=await ee.readlink(_,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!pe(R)&&!fe(R))throw R;C({path:A,size:null,type:"other",reason:fe(R)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!W.isSymbolicLink()||!Tr($,W)||W.mtimeMs!==$.mtimeMs||W.ctimeMs!==$.ctimeMs||!V.equals(Z)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=V.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 ae=Ks("sha256").update("symlink\0").update(V).digest("hex");H(n)&&await T({path:A,hash:ae,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:W})},St=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,ae;try{if(D=await ee.realpath(A.target),!H(n))return;ae=await ee.lstat(A.target)}catch(R){if(!H(n))return;if(!pe(R)&&!fe(R))throw R;Y(_,{path:_,size:null,type:"file",reason:pe(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!ae.isFile()||ae.isSymbolicLink()||!Tr(A.stat,ae)||ae.size!==A.stat.size||ae.mtimeMs!==A.stat.mtimeMs||ae.ctimeMs!==A.stat.ctimeMs)&&Y(_,{path:_,size:ae.isFile()?ae.size:null,type:ae.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,ae;try{if(D=await ee.lstat(A.target),!H(n))return;ae=await ee.readlink(A.target,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!pe(R)&&!fe(R))throw R;Y(_,{path:_,size:null,type:"other",reason:pe(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Tr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ae))&&Y(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,V;try{if($=await ee.realpath(A.target),!H(n))return;V=await ee.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&&V.isDirectory()&&!V.isSymbolicLink()&&Tr(A.stat,V)&&B(c,$)&&!mt(u,$))){Y(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let W;try{if(!H(n))return;W=await Cg(n,$)}catch(D){if(en(D))throw D;Y(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;W.dirty?Y(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):W.hash!==A.hash&&Y(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await ee.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(fe($))continue;if(!pe($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},ne=await Dg(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(ne===null){let _=await Eg({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||g.has(V.path))continue;if(ht(n)<1)break;if(!Rg(i,V.path,n))continue;if(ht(n)<1)break;let Z=F.resolve(s,...V.path.split("/")),W;try{W=await ee.lstat(Z)}catch(D){if(!H(n))break;if(!pe(D)&&!fe(D))throw D;C({path:V.path,size:null,type:"file",reason:fe(D)?"changed-during-read":"unreadable"});continue}if(ht(n)<1)break;if(V.type==="symlink"&&W.isSymbolicLink()){if(await X(Z,V.path,W),ht(n)<1)break;continue}if(V.type!=="file"||!W.isFile()||W.isSymbolicLink()){C({path:V.path,size:W.isFile()?W.size:null,type:W.isDirectory()?"directory":W.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Ee(Z,V.path,W),ht(n)<1)break}ht(n)>=1&&await St();let A=await Eg({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=g_(_.evidence,A.evidence);E=$.evidence;for(let V of[..._.omissions,...A.omissions,...$.omissions])v.some(Z=>Z.path===V.path&&Z.reason===V.reason)||C(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let R=li(_);for(let te of R.entries)te.gitObjectId!==void 0&&A.set(te.path,te);$=A.size>0}let V=new Set,Z=!0;try{let R=await Ra(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 te of R.records){let oe=Gs(te),xe=oe.indexOf(" "),be=xe<0?null:tn(oe.slice(xe+1));if(xe!==1||be===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");oe[0]!=="H"&&V.add(be)}}catch(R){if(en(R))throw R;$=!1,Z=!1,A.clear()}let W=new Set;try{let R=await Js(n,s,["ls-files","--modified","-z"],Bd);for(let te of R.toString("utf8").split("\0")){let oe=tn(te);oe!==null&&W.add(oe)}}catch{$=!1,Z=!1,A.clear()}let D=new Set,ae=new Set;for(let R of Lg(ne)){if(g.has(R)||!Pa(e,R))continue;if(ht(n)<1)break;if(!Rg(i,R,n))continue;if(ht(n)<1)break;let te=F.resolve(s,...R.split("/"));if(te===f||te===p||mt(d,te)||m.some(Ve=>mt(Ve,te)))continue;if(ne.gitlinks.has(R)){if(h.length>=r.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Ve,mo;try{[Ve,mo]=await Promise.all([ee.realpath(te),ee.lstat(te)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(mo.isSymbolicLink()||!mo.isDirectory()||!B(c,Ve)||mt(u,Ve)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ki=await Cg(n,Ve);if(ki.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await T({path:R,hash:ki.hash,size:0,type:"file"},{kind:"gitlink",target:te,realTarget:Ve,stat:mo,hash:ki.hash})}catch(ki){if(en(ki))throw ki;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let oe;try{oe=await ee.lstat(te)}catch(Ve){if(fe(Ve)&&ne.tracked.has(R)){b.set(R,te);continue}if(!pe(Ve)&&!fe(Ve))throw Ve;C({path:R,size:null,type:"file",reason:fe(Ve)?"changed-during-read":"unreadable"});continue}if(oe.isSymbolicLink()){await X(te,R,oe);continue}if(!oe.isFile()){ne.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let xe=ne.trackedObjectIds.get(R),be=xe?A.get(R):void 0;if($&&be?.gitObjectId!==void 0&&be.gitObjectId===xe&&!V.has(R)&&!W.has(R)){if(h.length>=r.maxFiles){C({path:R,size:be.size,type:"file",reason:"file-count"});continue}if(be.size>r.maxFileBytes){C({path:R,size:be.size,type:"file",reason:"file-size"});continue}if(w+be.size>r.maxTotalBytes){C({path:R,size:be.size,type:"file",reason:"total-size"});continue}h.push({...be}),w+=be.size,D.add(R);continue}let Ip=Z&&!V.has(R)&&!W.has(R)?xe:void 0;await Ee(te,R,oe,Ip),Ip!==void 0&&ae.add(R)}if(await St(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await qg(n,e,a,ne,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&ae.size>0){let R=await Js(n,s,["ls-files","--modified","-z"],Bd),te=new Set;for(let oe of R.toString("utf8").split("\0")){let xe=tn(oe);xe!==null&&te.add(xe)}for(let oe of D){if(!te.has(oe))continue;let xe=h.find(be=>be.path===oe);Y(oe,{path:oe,size:xe?.size??null,type:"file",reason:"changed-during-read"})}for(let oe of ae){if(!te.has(oe))continue;let xe=h.find(be=>be.path===oe);xe&&delete xe.gitObjectId}}for(let R of ne.omissions)C(R);ne.overflow&&O(ne.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let Jb=ne===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...ne.evidence?{gitSelection:ne.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Jb,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 zd(e,t,r={}){let n=(await Pe(e.projectRoot))?.native.snapshot??vd;return Jg(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 Xs(e,t){let r=R_(e,t),i=ve(e,r);await U(i,r);try{let n=await gg({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return li(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var zs,Vd,LR,BR,VR,MR,WR,zR,JR,GR,UR,KR,YR,XR,QR,ZR,e_,t_,Ys,jg,r_,rn,Bd,i_,n_,a_,Md,o_,m_,nn=I(()=>{"use strict";ce();Me();$t();Rt();G();pt();aa();zs={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Vd=1e3,LR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BR=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),VR=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),MR=new Set(["schema","include","exclude","hash"]),WR=new Set(["provider","gitSelection","physicalSelection","projection"]),zR=new Set(["provider","selection"]),JR=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),GR=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),UR=new Set(["schema","status","before","after"]),KR=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),YR=new Set(["path","hash","size","type","gitObjectId"]),XR=new Set(["path","size","type","reason"]),QR=new Set(["ref","hash","count"]),ZR=new Set(["change-created","legacy-migration","explicit"]),e_=new Set(["file","directory","other"]),t_=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"]),Ys=/^[a-f0-9]{64}$/u,jg=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,r_=new Set(["EACCES","EPERM"]),rn=64*1024,Bd=64*1024,i_=6e4,n_=1e3,a_=2,Md={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},o_={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};m_=(1n<<256n)-1n});function Iw(){AA+=1}var AA,jw=I(()=>{"use strict";AA=0});import{execFileSync as IA}from"node:child_process";function $A(e,t){Iw();try{return IA("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:jA,maxBuffer:TA,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new of(e,t,i)}}function We(e,t){return $A(e,t).trim()}var jA,TA,of,wt=I(()=>{"use strict";jw();jA=3e4,TA=8*1024*1024,of=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 MA}from"node:fs";import WA from"node:path";function vc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function mc(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 Fw(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 YA(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 Lw(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 Ww(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===ff&&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=>!Bw(e.children,l)),Vw(i)?i:null}if(e.schema===fi&&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=>!Bw(e.children,a)),Vw(i)?i:null}return null}function Bw(e,t){return e.some(r=>r.covers.includes(t))}function Vw(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function qr(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 XA(e){let t=vc(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=vc(n,`Native children acceptance_index.${i}`);if(mc(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 QA(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 zw(e,t,r={}){let i=(0,Mw.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=vc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==fi&&a!==Dr)throw mc(n,qw,"Native children contract"),new Error(`Native children schema must be ${fi} or ${Dr}`);let o=a===fi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(mc(n,o==="indexed-v2"?JA:qw,"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=vc(f,`Native child ${p}`);if(mc(m,o==="indexed-v2"?KA:o==="summary-v2"?UA:GA,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!zA.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:Fw(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Fw(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(", ")}`)}YA(c);let d=r.policy==="advisory";if(a===ff){if(o==="indexed-v2"){let f=XA(n.acceptance_index);d||QA(f,t,r);let p=Object.keys(f);return d||Lw(c,p,p),{schema:Dr,acceptance_index:f,children:c}}return{schema:Dr,children:c}}return t&&!d&&Lw(c,t),{schema:fi,children:c}}async function Ht(e){let t=WA.join(e.changeDir,df);try{await MA.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await re({root:e.changeDir,ref:df}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=zw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Ww(a,e.acceptanceIds,e.validation??{}):null}}var Mw,df,fi,Dr,ff,zA,qw,JA,GA,UA,KA,gc=I(()=>{"use strict";Mw=Bt(Ct(),1);Xe();df="children.yaml",fi="comet.native.children.v1",Dr="comet.native.children.v2",ff=Dr,zA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qw=new Set(["schema","children"]),JA=new Set(["schema","acceptance_index","children"]),GA=new Set(["name","depends_on","covers"]),UA=new Set(["name","summary","depends_on"]),KA=new Set(["name","depends_on","covers"])});var wc,pf=I(()=>{"use strict";wc=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 Fa=I(()=>{"use strict"});var yc=I(()=>{"use strict";pf();Fa()});function er(e,t){if(!eI.test(e))throw new Error(`${t} must be a Git commit`)}function hf(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function bc(e){er(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:mf(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:La,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 mf(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 eI,La,Nc,pi=I(()=>{"use strict";se();yc();eI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;La="comet.native.supervisor.v2",Nc=3});import Ba from"node:path";import{promises as Gw}from"node:fs";function vf(e,t){return Ba.join(dt(e,t),"supervisor")}function Va(e,t){return Ba.join(vf(e,t),"state.json")}function Uw(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!==La)throw new Error(`Native Supervisor state schema must be ${La}`);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(er(t.integration.targetCommit,"Native Supervisor target commit"),er(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");er(n.candidateCommit,"Native Supervisor integration candidate commit"),er(n.integrationCommit,"Native Supervisor integration check commit"),Jw(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&&er(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(er(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&&Jw(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 ze(e,t,r={}){try{let i=await Gw.readFile(Va(e,t),"utf8"),n=JSON.parse(i);if(Uw(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(()=>(ft(),Td)),c=await s(Ba.join(o.changesDir,t,"comet-state.yaml")),l=await Ht({changeDir:Ba.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:qr(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=mf(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(()=>(ft(),Td)),s=await o(Ba.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 Fr(e,t){Uw(t),await Gw.mkdir(e.changesRuntimeDir,{recursive:!0}),await He(Va(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Jw(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 Lr=I(()=>{"use strict";ce();se();gc();G();pi()});var gf=I(()=>{"use strict"});function it(e){return e.replace(tI,"$1 [REDACTED]").replace(rI,"[REDACTED PRIVATE KEY]").replace(iI,"$1[REDACTED]@").replace(nI,"[REDACTED TOKEN]").replace(aI,'$1"[REDACTED]"').replace(oI,"$1$2$1$3$4[REDACTED]$4").replace(sI,"$1$2[REDACTED]")}var tI,rI,iI,nI,aI,oI,sI,hi=I(()=>{"use strict";tI=/\b(Bearer|Basic)\s+[^\s"']+/giu,rI=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,iI=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,nI=/\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,aI=/("(?:[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,oI=/(["'])((?:[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,sI=/\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 XV,constants as QV,createWriteStream as ZV,existsSync as eM,promises as tM,statSync as uI}from"node:fs";import mi from"node:path";function dI(e,t){let r=mi.relative(e,t);return r===""||!mi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${mi.sep}`)}function Kw(e,t){if(t.length===0||t.includes("\\")||mi.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||mi.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=mi.resolve(e),i=mi.resolve(r,...t.split("/"));if(!dI(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=uI(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 Sc=I(()=>{"use strict";Is();gf();hi()});var Yw=I(()=>{"use strict";wt();Sc();se()});var Ec=I(()=>{"use strict";wt();ce()});import{createHash as ly}from"node:crypto";import ry from"path";function ke(e,t){return e<t?-1:e>t?1:0}function Sf(e){if(!Cf.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function LI(e,t){return e===t?0:e===null?-1:t===null?1:ke(e,t)}function Vr(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=ry.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||ry.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function fy(e,t){return e==="."?e:Vr(e,t)}function pn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function BI(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:Vr(e.path,`${t} path`),hash:e.hash,size:pn(e.size,`${t} size`),type:"file"}}function VI(e,t){return{path:fy(e.path,`${t} path`),size:e.size===null?null:pn(e.size,`${t} size`),type:e.type,reason:e.reason}}function MI(e,t){return ke(e.path,t.path)||ke(e.hash,t.hash)||e.size-t.size}function WI(e,t){return ke(e.path,t.path)||ke(e.reason,t.reason)||ke(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ja(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
158
|
-
`,"utf8")}function
|
|
159
|
-
${
|
|
160
|
-
`),e.omissionOverflow&&
|
|
161
|
-
`);let r=0;Pf(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Br(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Ua(o,n.path)&&(a+=1,Br(t,"change-attribution",o));Br(t,"change-end",{attributionCount:a}),a===0&&Br(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&&Br(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function wy(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=KI(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=>Ua(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=j(Wa,e),c=j(Wa,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>=FI)break;l.push(tr({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=[...ny("baseline",e),...ny("current",t),...o.totalChanges===0&&a===null?[tr({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(ne=>ne.attributedTo.length===0&&!u.has(ne.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,T=d-k.detailedOmissionCount,Y=O+T,Ee=[...y.map(ne=>tr({kind:"unattributed-change",source:"implementation-scope",path:ne.path,evidence:{after:ne.after,before:ne.before,changeKind:ne.kind}},`Changed path is not covered by a declared artifact: ${ne.path}`)),...l.slice(0,k.detailedOmissionCount),...f,...Y>0?[gy(k.overflowHash,{changes:C,unattributed:O,unresolved:Y})]:[]],X=GI(Ee),St=k.includeGitAdvisory?p():void 0;return{schema:kf,contractHash:i,baselineProjectionRef:Sf(s),baselineProjectionHash:s,currentProjectionRef:Sf(c),currentProjectionHash:c,complete:X.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:X,noCodeReason:a,...St?{gitAdvisory:St}:{},...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(Ja({...k,scopeHash:b})<=gi)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?XI({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(dy,x)};if(Ja(w)>gi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function _f(e){let t=Ef(e.baseline),r=Ef(e.current),i=vy(e);return{authority:i,baseline:t,current:r,scope:wy(t,r,i)}}function Dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qt(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 vi(e,t){if(typeof e!="string"||!Cf.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function oy(e,t,r){let i=Sf(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function Pc(e,t){let r=Dt(e,"Native snapshot projection");if(qt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==uy)throw new Error("Native snapshot projection schema is invalid");let i=li({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=Ef(i);if(j(Wa,r)!==j(Wa,n))throw new Error("Native snapshot projection is not canonical");let a=j(Wa,n);if(t!==void 0&&vi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Af(e,t){let r=Dt(e,`Declared artifact ${t}`);if(qt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Vr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function sy(e,t){if(e===null)return null;let r=Dt(e,t);return qt(r,["hash","size"],[],t),{hash:vi(r.hash,`${t} hash`),size:pn(r.size,`${t} size`)}}function cy(e,t){let r=Dt(e,`Implementation change ${t}`);if(qt(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(Af),n=Ga(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=sy(r.before,`Implementation change ${t} before`),o=sy(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:Vr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function ZI(e,t){let r=Dt(e,`Unresolved scope ${t}`);qt(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"?fy(r.path,`Unresolved scope ${t} path`):Vr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function za(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)=>Vr(n,`${t} ${a}`)),i=[...new Set(r)].sort(ke);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function yy(e){let t=Dt(e,"Native implementation external drift");if(qt(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=za(t.paths,"Native external drift paths");return my({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Rc(e){let t=Dt(e,"Native implementation scope"),r=[...QI].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(qt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==kf)throw new Error("Native implementation scope schema is invalid");let i=vi(t.contractHash,"Implementation scope contractHash"),n=vi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=oy(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=vi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=oy(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(Af);if(JSON.stringify(c)!==JSON.stringify(Ga(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(cy),u=[...l].sort((y,C)=>ke(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=>Ua(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(cy),p=t.externalDrift===void 0?void 0:yy(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(ZI),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:YI(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=>tr({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?[tr({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(xf))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(xf))||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=Dt(t.gitAdvisory,"Implementation scope Git advisory");if(qt(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=za(y.changedPaths,"Git changed paths"),O=za(y.pathsPresentInSnapshotChanges,"Git present paths"),T=za(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Y=[...O,...T].sort(ke);if(JSON.stringify(Y)!==JSON.stringify(C)||T.some(Ee=>l.some(X=>X.path===Ee)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let k={schema:kf,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=vi(t.scopeHash,"Implementation scope scopeHash");if(j(dy,k)!==E)throw new Error("Implementation scope content hash mismatch");return{...k,scopeHash:E}}function ej(e){let t=Dt(e,"Native implementation scope authority");if(qt(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(Af);if(JSON.stringify(r)!==JSON.stringify(Ga(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=za(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:yy(t.externalDrift),a=vy({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 Ka(e){let t=Dt(e,"Native implementation scope bundle");qt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=ej(t.authority),i=Pc(t.baseline),n=Pc(t.current),a=Rc(t.scope),o=wy(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 Ny(e){let t=Rc(e.scope);return Ka({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 kf,uy,Wa,dy,OI,HI,DI,Cf,gi,qI,FI,QI,wi=I(()=>{"use strict";se();nn();kf="comet.native.implementation-scope.v2",uy="comet.native.content-snapshot-projection.v1",Wa="comet.native.content-snapshot-projection.v1",dy="comet.native.implementation-scope.v2",OI="comet.native.unresolved-scope-id.v1",HI="comet.native.scope-detail-overflow.v1",DI="comet.native.snapshot-projection-overflow.v2",Cf=/^[a-f0-9]{64}$/u,gi=1024*1024,qI=128,FI=128;QI=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import by from"node:path";function rr(e,t){if(!Sy.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ey(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function xy(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 If(e,t,r=2e3){let i=it(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Ya(e,t){let r=by.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})||by.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 nj(e,t,r){let i=Ya(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Pt(i),a=i.toLowerCase(),o=r?Ya(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 jf(e){let t=Ya(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 hn(e,t){return e<t?-1:e>t?1:0}function _c(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ac(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 Cy(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 ky(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 aj(e){let t=_c(e,"Native acceptance trace");if(Ac(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"||!Sy.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=Ya(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=_c(o,`Native acceptance trace entry ${s}`);if(Ac(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=>jf(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(hn))||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:Ya(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:If(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>hn(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=rr(t.traceHash,"Native acceptance trace hash");if(j(tj,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Py(e){let t=_c(e,"Native partial allowance");if(Ac(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(hn))||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:xy(t.change),scopeHash:rr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:If(t.reason,"Partial allowance reason"),confirmedSummary:If(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ey(t.sourceRevision),confirmedAt:Cy(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=rr(t.allowanceHash,"Native partial allowance hash");if(j(rj,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Tf(e){let t=_c(e,"Native verification evidence");if(Ac(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=rr(t.implementationScopeHash,"Native verification implementation scope hash"),i=aj(t.acceptanceTrace),n=rr(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:rr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>jf(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(hn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(hn);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=>jf(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(hn)))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:xy(t.change),sourceRevision:Ey(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:rr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:ky(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:nj(t.reportRef,"Native verification report ref"),reportHash:rr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:ky(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Cy(t.createdAt,"Native verification timestamp")},d=rr(t.envelopeHash,"Native verification envelope hash");if(j(ij,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var Sy,tj,rj,ij,Ic=I(()=>{"use strict";se();hi();aa();wi();Sy=/^[a-f0-9]{64}$/u,tj="comet.native.acceptance-trace.v2",rj="comet.native.partial-allowance.v1",ij="comet.native.verification-evidence.v2"});import Ry from"node:path";function Mr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wr(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 ir(e,t){if(typeof e!="string"||!sj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Je(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function $y(e,t){let r=Je(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function jy(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 hj(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>dj||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=Ry.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Ry.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function mj(e){let t=Mr(e,"Native check receipt checker");Wr(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Mr(t.limits,"Native check receipt limits");if(Wr(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==mn||t.version!==$f||t.hash!==Ay||r.maxFiles!==Le.maxFiles||r.maxFileBytes!==Le.maxFileBytes||r.maxTotalBytes!==Le.maxTotalBytes||r.maxIssues!==Le.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:mn,version:$f,hash:Ay,limits:{...Le}}}function vj(e){let t=Mr(e,"Native check receipt contract");return Wr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:ir(t.expectedHash,"Native check expected contract hash"),beforeHash:ir(t.beforeHash,"Native check before contract hash"),afterHash:ir(t.afterHash,"Native check after contract hash")}}function gj(e){let t=Mr(e,"Native check receipt implementation");return Wr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:ir(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:ir(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:ir(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:ir(t.afterSnapshotHash,"Native check after snapshot hash")}}function wj(e,t){let r=Mr(e,`Native check batch ${t}`);Wr(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Je(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Je(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Je(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Je(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Je(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Je(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Le.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Le.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function yj(e){let t=Mr(e,"Native check receipt counts");Wr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Je(t.filesSelected,"Native check filesSelected"),filesScanned:Je(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Je(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Je(t.bytesScanned,"Native check bytesScanned"),issueCount:Je(t.issueCount,"Native check issueCount"),recordedIssueCount:Je(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(wj):(()=>{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>Le.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Le.maxFiles||r.bytesScanned>Le.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function Nj(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Iy.indexOf(e.kind)-Iy.indexOf(t.kind)}function bj(e){if(!Array.isArray(e)||e.length>Le.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Mr(i,`Native check issue ${n}`);if(Wr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!fj.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:hj(a.path,`Native check issue ${n} path`),line:$y(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(Nj);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function kj(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!pj.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=Ty.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 Sj(e){return j(uj,e)}function Oy(e){let t=Mr(e,"Native check receipt");if(Wr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==_y)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!cj.test(t.change))throw new Error("Native check receipt change name is invalid");let r=$y(t.sourceRevision,"Native check source revision"),i=mj(t.checker),n=vj(t.contract),a=gj(t.implementation),o=Sj({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(ir(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=jy(t.startedAt,"Native check receipt startedAt"),c=jy(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=yj(t.counts),u=bj(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=kj(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>Le.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>Le.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:_y,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=ir(t.receiptHash,"Native check receipt content hash");if(j(oj,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var _y,oj,mn,$f,Le,sj,cj,lj,uj,dj,Ay,fj,Iy,Ty,pj,Of=I(()=>{"use strict";se();_y="comet.native.check-receipt.v1",oj="comet.native.check-receipt.v1",mn="scoped-text-safety",$f=1,Le=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),sj=/^[a-f0-9]{64}$/u,cj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lj="comet.native.checker-policy.v1",uj="comet.native.check-input.v1",dj=2048,Ay=j(lj,{policy:mn,version:$f,limits:Le,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),fj=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Iy=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Ty=["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"],pj=new Set(Ty)});function vn(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 zr(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 nr(e,t){if(typeof e!="string"||!Cj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function bt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=it(e).trim();if(!r||r.length>Aj||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Hf(e,t){let r=bt(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 Xa(e,t,r=bt,i=!1,n=Ij){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 Tj(e,t){if(typeof e!="string"||!Pj.test(e))throw new Error(`${t} is invalid`);return e}function $j(e){let t=vn(e,"Native verification receipt bindings");if(zr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Rj.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:nr(t.contractHash,"Native verification receipt contract hash"),scopeHash:nr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:nr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:nr(t.artifactHash,"Native verification receipt artifact hash")}}function Oj(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=_j.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function Hj(e,t,r,i){let n=vn(t,`Native ${e} evidence`);if(e==="automated-check"){if(zr(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=Hf(n.startedAt,"Native automated-check start time"),o=Hf(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=vn(n.worktree,"Native automated-check worktree");if(zr(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=vn(n.afterFence,"Native automated-check after fence");if(zr(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:bt(n.executable,"Native automated-check executable"),args:Xa(n.args,"Native automated-check arguments",bt,!0),cwd:bt(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:bt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:nr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:nr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:nr(n.outputHash,"Native automated-check output hash"),outputSummary:bt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){zr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=Oj(n.checkReceiptRef);if(nr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Xa(n.subjects,"Native static inspection subjects",bt,i==="required-check"),rule:bt(n.rule,"Native static inspection rule"),resultSummary:bt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return zr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Xa(n.steps,"Native manual evidence steps"),observations:Xa(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function Dj(e){let t=vn(e,"Native verification receipt");if(zr(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=bt(t.actor,"Native verification receipt actor"),o=Xa(t.acceptanceIds,"Native receipt acceptance IDs",Tj,i==="required-check",jj).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:Df,kind:r,role:i,status:n,bindings:$j(t.bindings),acceptanceIds:o,actor:a,issuedAt:Hf(t.issuedAt,"Native verification receipt issue time"),evidence:Hj(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==mn||s.actor!==`native-runtime:${mn}`))throw new Error("Native required check policy identity is invalid");return s}function Hy(e){let t=vn(e,"Native verification receipt");if(zr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Df)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=Dj(i),a=nr(t.receiptHash,"Native verification receipt hash");if(j(Ej,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function qf(e){return j(xj,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Df,Ej,xj,Cj,Pj,Rj,_j,Aj,Ij,jj,Qa=I(()=>{"use strict";se();Of();hi();Df="comet.native.verification-receipt.v3",Ej=Df,xj="comet.native.declared-artifacts.v1",Cj=/^[a-f0-9]{64}$/u,Pj=/^acceptance-[a-f0-9]{64}$/u,Rj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_j=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Aj=4096,Ij=256,jj=1024});import{createHash as qj}from"node:crypto";import{promises as kt}from"node:fs";import Ft from"node:path";function Ff(e,t){let r=Ft.relative(e,t);return r===""||!Ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ft.sep}`)}function Fj(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function jc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Dy(e){let t=await kt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await kt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Lj(e,t){let r=Ft.resolve(e),i=Ft.resolve(t);if(!Ff(r,i))throw new Error("Native evidence path is outside its change");let n=[await Dy(r)],a=r;for(let o of Ft.relative(r,i).split(Ft.sep).filter(Boolean)){a=Ft.join(a,o);let s=await Dy(a);if(!Ff(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function qy(e){for(let t of e){let r=await kt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Fj(t,r)||await kt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function Bj(e,t,r={}){let i=await Lj(t,Ft.dirname(e));await r.afterParentChainCaptured?.();let n=await kt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await kt.realpath(e);if(!Ff(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await kt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),kt.lstat(e),kt.realpath(e)]);if(await qy(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!jc(s,n)||!jc(s,c))throw new Error("Native evidence document changed while opening");if(s.size>gn)throw new Error(`Native evidence document exceeds ${gn} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=gn+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>gn)throw new Error(`Native evidence document exceeds ${gn} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),kt.lstat(e),kt.realpath(e)]);if(await qy(i),!m.isFile()||m.isSymbolicLink()||h!==a||!jc(s,p)||!jc(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 By(e,t){if(!Ly.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function Vj(e,t,r,i,n){if(!Ly.test(r))throw new Error("Native report evidence hash is invalid");let a=await yi({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"||qj("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 wn(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 Mj(e,t,r,i,n){let a=By(r,i);return n?Ft.join(n,...a.split("/")):Pr(K(e,t),a)}async function yi(e){let t=Mj(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??ve(e.paths,t);return await U(r,t),Bj(t,r,e.hooks)}function Fy(e,t){return Pc(e,t)}function Wj(e,t){let r=Rc(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function zj(e,t,r){let i=Py(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Jj(e,t,r){let i=Tf(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function Gj(e,t,r,i=!1,n){let a=await Tc(e,t,r.implementationScopeRef,void 0,n);if(i&&await Vj(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 Vy(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 Za(e,t,r,i,n){let a=wn(r,"scopes"),o=Wj(await yi({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=wn(o.baselineProjectionRef,"snapshots"),c=wn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([yi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Fy(d,s)),yi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Fy(d,c))]);return Ny({baseline:l,current:u,scope:o})}async function Tc(e,t,r,i,n){return(await Za(e,t,r,i,n)).scope}async function Vy(e,t,r,i,n){let a=wn(r,"allowances");return zj(await yi({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function eo(e,t,r,i,n){let a=wn(r,"receipts"),o=Hy(await yi({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 yn(e,t,r,i,n){let a=wn(r,"verifications"),o=Jj(await yi({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Gj(e,t,o,!1,n),o}var Ly,gn,CW,Jr=I(()=>{"use strict";ce();G();Rt();wi();Ic();Qa();Ly=/^[a-f0-9]{64}$/u,gn=gi,CW=3*gn});import sr from"node:path";import{realpathSync as AO}from"node:fs";import{execFileSync as ek}from"child_process";import tk from"fs";import lr from"path";function Si(e,t){return ek("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Pn(e,t){return jp(e)===jp(t)}function jp(e){let t=lr.resolve(e);try{let r=tk.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function he(e){try{let t=lr.resolve(Si(e,["rev-parse","--show-toplevel"])),i=Si(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?lr.resolve(i.slice(9)):t,a=null;try{a=Si(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Pn(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function go(e){try{Si(e,["rev-parse","--is-inside-work-tree"]);let t=Si(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:lr.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 ur(e){return go(e).map(t=>t.root)}function nl(e,t){let r=t.find(a=>Pn(lr.resolve(a.root),lr.resolve(e)));if(!r)return null;let i=lr.resolve(t[0].root),n=lr.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Pn(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Vt(e,t){try{let r=Si(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}se();var ef=Bt(Ct(),1);import{promises as pw}from"fs";import Or from"path";Xe();ce();ri();Me();Ne();G();pt();nn();import{createHash as Z_}from"crypto";import eA from"path";var rt=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"});Ne();G();import{constants as Zs,promises as vt}from"node:fs";import gt from"node:path";import{TextDecoder as U_}from"node:util";import W_ from"path";Li();Sr();var $_=Bt(Ct(),1);Li();Sr();xr();xr();Fi();cd();Li();xr();var OF=4*1024*1024;var O_=null;function H_(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Gg(e,t){return(...r)=>{let i=O_;if(i===null)return t(...r);let n=H_(`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}}Fi();var LF=Gg("hookWritePolicy",async e=>(await nd(e))?.hook??{allow_paths:[]});da();import D_ from"node:path";var Qs="comet.selection.v2",Kg=16*1024;function Jd(e){return D_.join(e,".comet","current-change.json")}function q_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ug(e){return e===null||typeof e=="string"}function F_(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(!q_(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&&!Ug(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Qs,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Qs)throw new Error(`current change selection schema must be ${Qs}`);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(!Ug(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 Gd(e){let t;try{let i=Jd(e),{bytes:n}=await Di(i,Kg,{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",...F_(t)}}ad();oa();var Yg=(e,t)=>{let r=e[t];return r==null?null:String(r)};function Aa(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 _a(e,t){let r=Aa(e,t);if(W_.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 z_(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 Xg(e){if(!e.run_id)return null;let t=Aa(e,"run_id"),r=Aa(e,"skill"),i=Aa(e,"skill_version"),n=Aa(e,"skill_hash"),a=_a(e,"pending_ref"),o=_a(e,"trajectory_ref"),s=_a(e,"context_ref"),c=_a(e,"artifacts_ref"),l=_a(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:Yg(e,"current_step"),iteration:u,pending:Yg(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:z_(e)}}var ML=Number.MAX_SAFE_INTEGER;var J_=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function G_(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=Xg(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function Ud(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=>!J_.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 G_(t)}ce();Rt();var an={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 tc(e,t){let r=gt.relative(e,t);return r===""||!gt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${gt.sep}`)}function K_(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ec(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}function Y_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function rc(e,t,r){let i=rt[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=gt.resolve(e),a=gt.resolve(n,...i.slice(8).split("/"));if(!tc(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function Qg(e){let t=await vt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await vt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function X_(e,t){let r=gt.resolve(e),i=gt.resolve(t);if(!tc(r,i))throw new Error("Native Run path is outside its change");let n=[await Qg(r)],a=r;for(let o of gt.relative(r,i).split(gt.sep).filter(Boolean)){a=gt.join(a,o);let s;try{s=await Qg(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!tc(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Zg(e){for(let t of e){let r=await vt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Y_(t,r)||await vt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function Q_(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 ic(e,t,r,i,n){let a=await X_(e,gt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await vt.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=K_(o),c=await vt.realpath(t);if(!tc(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Zs.O_RDONLY:Zs.O_RDONLY|Zs.O_NOFOLLOW|Zs.O_NONBLOCK,u;try{u=await vt.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),vt.lstat(t),vt.realpath(t)]);if(await Zg(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!ec(s,d)||!ec(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await Q_(u,r,i);await n?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([u.stat(),vt.lstat(t),vt.realpath(t)]);if(await Zg(a),!v.isFile()||v.isSymbolicLink()||g!==c||!ec(s,h)||!ec(s,v))throw new Error(`${i} changed while reading`);let b;try{b=new U_("utf-8",{fatal:!0}).decode(m)}catch(S){throw new Error(`${i} is not valid UTF-8`,{cause:S})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function ew(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function Kd(e){return Ud(e)}async function on(e,t){let r=rc(e,"stateRef"),i=await ic(e,r,an.runStateBytes,"Native Run state",t);return i?Ud(ew(i.text,"Native Run state")):null}async function ui(e,t,r){let i=rc(e,"trajectoryRef",t),n=await ic(e,i,an.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>an.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${an.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 tw(e,t,r){return(await ic(e,rc(e,"trajectoryRef",t),an.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function nc(e,t,r){let i=await ic(e,rc(e,"checkpointRef",t),an.checkpointBytes,"Native Run checkpoint",r);return i?ew(i.text,"Native Run checkpoint"):null}var tA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Yd(e){return Z_("sha256").update(e).digest("hex")}function rA(e,t){if(!tA.test(t))throw new Error(`Invalid Native change name: ${t}`);return eA.join(K(e,t),"trajectory.jsonl")}function iA(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 nA(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 aA(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=iA(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(`
|
|
162
|
-
`)])}catch(d){if(!
|
|
163
|
-
${t}`).digest("hex")}async function
|
|
170
|
+
${Buffer.byteLength(i)}:${i}`)}function zw(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Gw(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!zw(r))return e.splice(t,1),r}return null}function qr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function UA(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=Ec("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()||!qr(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()||!qr(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 mn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Jw(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 KA(e,t){let r=it(e,`Native snapshot entry ${t}`);nt(r,bA,`Native snapshot entry ${t}`);let i=Jw(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!xc.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:qt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Ow.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function YA(e,t){let r=it(e,`Native snapshot omission ${t}`);if(nt(r,kA,`Native snapshot omission ${t}`),!xA.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!CA.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Jw(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:qt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function XA(e){let t=it(e,"Native snapshot omission overflow");if(nt(t,SA,"Native snapshot omission overflow"),typeof t.hash!="string"||!xc.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:mn(t.count,"Native snapshot omission overflow count")}}function hn(e,t){let r=it(e,t);if(nt(r,wA,t),typeof r.hash!="string"||!xc.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=qt(r.recordCount,`${t} recordCount`),n=qt(r.storedRecordCount,`${t} storedRecordCount`),a=qt(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 Tw(e){let t=it(e,"Native Git selection evidence");if(nt(t,gA,"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=hn(t.stageBefore,"Native Git selection stageBefore"),i=hn(t.combined,"Native Git selection combined"),n=hn(t.stageAfter,"Native Git selection stageAfter"),a=hn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=hn(t.finalCombined,"Native Git selection finalCombined"),s=hn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Mr(r,n)||!Mr(n,a)||!Mr(i,o)||!Mr(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 jw(e,t){let r=it(e,t);if(nt(r,NA,t),typeof r.hash!="string"||!xc.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=qt(r.visitedNodeCount,`${t} visitedNodeCount`),n=qt(r.recordCount,`${t} recordCount`),a=qt(r.storedRecordCount,`${t} storedRecordCount`),o=qt(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 QA(e){let t=it(e,"Native physical selection evidence");if(nt(t,yA,"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=jw(t.before,"Native physical selection before"),i=jw(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Mw(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 yi(e){let t=it(e,"Native content snapshot manifest");if(nt(t,pA,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!EA.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,mA,"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:Tw(w.gitSelection),E=w.physicalSelection===void 0?void 0:QA(w.physicalSelection),y=null;if(w.projection!==void 0){let C=it(w.projection,"Native content snapshot projection");if(nt(C,vA,"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:Tw(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=it(t.limits,"Native content snapshot limits");nt(i,fA,"Native content snapshot limits");let n={maxFiles:mn(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:mn(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:mn(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:mn(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:mn(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=it(t.policy,"Native snapshot policy");if(nt(w,hA,"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=Ww({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(KA),s=t.omitted.map(YA),c=qt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:XA(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>Cp||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 Uw(e,t,r={}){let i=yi(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=Hw(r),o=Dw(r.gitSelectionLimits),s=await Lw(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(Vw(s).filter(S=>Ya(e,S))),l=[...s.gitlinks].filter(S=>c.has(S)),u=[...s.nestedRepositories].filter(S=>Ya(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 $A(a,n,m),v=i.entries.filter(S=>!p(S.path)&&!f(S.path)&&Ya(e,S.path)&&(c.has(S.path)||!h.has(S.path)));await qw(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)||!Ya(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=Sc(N,"git-selection",{source:"git-selection",...s.overflow}));let x=S=>{k+=1,N=Sc(N,"omission",S)};for(;b.length>Cp;){let S=Gw(b);if(S===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(S)}return yi({...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 ZA(e,t){if(!dA.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(Y(e,t),"baseline-manifest.json")}async function Kw(e,t={}){let r={maxFiles:t.limits?.maxFiles??Nc.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Nc.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Nc.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Nc.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=Ww(t.policy),n=Hw({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Dw(t.gitSelectionLimits,t.maxSelectionRecords),o=TA(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),p=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),m=WA(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=Sc(x,"omission",_)},C=_=>{if(k+=1,v.length<Cp){v.push(_);return}if(zw(_)){let A=Gw(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=Sc(x,"git-selection",{source:"git-selection",..._})},j=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[V]=h.splice($,1);w-=V.size,g.delete(_),C(A)},Pe=async(_,A,$,V)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let te;try{te=await re.realpath(_)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:$.size,type:"file",reason:he(P)?"changed-during-read":"unreadable"});return}if(!H(n)||!q(c,te)||Nt(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 z,D,ce;try{if(z=await UA(te,$.size,$,n),z.status==="budget-exhausted"||!H(n))return;if(z.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(ce=await re.realpath(_),!H(n)))return;D=await re.lstat(_)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:$.size,type:"file",reason:he(P)?"changed-during-read":"unreadable"});return}if(H(n)){if(z.bytes!==$.size||ce!==te||!qr($,z.finalStat)||!qr(z.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:z.hash,size:D.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:te,stat:D})}},Z=async(_,A,$)=>{if(!H(n))return;let V,te,z;try{if(V=await re.readlink(_,{encoding:"buffer"}),!H(n)||(z=await re.lstat(_),!H(n)))return;te=await re.readlink(_,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;C({path:A,size:null,type:"other",reason:he(P)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!z.isSymbolicLink()||!qr($,z)||z.mtimeMs!==$.mtimeMs||z.ctimeMs!==$.ctimeMs||!V.equals(te)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=V.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 ce=Ec("sha256").update("symlink\0").update(V).digest("hex");H(n)&&await j({path:A,hash:ce,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:z})},Pt=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,ce;try{if(D=await re.realpath(A.target),!H(n))return;ce=await re.lstat(A.target)}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;Q(_,{path:_,size:null,type:"file",reason:me(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!ce.isFile()||ce.isSymbolicLink()||!qr(A.stat,ce)||ce.size!==A.stat.size||ce.mtimeMs!==A.stat.mtimeMs||ce.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ce.isFile()?ce.size:null,type:ce.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,ce;try{if(D=await re.lstat(A.target),!H(n))return;ce=await re.readlink(A.target,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!me(P)&&!he(P))throw P;Q(_,{path:_,size:null,type:"other",reason:me(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!qr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ce))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,V;try{if($=await re.realpath(A.target),!H(n))return;V=await re.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&&V.isDirectory()&&!V.isSymbolicLink()&&qr(A.stat,V)&&q(c,$)&&!Nt(u,$))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let z;try{if(!H(n))return;z=await _w(n,$)}catch(D){if(vn(D))throw D;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;z.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):z.hash!==A.hash&&Q(_,{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"})}}},se=await Lw(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(se===null){let _=await Rw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||g.has(V.path))continue;if(yt(n)<1)break;if(!Iw(i,V.path,n))continue;if(yt(n)<1)break;let te=F.resolve(s,...V.path.split("/")),z;try{z=await re.lstat(te)}catch(D){if(!H(n))break;if(!me(D)&&!he(D))throw D;C({path:V.path,size:null,type:"file",reason:he(D)?"changed-during-read":"unreadable"});continue}if(yt(n)<1)break;if(V.type==="symlink"&&z.isSymbolicLink()){if(await Z(te,V.path,z),yt(n)<1)break;continue}if(V.type!=="file"||!z.isFile()||z.isSymbolicLink()){C({path:V.path,size:z.isFile()?z.size:null,type:z.isDirectory()?"directory":z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Pe(te,V.path,z),yt(n)<1)break}yt(n)>=1&&await Pt();let A=await Rw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=MA(_.evidence,A.evidence);E=$.evidence;for(let V of[..._.omissions,...A.omissions,...$.omissions])v.some(te=>te.path===V.path&&te.reason===V.reason)||C(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let P=yi(_);for(let ie of P.entries)ie.gitObjectId!==void 0&&A.set(ie.path,ie);$=A.size>0}let V=new Set,te=!0;try{let P=await Xa(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 ie of P.records){let le=kc(ie),_e=le.indexOf(" "),Ee=_e<0?null:gn(le.slice(_e+1));if(_e!==1||Ee===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");le[0]!=="H"&&V.add(Ee)}}catch(P){if(vn(P))throw P;$=!1,te=!1,A.clear()}let z=new Set;try{let P=await bc(n,s,["ls-files","--modified","-z"],xp);for(let ie of P.toString("utf8").split("\0")){let le=gn(ie);le!==null&&z.add(le)}}catch{$=!1,te=!1,A.clear()}let D=new Set,ce=new Set;for(let P of Vw(se)){if(g.has(P)||!Ya(e,P))continue;if(yt(n)<1)break;if(!Iw(i,P,n))continue;if(yt(n)<1)break;let ie=F.resolve(s,...P.split("/"));if(ie===p||ie===f||Nt(d,ie)||m.some(Ge=>Nt(Ge,ie)))continue;if(se.gitlinks.has(P)){if(h.length>=r.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Ge,Wo;try{[Ge,Wo]=await Promise.all([re.realpath(ie),re.lstat(ie)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Wo.isSymbolicLink()||!Wo.isDirectory()||!q(c,Ge)||Nt(u,Ge)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Oi=await _w(n,Ge);if(Oi.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await j({path:P,hash:Oi.hash,size:0,type:"file"},{kind:"gitlink",target:ie,realTarget:Ge,stat:Wo,hash:Oi.hash})}catch(Oi){if(vn(Oi))throw Oi;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let le;try{le=await re.lstat(ie)}catch(Ge){if(he(Ge)&&se.tracked.has(P)){b.set(P,ie);continue}if(!me(Ge)&&!he(Ge))throw Ge;C({path:P,size:null,type:"file",reason:he(Ge)?"changed-during-read":"unreadable"});continue}if(le.isSymbolicLink()){await Z(ie,P,le);continue}if(!le.isFile()){se.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let _e=se.trackedObjectIds.get(P),Ee=_e?A.get(P):void 0;if($&&Ee?.gitObjectId!==void 0&&Ee.gitObjectId===_e&&!V.has(P)&&!z.has(P)){if(h.length>=r.maxFiles){C({path:P,size:Ee.size,type:"file",reason:"file-count"});continue}if(Ee.size>r.maxFileBytes){C({path:P,size:Ee.size,type:"file",reason:"file-size"});continue}if(w+Ee.size>r.maxTotalBytes){C({path:P,size:Ee.size,type:"file",reason:"total-size"});continue}h.push({...Ee}),w+=Ee.size,D.add(P);continue}let Rh=te&&!V.has(P)&&!z.has(P)?_e:void 0;await Pe(ie,P,le,Rh),Rh!==void 0&&ce.add(P)}if(await Pt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await qw(n,e,a,se,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&ce.size>0){let P=await bc(n,s,["ls-files","--modified","-z"],xp),ie=new Set;for(let le of P.toString("utf8").split("\0")){let _e=gn(le);_e!==null&&ie.add(_e)}for(let le of D){if(!ie.has(le))continue;let _e=h.find(Ee=>Ee.path===le);Q(le,{path:le,size:_e?.size??null,type:"file",reason:"changed-during-read"})}for(let le of ce){if(!ie.has(le))continue;let _e=h.find(Ee=>Ee.path===le);_e&&delete _e.gitObjectId}}for(let P of se.omissions)C(P);se.overflow&&O(se.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let lS=se===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...se.evidence?{gitSelection:se.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:lS,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 _p(e,t,r={}){let n=(await Te(e.projectRoot))?.native.snapshot??Yd;return Kw(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 Cc(e,t){let r=ZA(e,t),i=we(e,r);await K(i,r);try{let n=await yw({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return yi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var Nc,Cp,dA,pA,fA,hA,mA,vA,gA,wA,yA,NA,bA,kA,SA,EA,xA,CA,xc,Ow,RA,wn,xp,PA,_A,AA,Rp,IA,LA,yn=I(()=>{"use strict";Hi();ae();Je();Lt();jt();U();wt();Ra();Nc={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Cp=1e3,dA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,pA=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),fA=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),hA=new Set(["schema","include","exclude","hash"]),mA=new Set(["provider","gitSelection","physicalSelection","projection"]),vA=new Set(["provider","selection"]),gA=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),wA=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),yA=new Set(["schema","status","before","after"]),NA=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),bA=new Set(["path","hash","size","type","gitObjectId"]),kA=new Set(["path","size","type","reason"]),SA=new Set(["ref","hash","count"]),EA=new Set(["change-created","legacy-migration","explicit"]),xA=new Set(["file","directory","other"]),CA=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"]),xc=/^[a-f0-9]{64}$/u,Ow=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,RA=new Set(["EACCES","EPERM"]),wn=64*1024,xp=64*1024,PA=6e4,_A=1e3,AA=2,Rp={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},IA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};LA=(1n<<256n)-1n});import{execFileSync as iT}from"node:child_process";function oT(e,t){try{return zn(()=>iT("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:nT,maxBuffer:aT,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Wp(e,t,i)}}function Ve(e,t){return oT(e,t).trim()}var nT,aT,Wp,ot=I(()=>{"use strict";Hi();nT=3e4,aT=8*1024*1024,Wp=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 pj}from"node:fs";import fj from"node:path";function Yc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Kc(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 tN(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 yj(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 rN(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 oN(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===uf&&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=>!iN(e.children,l)),nN(i)?i:null}if(e.schema===xi&&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=>!iN(e.children,a)),nN(i)?i:null}return null}function iN(e,t){return e.some(r=>r.covers.includes(t))}function nN(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Jr(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 Nj(e){let t=Yc(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=Yc(n,`Native children acceptance_index.${i}`);if(Kc(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 bj(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 sN(e,t,r={}){let i=(0,aN.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Yc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==xi&&a!==Gr)throw Kc(n,eN,"Native children contract"),new Error(`Native children schema must be ${xi} or ${Gr}`);let o=a===xi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Kc(n,o==="indexed-v2"?mj:eN,"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=Yc(p,`Native child ${f}`);if(Kc(m,o==="indexed-v2"?wj:o==="summary-v2"?gj:vj,`Native ${s} child fields (child ${f})`),typeof m.name!="string"||!hj.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:tN(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?tN(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(", ")}`)}yj(c);let d=r.policy==="advisory";if(a===uf){if(o==="indexed-v2"){let p=Nj(n.acceptance_index);d||bj(p,t,r);let f=Object.keys(p);return d||rN(c,f,f),{schema:Gr,acceptance_index:p,children:c}}return{schema:Gr,children:c}}return t&&!d&&rN(c,t),{schema:xi,children:c}}async function Vt(e){let t=fj.join(e.changeDir,lf);try{await pj.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ne({root:e.changeDir,ref:lf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=sN(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?oN(a,e.acceptanceIds,e.validation??{}):null}}var aN,lf,xi,Gr,uf,hj,eN,mj,vj,gj,wj,Xc=I(()=>{"use strict";aN=Kt(It(),1);et();lf="children.yaml",xi="comet.native.children.v1",Gr="comet.native.children.v2",uf=Gr,hj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eN=new Set(["schema","children"]),mj=new Set(["schema","acceptance_index","children"]),vj=new Set(["name","depends_on","covers"]),gj=new Set(["name","summary","depends_on"]),wj=new Set(["name","depends_on","covers"])});var ho=I(()=>{"use strict"});var Qc=I(()=>{"use strict";uc();ho()});function lr(e,t){if(!Sj.test(e))throw new Error(`${t} must be a Git commit`)}function df(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function el(e){lr(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:pf(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:mo,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 pf(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 tl(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 Sj,mo,Zc,Ci=I(()=>{"use strict";ue();Qc();Sj=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;mo="comet.native.supervisor.v2",Zc=3});import vo from"node:path";import{promises as lN}from"node:fs";function ff(e,t){return vo.join(vt(e,t),"supervisor")}function go(e,t){return vo.join(ff(e,t),"state.json")}function uN(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!==mo)throw new Error(`Native Supervisor state schema must be ${mo}`);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(lr(t.integration.targetCommit,"Native Supervisor target commit"),lr(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");lr(n.candidateCommit,"Native Supervisor integration candidate commit"),lr(n.integrationCommit,"Native Supervisor integration check commit"),cN(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&&lr(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(lr(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&&cN(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 Ue(e,t,r={}){try{let i=await lN.readFile(go(e,t),"utf8"),n=JSON.parse(i);if(uN(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(()=>(gt(),gp)),c=await s(vo.join(o.changesDir,t,"comet-state.yaml")),l=await Vt({changeDir:vo.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Jr(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=pf(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(()=>(gt(),gp)),s=await o(vo.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 Ur(e,t){uN(t),await lN.mkdir(e.changesRuntimeDir,{recursive:!0}),await Ie(go(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function cN(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 Kr=I(()=>{"use strict";ae();ue();Xc();U();Ci()});var hf=I(()=>{"use strict"});function ct(e){return e.replace(Ej,"$1 [REDACTED]").replace(xj,"[REDACTED PRIVATE KEY]").replace(Cj,"$1[REDACTED]@").replace(Rj,"[REDACTED TOKEN]").replace(Pj,'$1"[REDACTED]"').replace(_j,"$1$2$1$3$4[REDACTED]$4").replace(Aj,"$1$2[REDACTED]")}var Ej,xj,Cj,Rj,Pj,_j,Aj,Ri=I(()=>{"use strict";Ej=/\b(Bearer|Basic)\s+[^\s"']+/giu,xj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Cj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Rj=/\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,Pj=/("(?:[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,_j=/(["'])((?:[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,Aj=/\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 rz,constants as iz,createWriteStream as nz,existsSync as az,promises as oz,statSync as jj}from"node:fs";import Pi from"node:path";function $j(e,t){let r=Pi.relative(e,t);return r===""||!Pi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pi.sep}`)}function dN(e,t){if(t.length===0||t.includes("\\")||Pi.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Pi.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Pi.resolve(e),i=Pi.resolve(r,...t.split("/"));if(!$j(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=jj(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 rl=I(()=>{"use strict";Gn();hf();Ri()});var pN=I(()=>{"use strict";ot();rl();ue()});var il=I(()=>{"use strict";ot();ae()});import{createHash as xN}from"node:crypto";import wN from"path";function Ce(e,t){return e<t?-1:e>t?1:0}function Nf(e){if(!Sf.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function l$(e,t){return e===t?0:e===null?-1:t===null?1:Ce(e,t)}function Xr(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=wN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||wN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function PN(e,t){return e==="."?e:Xr(e,t)}function An(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function u$(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:Xr(e.path,`${t} path`),hash:e.hash,size:An(e.size,`${t} size`),type:"file"}}function d$(e,t){return{path:PN(e.path,`${t} path`),size:e.size===null?null:An(e.size,`${t} size`),type:e.type,reason:e.reason}}function p$(e,t){return Ce(e.path,t.path)||Ce(e.hash,t.hash)||e.size-t.size}function f$(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 bo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
171
|
+
`,"utf8")}function Yr(e,t,r){let i=`${t}
|
|
172
|
+
${Yn(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function h$(e){if(bo(e)<=Ai)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=xN("sha256");a.update(`${o$}
|
|
173
|
+
`),e.omissionOverflow&&Yr(a,"existing-overflow",e.omissionOverflow);let o=(p,f)=>{f||(i+=1),n+=1,Yr(a,"omission",p)},s=p=>{i+=1,n+=1,Yr(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(;bo(u)>Ai;){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 bf(e){let t=yi(e),r=t.entries.map((n,a)=>u$(n,`Snapshot entry ${a}`));if(r.sort(p$),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)=>d$(n,`Snapshot omission ${a}`));return i.sort(f$),h$({schema:CN,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 ko(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:Xr(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)=>Ce(r.path,i.path)||Ce(r.kind,i.kind))}function So(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function yN(e){return e?{hash:e.hash,size:e.size}:null}function Ef(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:Ce(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:yN(c),after:yN(l)})}}function _N(e,t){return{...e,attributedTo:t.filter(r=>So(r,e.path))}}function xf(e){let t=ko(e.declaredArtifacts),r=[];return Ef(e.baseline,e.current,i=>{r.push(_N(i,t))}),r}function ur(e,t){return{id:`scope:${T(n$,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function m$(e,t){let r=t.omitted.map(i=>ur({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(ur({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(ur({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 NN(e,t){return m$(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function kf(e,t){return Ce(e.kind,t.kind)||Ce(e.source,t.source)||l$(e.path,t.path)||Ce(e.id,t.id)}function v$(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(kf)}function AN(e){return[...new Set(e.map((t,r)=>Xr(t,`Git path ${r}`)))].sort(Ce)}function bN(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 g$(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 IN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=AN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:bN(e.baseCommit,"Native external drift base commit"),targetBranch:g$(e.targetBranch,"Native external drift target branch"),targetCommit:bN(e.targetCommit,"Native external drift target commit"),paths:t}}function TN(e){if(typeof e.contractHash!="string"||!Sf.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ko(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:AN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:IN(e.externalDrift)}}}function w$(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 Ef(e,t,f=>{let m=r.some(h=>So(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<s$){let h=_N(f,r),v=bo(h);l+v<=Ai?(a.push(h),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:p}}function jN(e,t){return ur({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 y$(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:An(Number(t[1]),"Scope overflow change count"),unresolved:An(Number(t[2]),"Scope overflow unresolved count"),unattributed:An(Number(t[3]),"Scope overflow unattributed count")},i=_i(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(jN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function N$(e){let t=xN("sha256");t.update(`${a$}
|
|
174
|
+
`);let r=0;Ef(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Yr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)So(o,n.path)&&(a+=1,Yr(t,"change-attribution",o));Yr(t,"change-end",{attributionCount:a}),a===0&&Yr(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&&Yr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function $N(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=w$(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=>So(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=T(yo,e),c=T(yo,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>=c$)break;l.push(ur({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=[...NN("baseline",e),...NN("current",t),...o.totalChanges===0&&a===null?[ur({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(se=>se.attributedTo.length===0&&!u.has(se.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,j=d-S.detailedOmissionCount,Q=O+j,Pe=[...y.map(se=>ur({kind:"unattributed-change",source:"implementation-scope",path:se.path,evidence:{after:se.after,before:se.before,changeKind:se.kind}},`Changed path is not covered by a declared artifact: ${se.path}`)),...l.slice(0,S.detailedOmissionCount),...p,...Q>0?[jN(S.overflowHash,{changes:C,unattributed:O,unresolved:Q})]:[]],Z=v$(Pe),Pt=S.includeGitAdvisory?f():void 0;return{schema:yf,contractHash:i,baselineProjectionRef:Nf(s),baselineProjectionHash:s,currentProjectionRef:Nf(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:Z,noCodeReason:a,...Pt?{gitAdvisory:Pt}:{},...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(bo({...S,scopeHash:b})<=Ai)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?N$({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(RN,x)};if(bo(w)>Ai)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function Cf(e){let t=bf(e.baseline),r=bf(e.current),i=TN(e);return{authority:i,baseline:t,current:r,scope:$N(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 _i(e,t){if(typeof e!="string"||!Sf.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kN(e,t,r){let i=Nf(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function ol(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!==CN)throw new Error("Native snapshot projection schema is invalid");let i=yi({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=bf(i);if(T(yo,r)!==T(yo,n))throw new Error("Native snapshot projection is not canonical");let a=T(yo,n);if(t!==void 0&&_i(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Rf(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:Xr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function SN(e,t){if(e===null)return null;let r=Wt(e,t);return zt(r,["hash","size"],[],t),{hash:_i(r.hash,`${t} hash`),size:An(r.size,`${t} size`)}}function EN(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(Rf),n=ko(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=SN(r.before,`Implementation change ${t} before`),o=SN(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:Xr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function k$(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"?PN(r.path,`Unresolved scope ${t} path`):Xr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function No(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)=>Xr(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 ON(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=No(t.paths,"Native external drift paths");return IN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function sl(e){let t=Wt(e,"Native implementation scope"),r=[...b$].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(zt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==yf)throw new Error("Native implementation scope schema is invalid");let i=_i(t.contractHash,"Implementation scope contractHash"),n=_i(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=kN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=_i(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=kN(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(Rf);if(JSON.stringify(c)!==JSON.stringify(ko(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(EN),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=>So(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(EN),f=t.externalDrift===void 0?void 0:ON(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(k$),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:y$(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=>ur({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?[ur({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(kf))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(kf))||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=No(y.changedPaths,"Git changed paths"),O=No(y.pathsPresentInSnapshotChanges,"Git present paths"),j=No(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Q=[...O,...j].sort(Ce);if(JSON.stringify(Q)!==JSON.stringify(C)||j.some(Pe=>l.some(Z=>Z.path===Pe)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:j}}let S={schema:yf,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=_i(t.scopeHash,"Implementation scope scopeHash");if(T(RN,S)!==E)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:E}}function S$(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(Rf);if(JSON.stringify(r)!==JSON.stringify(ko(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=No(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:ON(t.externalDrift),a=TN({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 Eo(e){let t=Wt(e,"Native implementation scope bundle");zt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=S$(t.authority),i=ol(t.baseline),n=ol(t.current),a=sl(t.scope),o=$N(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 HN(e){let t=sl(e.scope);return Eo({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 yf,CN,yo,RN,n$,a$,o$,Sf,Ai,s$,c$,b$,Ii=I(()=>{"use strict";ue();yn();yf="comet.native.implementation-scope.v2",CN="comet.native.content-snapshot-projection.v1",yo="comet.native.content-snapshot-projection.v1",RN="comet.native.implementation-scope.v2",n$="comet.native.unresolved-scope-id.v1",a$="comet.native.scope-detail-overflow.v1",o$="comet.native.snapshot-projection-overflow.v2",Sf=/^[a-f0-9]{64}$/u,Ai=1024*1024,s$=128,c$=128;b$=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import DN from"node:path";function dr(e,t){if(!FN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function LN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function qN(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 Pf(e,t,r=2e3){let i=ct(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function xo(e,t){let r=DN.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})||DN.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 R$(e,t,r){let i=xo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Tt(i),a=i.toLowerCase(),o=r?xo(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 _f(e){let t=xo(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 In(e,t){return e<t?-1:e>t?1:0}function cl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ll(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 MN(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 BN(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 P$(e){let t=cl(e,"Native acceptance trace");if(ll(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"||!FN.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=xo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=cl(o,`Native acceptance trace entry ${s}`);if(ll(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=>_f(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(In))||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:xo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Pf(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>In(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=dr(t.traceHash,"Native acceptance trace hash");if(T(E$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function VN(e){let t=cl(e,"Native partial allowance");if(ll(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(In))||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:qN(t.change),scopeHash:dr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Pf(t.reason,"Partial allowance reason"),confirmedSummary:Pf(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:LN(t.sourceRevision),confirmedAt:MN(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=dr(t.allowanceHash,"Native partial allowance hash");if(T(x$,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Af(e){let t=cl(e,"Native verification evidence");if(ll(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=dr(t.implementationScopeHash,"Native verification implementation scope hash"),i=P$(t.acceptanceTrace),n=dr(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:dr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>_f(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(In)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(In);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=>_f(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(In)))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:qN(t.change),sourceRevision:LN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:dr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:BN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:R$(t.reportRef,"Native verification report ref"),reportHash:dr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:BN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:MN(t.createdAt,"Native verification timestamp")},d=dr(t.envelopeHash,"Native verification envelope hash");if(T(C$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var FN,E$,x$,C$,ul=I(()=>{"use strict";ue();Ri();Ra();Ii();FN=/^[a-f0-9]{64}$/u,E$="comet.native.acceptance-trace.v2",x$="comet.native.partial-allowance.v1",C$="comet.native.verification-evidence.v2"});import WN from"node:path";function Qr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zr(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 pr(e,t){if(typeof e!="string"||!A$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ke(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function YN(e,t){let r=Ke(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function UN(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 D$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>$$||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=WN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||WN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function B$(e){let t=Qr(e,"Native check receipt checker");Zr(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Qr(t.limits,"Native check receipt limits");if(Zr(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Tn||t.version!==If||t.hash!==GN||r.maxFiles!==We.maxFiles||r.maxFileBytes!==We.maxFileBytes||r.maxTotalBytes!==We.maxTotalBytes||r.maxIssues!==We.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Tn,version:If,hash:GN,limits:{...We}}}function F$(e){let t=Qr(e,"Native check receipt contract");return Zr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:pr(t.expectedHash,"Native check expected contract hash"),beforeHash:pr(t.beforeHash,"Native check before contract hash"),afterHash:pr(t.afterHash,"Native check after contract hash")}}function L$(e){let t=Qr(e,"Native check receipt implementation");return Zr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:pr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:pr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:pr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:pr(t.afterSnapshotHash,"Native check after snapshot hash")}}function q$(e,t){let r=Qr(e,`Native check batch ${t}`);Zr(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Ke(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Ke(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Ke(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Ke(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Ke(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Ke(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>We.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>We.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function M$(e){let t=Qr(e,"Native check receipt counts");Zr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Ke(t.filesSelected,"Native check filesSelected"),filesScanned:Ke(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ke(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ke(t.bytesScanned,"Native check bytesScanned"),issueCount:Ke(t.issueCount,"Native check issueCount"),recordedIssueCount:Ke(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(q$):(()=>{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>We.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>We.maxFiles||r.bytesScanned>We.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function V$(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||JN.indexOf(e.kind)-JN.indexOf(t.kind)}function W$(e){if(!Array.isArray(e)||e.length>We.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Qr(i,`Native check issue ${n}`);if(Zr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!O$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:D$(a.path,`Native check issue ${n} path`),line:YN(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(V$);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function z$(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!H$.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=KN.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 G$(e){return T(j$,e)}function XN(e){let t=Qr(e,"Native check receipt");if(Zr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==zN)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!I$.test(t.change))throw new Error("Native check receipt change name is invalid");let r=YN(t.sourceRevision,"Native check source revision"),i=B$(t.checker),n=F$(t.contract),a=L$(t.implementation),o=G$({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(pr(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=UN(t.startedAt,"Native check receipt startedAt"),c=UN(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=M$(t.counts),u=W$(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=z$(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>We.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>We.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:zN,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=pr(t.receiptHash,"Native check receipt content hash");if(T(_$,f)!==m)throw new Error("Native check receipt content hash mismatch");return{...f,receiptHash:m}}var zN,_$,Tn,If,We,A$,I$,T$,j$,$$,GN,O$,JN,KN,H$,Tf=I(()=>{"use strict";ue();zN="comet.native.check-receipt.v1",_$="comet.native.check-receipt.v1",Tn="scoped-text-safety",If=1,We=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),A$=/^[a-f0-9]{64}$/u,I$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,T$="comet.native.checker-policy.v1",j$="comet.native.check-input.v1",$$=2048,GN=T(T$,{policy:Tn,version:If,limits:We,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),O$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),JN=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],KN=["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"],H$=new Set(KN)});function jn(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 ei(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 fr(e,t){if(typeof e!="string"||!K$.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=ct(e).trim();if(!r||r.length>Z$||r!==e.trim())throw new Error(`${t} is invalid`);return r}function jf(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 Co(e,t,r=Ct,i=!1,n=e0){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 r0(e,t){if(typeof e!="string"||!Y$.test(e))throw new Error(`${t} is invalid`);return e}function i0(e){let t=jn(e,"Native verification receipt bindings");if(ei(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!X$.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:fr(t.contractHash,"Native verification receipt contract hash"),scopeHash:fr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:fr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:fr(t.artifactHash,"Native verification receipt artifact hash")}}function n0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Q$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function a0(e,t,r,i){let n=jn(t,`Native ${e} evidence`);if(e==="automated-check"){if(ei(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=jf(n.startedAt,"Native automated-check start time"),o=jf(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=jn(n.worktree,"Native automated-check worktree");if(ei(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=jn(n.afterFence,"Native automated-check after fence");if(ei(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:Co(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:fr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:fr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:fr(n.outputHash,"Native automated-check output hash"),outputSummary:Ct(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){ei(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=n0(n.checkReceiptRef);if(fr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Co(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 ei(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Co(n.steps,"Native manual evidence steps"),observations:Co(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function o0(e){let t=jn(e,"Native verification receipt");if(ei(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=Co(t.acceptanceIds,"Native receipt acceptance IDs",r0,i==="required-check",t0).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:$f,kind:r,role:i,status:n,bindings:i0(t.bindings),acceptanceIds:o,actor:a,issuedAt:jf(t.issuedAt,"Native verification receipt issue time"),evidence:a0(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Tn||s.actor!==`native-runtime:${Tn}`))throw new Error("Native required check policy identity is invalid");return s}function QN(e){let t=jn(e,"Native verification receipt");if(ei(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==$f)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=o0(i),a=fr(t.receiptHash,"Native verification receipt hash");if(T(J$,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Of(e){return T(U$,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var $f,J$,U$,K$,Y$,X$,Q$,Z$,e0,t0,Ro=I(()=>{"use strict";ue();Tf();Ri();$f="comet.native.verification-receipt.v3",J$=$f,U$="comet.native.declared-artifacts.v1",K$=/^[a-f0-9]{64}$/u,Y$=/^acceptance-[a-f0-9]{64}$/u,X$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Q$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Z$=4096,e0=256,t0=1024});import{createHash as s0}from"node:crypto";import{promises as Rt}from"node:fs";import Gt from"node:path";function Hf(e,t){let r=Gt.relative(e,t);return r===""||!Gt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Gt.sep}`)}function c0(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function dl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ZN(e){let t=await Rt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Rt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function l0(e,t){let r=Gt.resolve(e),i=Gt.resolve(t);if(!Hf(r,i))throw new Error("Native evidence path is outside its change");let n=[await ZN(r)],a=r;for(let o of Gt.relative(r,i).split(Gt.sep).filter(Boolean)){a=Gt.join(a,o);let s=await ZN(a);if(!Hf(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function eb(e){for(let t of e){let r=await Rt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!c0(t,r)||await Rt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function u0(e,t,r={}){let i=await l0(t,Gt.dirname(e));await r.afterParentChainCaptured?.();let n=await Rt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Rt.realpath(e);if(!Hf(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Rt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Rt.lstat(e),Rt.realpath(e)]);if(await eb(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!dl(s,n)||!dl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>$n)throw new Error(`Native evidence document exceeds ${$n} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=$n+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>$n)throw new Error(`Native evidence document exceeds ${$n} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,m,h]=await Promise.all([o.stat(),Rt.lstat(e),Rt.realpath(e)]);if(await eb(i),!m.isFile()||m.isSymbolicLink()||h!==a||!dl(s,f)||!dl(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 ib(e,t){if(!rb.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function d0(e,t,r,i,n){if(!rb.test(r))throw new Error("Native report evidence hash is invalid");let a=await Ti({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"||s0("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 On(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 p0(e,t,r,i,n){let a=ib(r,i);return n?Gt.join(n,...a.split("/")):Or(Y(e,t),a)}async function Ti(e){let t=p0(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??we(e.paths,t);return await K(r,t),u0(t,r,e.hooks)}function tb(e,t){return ol(e,t)}function f0(e,t){let r=sl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function h0(e,t,r){let i=VN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function m0(e,t,r){let i=Af(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function v0(e,t,r,i=!1,n){let a=await pl(e,t,r.implementationScopeRef,void 0,n);if(i&&await d0(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 nb(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 Po(e,t,r,i,n){let a=On(r,"scopes"),o=f0(await Ti({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=On(o.baselineProjectionRef,"snapshots"),c=On(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ti({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>tb(d,s)),Ti({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>tb(d,c))]);return HN({baseline:l,current:u,scope:o})}async function pl(e,t,r,i,n){return(await Po(e,t,r,i,n)).scope}async function nb(e,t,r,i,n){let a=On(r,"allowances");return h0(await Ti({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function _o(e,t,r,i,n){let a=On(r,"receipts"),o=QN(await Ti({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 Hn(e,t,r,i,n){let a=On(r,"verifications"),o=m0(await Ti({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await v0(e,t,o,!1,n),o}var rb,$n,TG,ti=I(()=>{"use strict";ae();U();jt();Ii();ul();Ro();rb=/^[a-f0-9]{64}$/u,$n=Ai,TG=3*$n});import vr from"node:path";import{realpathSync as eD}from"node:fs";Hi();Di();import{execFileSync as SS}from"child_process";import ES from"fs";import ni from"path";import{AsyncLocalStorage as Ih}from"node:async_hooks";Gn();var ai=new Ih,Th=new Ih;function jh(e){return ai.getStore()?e():ai.run(new Map,e)}function xS(e){let t=ai.getStore();for(let r of e)t?.set(wr(r.root),e);return e}function Jn(e,t){return zn(()=>SS("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Un(e,t){return wr(e)===wr(t)}function wr(e){let t=ni.resolve(e);try{let r=ES.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ve(e){try{let t=Th.getStore()?.get(wr(e)),r=ai.getStore()?.get(t??wr(e));if(r){let c=Kn(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=ni.resolve(Jn(e,["rev-parse","--show-toplevel"])),n=ai.getStore()?.get(wr(i))??$h(e),a=Kn(i,n);if(ai.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Jn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Un(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Go(e){try{let t=ai.getStore()?.get(Th.getStore()?.get(wr(e))??wr(e));return t?t.map(r=>({...r})):(Jn(e,["rev-parse","--is-inside-work-tree"]),$h(e))}catch{return[]}}function $h(e){let t=CS(Jn(e,["worktree","list","--porcelain","-z"]));return xS(t),t.map(r=>({...r}))}function CS(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:ni.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}function yr(e){return Go(e).map(t=>t.root)}function Kn(e,t){let r=t.find(a=>Un(ni.resolve(a.root),ni.resolve(e)));if(!r)return null;let i=ni.resolve(t[0].root),n=ni.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Un(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Yt(e,t){try{let r=Jn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ue();var Bp=Kt(It(),1);import{promises as vy}from"fs";import Vr from"path";et();ae();pi();Je();Se();U();wt();yn();import{createHash as CI}from"crypto";import RI 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"});Se();U();import{constants as Pc,promises as bt}from"node:fs";import kt from"node:path";import{TextDecoder as bI}from"node:util";import gI from"path";en();Tr();var aI=Kt(It(),1);en();Tr();er();er();Zi();Md();en();er();var A1=4*1024*1024;import{AsyncLocalStorage as oI}from"node:async_hooks";var sI=new oI;function cI(){let e=sI.getStore();return e?.active?e:null}function lI(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Yw(e,t){return(...r)=>{let i=cI();if(i===null)return t(...r);let n=lI(`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}}Zi();var H1=Yw("hookWritePolicy",async e=>(await Bd(e))?.hook??{allow_paths:[]});ja();import uI from"node:path";var Rc="comet.selection.v2",Qw=16*1024;function Ap(e){return uI.join(e,".comet","current-change.json")}function dI(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xw(e){return e===null||typeof e=="string"}function pI(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(!dI(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&&!Xw(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Rc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Rc)throw new Error(`current change selection schema must be ${Rc}`);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(!Xw(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 Ip(e){let t;try{let i=Ap(e),{bytes:n}=await Xi(i,Qw,{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",...pI(t)}}Fd();Pa();var Zw=(e,t)=>{let r=e[t];return r==null?null:String(r)};function Za(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 Qa(e,t){let r=Za(e,t);if(gI.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 wI(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 ey(e){if(!e.run_id)return null;let t=Za(e,"run_id"),r=Za(e,"skill"),i=Za(e,"skill_version"),n=Za(e,"skill_hash"),a=Qa(e,"pending_ref"),o=Qa(e,"trajectory_ref"),s=Qa(e,"context_ref"),c=Qa(e,"artifacts_ref"),l=Qa(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:Zw(e,"current_step"),iteration:u,pending:Zw(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:wI(e)}}var FM=Number.MAX_SAFE_INTEGER;var yI=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function NI(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=ey(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function Tp(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=>!yI.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 NI(t)}ae();jt();var Nn={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 Ac(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function kI(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function _c(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 SI(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ic(e,t,r){let i=at[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=kt.resolve(e),a=kt.resolve(n,...i.slice(8).split("/"));if(!Ac(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function ty(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run 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 EI(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!Ac(r,i))throw new Error("Native Run path is outside its change");let n=[await ty(r)],a=r;for(let o of kt.relative(r,i).split(kt.sep).filter(Boolean)){a=kt.join(a,o);let s;try{s=await ty(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ac(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function ry(e){for(let t of e){let r=await bt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!SI(t,r)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function xI(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 Tc(e,t,r,i,n){let a=await EI(e,kt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await bt.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=kI(o),c=await bt.realpath(t);if(!Ac(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Pc.O_RDONLY:Pc.O_RDONLY|Pc.O_NOFOLLOW|Pc.O_NONBLOCK,u;try{u=await bt.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,p,f]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await ry(a),!d.isFile()||!p.isFile()||p.isSymbolicLink()||f!==c||!_c(s,d)||!_c(s,p))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await xI(u,r,i);await n?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await ry(a),!v.isFile()||v.isSymbolicLink()||g!==c||!_c(s,h)||!_c(s,v))throw new Error(`${i} changed while reading`);let b;try{b=new bI("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 iy(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function jp(e){return Tp(e)}async function bn(e,t){let r=Ic(e,"stateRef"),i=await Tc(e,r,Nn.runStateBytes,"Native Run state",t);return i?Tp(iy(i.text,"Native Run state")):null}async function Ni(e,t,r){let i=Ic(e,"trajectoryRef",t),n=await Tc(e,i,Nn.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>Nn.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Nn.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 ny(e,t,r){return(await Tc(e,Ic(e,"trajectoryRef",t),Nn.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function jc(e,t,r){let i=await Tc(e,Ic(e,"checkpointRef",t),Nn.checkpointBytes,"Native Run checkpoint",r);return i?iy(i.text,"Native Run checkpoint"):null}var PI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function $p(e){return CI("sha256").update(e).digest("hex")}function _I(e,t){if(!PI.test(t))throw new Error(`Invalid Native change name: ${t}`);return RI.join(Y(e,t),"trajectory.jsonl")}function AI(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 II(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 TI(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=AI(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(`
|
|
175
|
+
`)])}catch(d){if(!II(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:$p(t),targetHash:$p(l),tailHash:$p(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function jI(e,t){let r=_I(e,t);await K(we(e,r),r);let i=Y(e,t),n=await ny(i,at.trajectoryRef);return n===null?{status:"clean",file:r}:TI(r,Buffer.from(n))}async function ay(e,t){let r=await jI(e,t);return"inspection"in r?r.inspection:r}import{createHash as $I}from"node:crypto";import{promises as $c}from"node:fs";import ar from"node:path";ae();et();Se();U();var eo=/^[a-f0-9]{64}$/u,oy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,OI=16*1024,Hp=process.platform,HI=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function kn(e){return HI.has(e)}function uy(e,t){let r=ar.relative(e,t);return ar.isAbsolute(r)||r===".."||r.startsWith(`..${ar.sep}`)?null:r.replaceAll("\\","/")||"."}function dy(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function py(e,t){if(e.length===0||dy(e)||e.includes("\\")||ar.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=ar.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Dp(e,t){return $I("sha256").update(`${e}
|
|
176
|
+
${t}`).digest("hex")}async function sy(e,t){let r=await $c.realpath(t),i=await $c.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Hp==="win32"?ar.normalize(r).toLowerCase():r;return Dp(e,`${n}
|
|
164
177
|
${i.dev}
|
|
165
178
|
${i.ino}
|
|
166
|
-
${i.birthtimeMs}`)}async function
|
|
179
|
+
${i.birthtimeMs}`)}async function cy(e,t){let r=await $c.realpath(t),i=await $c.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Hp==="win32"?ar.normalize(r).toLowerCase():r;return Dp(e,n)}function DI(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 Op(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||dy(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function fy(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Op(e.changeBranch,"Native workspace change branch"),Op(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 BI(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"||!oy.test(t.baseCommit)||typeof t.targetCommit!="string"||!oy.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Op(t.targetBranch,"Native workspace Git target branch")}function Oc(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"||!eo.test(String(t.projectRootId))||!eo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");DI(t.capturedAt),py(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&&!eo.test(String(t.projectRootPathId))||a&&!eo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!eo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&BI(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(fy(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 FI(e,t){return ar.join(Y(e,t),"workspace.json")}function LI(e,t){let r=FI(e,t),i=we(e,r),n=uy(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:py(n,"Native workspace file ref")}}async function qI(e,t){try{let r=LI(e,t),i=await ne({root:r.root,ref:r.ref,maxBytes:OI});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function to(e,t){let r=ve(e.projectRoot),i={projectRoot:ar.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await or(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 Sn({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 MI(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=uy(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ve(e.paths.projectRoot),i=r.isGitWorktree?Yt(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Yt(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([sy("comet.native.workspace-project-root.v2",e.paths.projectRoot),sy("comet.native.workspace-native-root.v2",e.paths.nativeRoot),cy("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),cy("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&&fy(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:Dp("comet.native.workspace-session.v2",`${s}
|
|
167
180
|
${c}
|
|
168
|
-
${e.sessionId}`)}:{}},
|
|
169
|
-
`).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
|
|
170
|
-
`).trim()}function
|
|
171
|
-
`))}function PA(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(Cw))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(Cw))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Pw(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Rw(e.markdown)},markdown:e.markdown}}function RA(e,t){return _w(e.id,t.id)}function _w(e,t){return e<t?-1:e>t?1:0}function Aw(e){let t=Pw(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(PA).sort((d,f)=>_w(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=xd(e.briefMarkdown,t,Ha.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...Cd(f,d.source,Ha.maxAcceptanceCriteria-a.length)),a.push(...ag(f,d.source,Ha.maxAcceptanceCriteria-a.length)));if(a.sort(RA),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ha.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ha.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:Rw(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(CA,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(xA,u)}}var _A={maxSpecs:64};async function ln(e){if(e.specChanges.length>_A.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:Aw({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Me();Ne();import{promises as VA}from"node:fs";import lf from"node:path";wt();import{promises as OA}from"node:fs";ce();ka();import Tw from"node:path";function Da(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qa(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 je(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 un(e,t){return e===null?null:je(e,t)}function dn(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 HA(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 DA(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function fn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function sf(e,t){if(e===null)return null;let r=je(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function qA(e,t){let r=je(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function cf(e,t){let r=je(e,t);if(!Tw.isAbsolute(r))throw new Error(`${t} must be absolute`);return Tw.resolve(r)}function FA(e,t){let r=`Native local checks[${t}]`,i=Da(e,r);if(qa(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)=>je(u,`${r}.argv[${d}]`,!0)),a=fn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=sf(i.startedAt,`${r}.startedAt`),s=sf(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=dn(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=Da(i.activeProcess,`${r}.activeProcess`),d=fn(u.status,["starting","running"],`${r}.activeProcess.status`);if(qa(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:dn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:je(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:je(i.id,`${r}.id`),name:je(i.name,`${r}.name`),operationId:je(i.operationId,`${r}.operationId`),status:a,repeatable:DA(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:dn(i.executionCount,`${r}.executionCount`),argv:n,cwd:cf(i.cwd,`${r}.cwd`),exitCode:HA(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:je(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:fn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:je(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function LA(e){let t="Native local execution state",r=Da(e,t);if(qa(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Ds)throw new Error(`Native local execution schema must be ${Ds}`);let i=Da(r.workspace,"Native local workspace");qa(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Da(r.execution,"Native local execution");qa(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=sf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:je(o.operationId,"Native local execution.operationId"),stage:fn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:fn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:un(o.executionId,"Native local execution.executionId"),status:fn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:dn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:qA(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:dn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:je(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(FA);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:Ds,change:je(r.change,"Native local change"),basedOnStateVersion:dn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:un(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:un(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:un(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:un(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:cf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:cf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:un(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:je(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function fc(e){let t;try{t=await OA.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 LA(r)}function $w(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}ft();G();var Ow=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hw="comet-state.yaml",Dw="state.json";function di(e,t){if(!Ow.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=lf.join(e.changesDir,t);if(!B(e.changesDir,r))throw new Error("Native change path escaped");return r}function pc(e,t){return lf.join(di(e,t),Hw)}function Hr(e,t){return lf.join(dt(e,t),Dw)}async function hc(e,t){try{let r=await VA.readFile(pc(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 yt(e,t){return Ar(pc(e,t))}async function uf(e){let t=await yt(e.paths,e.name),r=Hr(e.paths,e.name);try{let i=await fc(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"}}}ce();Xe();se();var ty=Bt(Ct(),1);import{promises as EI}from"node:fs";import Nt from"node:path";wt();Xe();se();Me();G();ft();gc();gc();pi();Lr();wt();Ts();ce();se();Sc();Ne();G();Yw();pi();Lr();Ec();wt();Me();Ec();ma();G();var xc=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function wf(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 bI from"node:path";wt();Me();Ne();pi();Lr();async function Cc(e){let t=wf(e.parent),r=Vt(e.paths.projectRoot,t);if(!r)return null;let i=Vt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=ur(e.paths.projectRoot).map(o=>bI.resolve(o)).find(o=>he(o).currentBranch===t);if(!n)return null;let a=bc({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 hf(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function yf(e,t){let r=Nt.normalize(Nt.resolve(e)),i=Nt.normalize(Nt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function xI(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 CI(e){let t=xI(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 Nf(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return CI(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function bf(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 PI(e){let t=ur(e.projectRoot);t.some(i=>yf(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Nt.resolve(n)))]){let n=await Pe(i);n&&r.push({projectRoot:i,paths:await Gt(i,n.native.artifact_root),parent:yf(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function RI(e,t){let r=Nt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ar(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _I(e,t){let r;try{r=await EI.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=Nt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ar(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function AI(e,t,r){let i=Nt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Nt.sep}`))return null;let n=i.split(Nt.sep).join("/");try{let a=(0,ty.parseDocument)(We(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:qe(a.toJS({mapAsMap:!1}))}catch{return null}}function II(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 ey(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ma(e){let t=Nt.join(e.paths.changesDir,e.state.name),r=await Nf(t),i=null,n;try{n=await Ht({changeDir:t,validation:qr(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 ze(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=bf({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===Dr){let g=await ze(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 Cc({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await Fr(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 PI(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 _I(g,l)){let N={...S,source:g,committedState:AI(g,S.file,b)};u.set(S.state.name,[...u.get(S.state.name)??[],N])}for(let S of l){let N=await RI(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&&ey(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,II(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:T,committedState:Y})=>yf(T.projectRoot,w.projectRoot)&&Y?.name===O&&ey(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")}}ft();si();Fa();yc();Ne();Pd();gd();ft();si();ce();ri();Fa();G();ri();Jr();Me();var My=Bt(Ct(),1);xr();var RW=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 $W=256*1024;ft();si();Lr();var Xj=Ns("en");Me();Ne();pi();Lr();ft();si();wt();Ts();se();Sc();import Nn from"node:path";Ne();si();G();function eT(e,t){let r=Nn.relative(Nn.resolve(e),Nn.resolve(t));if(Nn.isAbsolute(r)||r===".."||r.startsWith(`..${Nn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Nn.sep).join("/");return Kw(e,i),i}function Gy(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:eT(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var u2=1024*1024*1024;Ne();yc();Fa();Lr();Ne();Lr();Ne();$d();var eG=16*1024;async function Uy(e){let t=await Gd(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Ji(t.selection.change),t.selection)}G();async function Ky(e,t){let r=[],i=K(e,t.name),n=Pr(i,rt.stateRef),a;try{a=await on(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=Pr(i,a.trajectoryRef),s=await rw(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 ui(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=Pr(i,a.checkpointRef);try{let u=await nc(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}nn();import bT from"path";import{isDeepStrictEqual as Uf}from"util";ce();$t();ma();Ne();G();pt();hi();se();se();var bn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var tT=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function rT(e,t){return e<t?-1:e>t?1:0}function iT(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"||!tT.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(rT)}function Bf(e=[]){return iT(e,"Native repair failed check IDs",bn.maxFailedCheckIds,!0)}function Yy(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function nT(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Yy(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Yy(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Vf(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(nT(i,a))break;r+=1,i=a}return r}Ic();wi();function Mf(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 Xy="repairStagnation",Ge={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},oT=/^[a-f0-9]{64}$/u;var sT=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),cT=["data","runId","sequence","timestamp","type"],Qy=["disposition","overrideSummaryHash","signatureHash"],lT=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Zy=12;function zf(e,t){return e<t?-1:e>t?1:0}function eN(e,t,r){let i=Object.keys(e).sort(zf);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function Oc(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 ao(e,t){if(typeof e!="string"||!oT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function uT(e){if(!Array.isArray(e)||e.length>bn.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(zf)}function tN(e){if(typeof e!="string"||e.length===0||e.length>Ge.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 Wf(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Ge.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ge.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>Ge.maxTextCharacters&&(!n||e.length>Ge.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Ge.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>Ge.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Wf(s,t+1,r,`${i}[${c}]`));return}let a=Oc(e,i),o=Object.keys(a);if(o.length>Ge.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ge.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Ge.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Wf(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function dT(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 fT(e,t,r){let i=Oc(e,`Native repair trajectory event ${t+1}`);if(eN(i,cT,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(dT(i.timestamp),typeof i.type!="string"||!sT.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(tN(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 Wf(i.data,0,n,"Native trajectory event data"),Oc(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Jf(e){let t=Oc(e,"Native repair trajectory projection"),r=Object.keys(t).sort(zf),i=r.length===Qy.length&&r.every((l,u)=>l===Qy[u]);i||eN(t,lT,"Native repair trajectory projection");let n=ao(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:ao(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=ao(t.contractHash,"Native repair trajectory contract hash"),s=uT(t.failedAcceptanceIds),c=Bf(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 pT(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 hT(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??Zy;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Vf({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<bn.warningAtConsecutiveFailures?"continue":a<bn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function mT(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??Zy;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 rN(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ge.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=tN(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=fT(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ge.maxTotalDataNodes||c>Ge.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?ao(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?ao(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Xy)){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=Jf(f[Xy]);if(pT(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),hT(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");mT(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>bn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function iN(e){return rN(e).history}function nN(e){let t=rN(e).latestProjection;return t?{...t}:null}$t();var kn={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:[]},Gf=Q("comet-native-runtime:v3:scope-reopen"),vT=[{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 aN(e){return e.skillVersion===kn.definition.metadata.version&&e.skillHash===Gf||vT.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}$t();$t();function oN(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}))}ga();var dN=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],kT=new Set(dN),fN=new Set([...dN,"minimum_runtime_version","revision"]),ST=new Set([...fN,"operation"]),Kf=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),ET=new Set([...Kf,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Yf=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 Qf(e,t){return bT.join(K(e,t),"transition.json")}function Dc(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Zf(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 Hc(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xf(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=>!ET.has(u)),a=[...Kf].find(u=>!Object.hasOwn(r,u)),o=Kf.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(Mf(r.summary,"Native transition journal event summary"),it(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&&(Mf(r.noCodeReason,"Native transition journal event no-code reason"),it(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")?Jf(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 xT(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 Xf({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Xf(e,t)}function ep(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?xT(e.eventData,e.evidenceHash):Xf(e.eventData,e.evidenceHash),n=Kd(e.nextRun),a=e.previousRun===null?null:Kd(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function sN(e,t,r=!1){if(e.skill!==kn.definition.metadata.name||(r?!aN(e):e.skillVersion!==kn.definition.metadata.version||e.skillHash!==Gf)||e.orchestration!==kn.definition.orchestration.mode||e.pendingRef!==rt.pendingRef||e.trajectoryRef!==rt.trajectoryRef||e.contextRef!==rt.contextRef||e.artifactsRef!==rt.artifactsRef||e.checkpointRef!==rt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function cN(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 lN(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 tp(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(sN(o,"next Run",i||a!==null),lN(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(sN(a,"previous Run",!0),lN(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(!Uf(cN(a),cN(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function CT(e,t,r){return Q(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function pN(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function uN(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function rp(e,t,r,i,n=!1){let a=r.eventData,o=uN(e),s=uN(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&&Uf(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&&Uf(e.spec_changes,t.spec_changes),l=oN({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=CT(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 PT(e,t){let r=Dc(e);if(Zf(r,ST),r.schema!==Mi)throw new Error(`Expected Native transition schema ${Mi}`);let i=Hc(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 ${Mi} minimum_runtime_version must be ${3}`);let n=Hc(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=ep(r,t),o=jt(r.previousState),s=jt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(rp(o,s,a,r.operation),tp(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:Mi,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 RT(e,t){let r=Dc(e);if(Zf(r,kT),r.schema!==va)throw new Error(`Expected Native transition schema ${va}`);let i=ep(r,t,!0),n=ni(r.previousState),a=ni(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return rp(n,a,i,pN(n,a,i.eventData),!0),tp(n,a,i,!0),{schema:va,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 _T(e,t){let r=Dc(e);if(Zf(r,fN),r.schema!==Wi)throw new Error(`Expected Native transition schema ${Wi}`);if(Hc(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Wi} minimum_runtime_version must be 2`);let n=Hc(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=ep(r,t,!0),o=ai(r.previousState),s=ai(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(rp(o,s,a,pN(o,s,a.eventData),!0),tp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Wi,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 AT(e,t){let r=Dc(e);if(r.schema===Mi)return{status:"current",journal:PT(r,t)};if(r.schema===va)return{status:"migration-required",journal:RT(r,t)};if(r.schema===Wi)return{status:"migration-required",journal:_T(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function IT(e,t){let r=Qf(e,t),i=ve(e,r);await U(i,r);try{let n=await ci({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return AT(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function hN(e,t){let r=await IT(e,t);if(!r)return null;if(r.status==="migration-required")throw new Yf(t);return r.journal}var jT=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function TT(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function $T(e){return e?e.map(TT).join(" "):null}function OT(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 nt(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 HT(e){return e.map(t=>nt(t,[],null))}function DT(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[nt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(nt("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(nt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),nt("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(nt("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(nt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),nt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Se(e,t){let r=t.commandArgs===void 0?OT(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?$T(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??HT(t.requiredInputs??[])}}function qc(e){let r=(e.findings??[]).filter(d=>!sn(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||jT.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 Se(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Se(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[nt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Se(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Se(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Se(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Se(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[nt("summary",["--summary"],"<summary>")]});if(n)return Se(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 Se(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[nt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Se(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Se(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Se(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Se(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"),Se(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[nt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Se(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Se(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=DT(e.state);return Se(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import oo from"path";G();var mN=8,qT={"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 FT(e){let t=qT[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"}:sn(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 LT(e,t,r){if(!r.path)return null;let i;if(oo.isAbsolute(r.path)?i=oo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=oo.resolve(we(e,t.name),...r.path.split(/[\\/]/u)):i=oo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!B(e.projectRoot,i))return null;let n=oo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function BT(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 ip(e){return e.findings.map(t=>{let r=FT(t.code);return{code:t.code,message:t.message,severity:r.severity,path:LT(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:BT(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 np(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,mN),truncated:t.length>mN}}ce();import Sn from"path";$t();G();pt();aa();hi();var so={maxArtifacts:128},En=/^[a-f0-9]{64}$/u;function Fc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Lc(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 Gr(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 vN(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ap(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function VT(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Sn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Sn.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function gN(e,t){return Sn.join(K(e,t),"checkpoints","progress.json")}function co(e,t){return Sn.join(K(e,t),"checkpoint-journal.json")}function wN(e,t,r){if(!En.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Sn.join(K(e,t),"checkpoints","manifests",`${r}.json`)}function MT(e){if(!En.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function op(e,t,r){let i=await ci({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function WT(e,t){let r=Fc(e,`checkpoint manifest artifact ${t}`);Lc(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=VT(Gr(r.path,`checkpoint artifact ${t} path`,4096)),n=Pt(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!En.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:ap(r.size,`checkpoint artifact ${t} size`)}}function sp(e,t){let r=Fc(e,"Native checkpoint manifest");if(Lc(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>so.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(WT),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=ap(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 yN(e){return Q(JSON.stringify(sp(e,e.change)))}function NN(e,t){let r=Fc(e,"Native progress checkpoint");if(Lc(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=vN(r.previousRevision,"Native checkpoint previousRevision"),a=vN(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Gr(r.manifestHash,"Native checkpoint manifestHash",64);if(!En.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=MT(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Gr(r.inputHash,"Native checkpoint inputHash",64);if(!En.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Gr(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=ap(r.artifactCount,"Native checkpoint artifactCount");if(u>so.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Gr(r.summary,"Native checkpoint summary"),f=Gr(r.nextAction,"Native checkpoint nextAction");if(it(d)!==d||it(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Gr(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 zT(e,t){let r=Fc(e,"Native checkpoint journal");if(Lc(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=jt(r.previousState),n=jt(r.nextState),a=NN(r.checkpoint,t),o=sp(r.manifest,t),s=Gr(r.inputHash,"Native checkpoint journal inputHash",64),c=Q(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!En.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!==yN(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 JT(e,t,r){let i=Sn.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=Bu(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Od({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 GT(e,t){let r=gN(e,t),i=ve(e,r);await U(i,r);try{return NN(await op(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function UT(e,t,r){let i=wN(e,t,r),n=ve(e,i);await U(n,i);let a=await op(n,i,"Native checkpoint manifest"),o=sp(a,t);if(bN(e,o),yN(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function cp(e,t){let r=co(e,t),i=ve(e,r);await U(i,r);try{let n=zT(await op(i,r,"Native checkpoint journal"),t);return bN(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function bN(e,t){for(let r of t.artifacts){let i=Bu(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function kN(e){let t;try{t=await GT(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:gN(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 UT(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 JT(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:wN(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var SN=240,EN=8,Bc=50;function xN(e){let t=Array.from(e);return t.length<=SN?e:`${t.slice(0,SN-1).join("")}…`}function KT(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function YT(e){let t=[...new Set(e.map(KT))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,EN),reasonCount:e.length,codesTruncated:t.length>EN};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Bc),reasonsTruncated:e.length>Bc}}}async function CN(e){let t=null;try{let s=await cp(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:co(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:co(e.paths,e.state.name)}}let r=await kN({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=YT(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:so.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:xN(r.checkpoint.summary),nextAction:xN(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:so.maxArtifacts}}import{promises as K$}from"node:fs";import zN from"node:path";se();import PN from"node:path";var XT="comet.native.archive-preflight.v1",QT="comet.native.archive-preflight.v1",ZT="comet.native.archive-operation.v1",e$=/^[a-f0-9]{64}$/u,RN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,t$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Vc(e,t){return e<t?-1:e>t?1:0}function r$(e,t){if(typeof e!="string"||!e$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ar(e,t){return e===null?null:r$(e,t)}function i$(e,t){let r=PN.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||PN.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 n$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function a$(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 o$(e,t){if(!RN.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=ar(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=ar(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=ar(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 s$(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:ar(e.contractHash,"Native archive contract hash"),acceptanceHash:ar(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:ar(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:ar(e.reportHash,"Native archive report hash"),envelopeHash:ar(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:ar(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 c$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!t$.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(Vc);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function l$(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(Vc)}function _N(e){if(!RN.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(o$).sort((l,u)=>Vc(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(ZT,l)})),i=s$(e.evidence),n=a$(e.workspace),a=[...new Set([...c$(e.findingCodes??[]),...l$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(Vc),o=n$(e.revision),s=i$(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:XT,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(QT,c)}}Xe();se();import{createHash as u$}from"node:crypto";import AN from"node:path";var d$="comet.native.conflict-radar.v1",Be=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}),f$="comet.native.conflict-radar.v1",p$="comet.native.conflict-radar-signals.v1",h$=/^[a-f0-9]{64}$/u,TN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,m$=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),v$=new Set(["capability","operation","baseHash"]),g$=new Set(["path","kind"]);function xn(e,t){return e<t?-1:e>t?1:0}function lp(e){return Buffer.byteLength(e,"utf8")}function up(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 dp(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(lp(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function w$(e,t){let r=dp(e,t,Be.maxArtifactPathBytes),i=AN.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)||AN.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 $N(e,t){if(typeof e!="string"||!h$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function y$(e,t){let r=up(e,v$,t),i=dp(r.capability,`${t} capability`,Be.maxCapabilityBytes);if(!TN.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:$N(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 N$(e,t){let r=up(e,g$,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:w$(r.path,`${t} path`),kind:r.kind}}function b$(e,t){let r=up(e,m$,`Conflict radar change ${t}`),i=dp(r.name,`Conflict radar change ${t} name`,Be.maxNameBytes);if(!TN.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>Be.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>Be.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>y$(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>xn(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)=>N$(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>xn(c.path,l.path)||xn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:$N(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function k$(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Be.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(b$).sort((n,a)=>xn(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)>Be.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Be.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function S$(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 E$(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 x$(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function C$(e,t){let r=[],i=u$("sha256").update(`${p$}
|
|
172
|
-
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Rn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Be.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(S$(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=E$(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:x$(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function IN(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function P$(e,t){return IN(e.classification)-IN(t.classification)||xn(e.left,t.left)||xn(e.right,t.right)}function jN(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:d$,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 ON(e){let t=k$(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(C$(t[s],t[c]));r.sort(P$);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(f$,{changes:t,relationships:i}),a=r.slice(0,Be.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=jN(t,r,a,n);for(;a.length>0&&lp(JSON.stringify(o))>Be.maxSerializedBytes;)a=a.slice(0,-1),o=jN(t,r,a,n);if(lp(JSON.stringify(o))>Be.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}Jr();pt();var R$=4096;async function _$(e,t=Be.maxChanges){try{let r=await Ca({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 HN(e,t){let r=await Zt(e,t),[i,n]=await Promise.all([r.implementation_scope?Tc(e,t,r.implementation_scope):null,Qt(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 Mc(e,t,r={}){let n=(await _$(e,R$)).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 HN(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await HN(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=ON([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"]:[]]}}Me();G();ba();Xe();Jr();nn();wi();Ic();import{execFile as L$}from"node:child_process";Is();gf();import{promisify as B$}from"node:util";Ne();ce();Of();G();Rt();import{constants as fp,promises as at}from"node:fs";import Cn from"node:path";var I$=/^[a-f0-9]{64}$/u,j$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function T$(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Wc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function $$(e,t){let r=Cn.resolve(e),i=Cn.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["",...Cn.relative(r,i).split(Cn.sep).filter(Boolean)]){o&&(a=Cn.join(a,o));let s=await at.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await at.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 qN(e){for(let t of e){let r=await at.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!T$(t,r)||await at.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function O$(e){if(!I$.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function H$(e){let t=j$.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function D$(e,t,r){return Pr(K(e,t),O$(r))}async function q$(e,t,r){let i=await $$(r,Cn.dirname(e)),n=await at.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([at.realpath(t),at.realpath(e)]);if(!B(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":fp.O_RDONLY|fp.O_NOFOLLOW|fp.O_NONBLOCK,c=await at.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(),at.lstat(e),at.realpath(e)]);if(await qN(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Wc(n,l)||!Wc(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(),at.lstat(e),at.realpath(e)]);if(await qN(i),!v.isFile()||v.isSymbolicLink()||g!==o||!B(a,g)||!Wc(l,h)||!Wc(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 FN(e,t,r){let i=H$(r),n=K(e,t),a=D$(e,t,i),o=ve(e,a);await U(o,a);let s=Oy(await q$(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}Jr();Ne();hi();var lo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};nn();Qa();wi();var dK=64*1024;var fK=3600*1e3;var pK=B$(L$);var V$=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function LN(e,t){let r=[];for(let i of V$){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 BN(e){if(e.receipt.kind!=="static-inspection")return null;let t=await FN(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}Qa();var Ur=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 M$(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 W$(e){let t=M$(e.bundle.baseline),r=await zd(e.paths,t,{origin:"explicit",now:e.now});return _f({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 MN(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Za(e.paths,e.state.name,e.state.implementation_scope),r=await ln({changeDir:we(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await W$({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 WN(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await MN(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 z$(e){let t=await re({root:we(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:sg(t.text)}}function J$(e){let{receipt:t,implementationScope:r}=e,i=[],n=Rf({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 G$(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:qf(e.implementationScope.scope.declaredArtifacts)}}async function VN(e){let t=await eo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=LN(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 Ur([{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 BN({paths:e.paths,state:e.state,receipt:t});if(n){let a=J$({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 U$(e){let t=G$({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await VN({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Ur)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 VN({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Ur)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 Ur(r)}function pp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function hp(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:pp(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([MN(e),yn(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:pp(e.state.verification_result,"stale"),envelope:null};let i=await z$({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 U$({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:pp(e.state.verification_result,"invalid"),envelope:null}}}function Y$(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function JN(e){try{return await K$.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function X$(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 Q$(e,t,r){let i=Oa(e,r.capability);if(!B(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=zN.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await X$(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:we(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 Z$(e,t){return JN(Qf(e,t))}async function mp(e){let t=e.now??new Date,r=await Zt(e.paths,e.name),i=await Qt(e.paths,e.name),n=await Pe(e.paths.projectRoot),a=Y$(r.name,t),o=zN.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=>Q$(e.paths,r.name,m))),hp({paths:e.paths,state:r,now:t}),Mc(e.paths,r.name),uc(e.paths,r.name),hw(e.paths,r.name),Z$(e.paths,r.name),JN(o)]);return _N({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]})}G();Jr();Qa();wi();async function eO(e,t){let r=K(e,t.name),i=await on(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 nc(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 ui(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function tO(e,t){let r=await eO(e,t);return{committed:r,latest:nN(r),history:iN(r)}}async function GN(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await tO(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)}}Jr();pt();G();function uo(e,t){try{return ha(e,t)}catch{return}}var or=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function iO(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function nO(e){return(await Uy(e))?.change??null}function aO(e,t,r=!1,i){return qc({state:e,archiveReady:t,evidenceRetreat:r}).command}async function oO(e,t){let r=we(e,t.name),i=[...(await dc(r,t.brief)).findings,...(await Ew(e,t)).findings,...await Ky(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Xs(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 zg(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 ln({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 hN(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 af(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 vp(e,t,r){let i=await nO(e)===t,n=await md(e,t),a=await ja(e,t),o;try{let y=await tf(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:uo(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:uo(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:uo(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=ip({paths:e,state:o,findings:[y]}),O=qc({state:o,findings:C});return{name:o.name,artifacts:uo(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:np(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 CN({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await GN(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 ln({changeDir:we(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 yn(e,o.name,o.verification_evidence);for(let Ee of Y.acceptanceTrace.entries)C.set(Ee.acceptanceId,Ee.status==="failed"?"failed":Ee.status==="missing"?"missing":"satisfied")}let O=ng({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:iO(T),nextPageArgs:T}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await Mc(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 Qt(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await cn({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 sc({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 WN({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 mp({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 oO(e,o),...s.findings,...d,...f,...p,...l,...v].filter((y,C,O)=>O.findIndex(T=>T.code===y.code&&T.path===y.path)===C),b=ip({paths:e,state:o,findings:g}),S=b.filter(y=>!sn(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:uo(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:aO(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:np(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:qc({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:Bc,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 UN(e){let t;try{t=await Hd({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await rO.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>or.maxChanges))throw new Error(`Native status exceeds ${or.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}G();var wp=Bt(Ct(),1);wt();se();Xe();ft();import{promises as sO}from"node:fs";import gp from"node:path";var zc=class extends Error{};async function yp(e,t){let r=await re({root:e.nativeRoot,ref:gp.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,wp.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new zc("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:qe(i)}}async function YN(e,t,r){let i;try{i=await sO.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=gp.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await yp(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof zc)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 Jc(e){return j("comet.native.status-record.v1",e)}function KN(e){let t=gp.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=We(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=qe((0,wp.parse)(We(e.projectRoot,["show",`${r}:${t}`])));return Jc(i)===Jc(e.state)?r:null}catch{return null}}function XN(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=KN(e),i=KN(t);if(!r||!i)return!1;try{return We(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function QN(e,t){return e.state.archived&&t.state.archived&&Jc(e.state)===Jc(t.state)}import sb from"node:path";import{promises as ZN}from"node:fs";import cO from"node:path";se();var lO=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),uO=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),dO=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),fO=new Set(["status","summary"]);function Gc(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Uc(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 pO(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Ni(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function hO(e,t,r,i){let n=Gc(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Uc(n,lO,"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=Gc(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Uc(o,uO,"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=Gc(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Uc(c,fO,"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=Gc(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:m,...h}=f,v=Uc(h,dO,`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!==j("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||!pO(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 eb(e){let t=Va(e.paths,e.state.name),r;try{let c=await ZN.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Ni(t,"","Native Supervisor overlay is not a regular file");r=await ZN.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Ni(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Ni(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=cO.join(e.paths.changesDir,e.state.name),a;try{a=await Ht({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Ni(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 ze(e.paths,e.state.name)}catch(c){return Ni(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Ni(t,r,"Native Supervisor overlay disappeared during inspection");let s=hO(i,e.state,a.contract,o);return s?Ni(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}}ka();pi();function Te(e,t,r){return e.language==="zh-CN"?r:t}function mO(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:Te(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:Te(e,"Reply A or B","回复 A 或 B"),agentInstruction:Te(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(Te(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(Te(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:Te(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:Te(e,"Accept the result","接受结果"),agentInstruction:Te(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)>=Nc)??!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(Te(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(Te(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 vO(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 gO(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:Te(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Te(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function nb(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function bi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function tb(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function wO(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function rb(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function yO(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function NO(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 Kr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:nb({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[bi("summary","--summary"),wO(e.name,e.flag)]}}function ib(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:Te(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function bO(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Kc(e){return[Kr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Kr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function kO(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 fo(e,t,r={}){let i=yO(t)&&e.coordination_mode===void 0,n=mO(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:[bi("summary","--summary")],commandAlternatives:[Kr({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:[bi("summary","--summary")],commandAlternatives:[Kr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Kc({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:[bi("summary","--summary")],commandAlternatives:[Kr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Kr({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:[bi("summary","--summary")],commandAlternatives:[Kr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Kc({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:[bi("summary","--summary")],commandAlternatives:Kc({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Kc({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?nb({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:NO({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?[rb("coordination-mode","--coordination-mode",cg)]:[]],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:[tb()],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)>=Nc)??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:Te(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]:[bi("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=tb();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} ${Te(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:kO([{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=ib(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>bO(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:ib(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:[rb("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...gO(e)],userCommunication:vO(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Kr({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 ab from"node:path";function ob(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Np(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:ob(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:ob(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=>ab.relative(t.projectRoot,ab.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}G();function cb(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function lb(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 ub(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:xO(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:CO(i,r)}))]:[]]}function db(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 SO(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 Yc(e,t,r=he(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:sb.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 bp(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=Np(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...fo(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:{...fo(t).runnerAction,kind:"none"}}:fo(t),c=e.details?ub(t,null,[]):[],l=lb(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?cb(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:ha(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:sb.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:db(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 EO(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 Xc(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function xO(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:Xc(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function CO(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:Xc(e.summary,t)??""}}async function fb(e){let t=await uf(e),r=Np(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Ma({paths:e.paths,state:t.state}),a=await eb({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await ze(e.paths,e.name,{diagnostics:!0}),s=o?{...Yc(e.paths,t.state,e.gitContext),projectRoot:"."}:Yc(e.paths,t.state,e.gitContext),c=fo(t.state,n,{verifierExecutionRef:$w(t.state,t.local),...t.local?{verificationCheckPlans:Gy(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?EO(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:Xc(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let k=Xc(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=ub(t.state,o,u),v=lb(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?cb(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:ha(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:db(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=SO(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}}:{}}}ce();js();wt();import{accessSync as o6,constants as s6,promises as kp}from"node:fs";import hb from"node:path";Ec();js();var pb="comet.native.workspace-finish.v1",mb="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",vb=new RegExp(`^${mb}$`,"u"),PO=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function RO(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==pb||typeof t.name!="string"||!vb.test(t.name)||typeof t.transactionId!="string"||!PO.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!hb.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:pb,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function _O(e,t){if(!vb.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return hb.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function Sp(e,t,r={}){let i=_O(e,t);try{let n=await kp.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=RO(JSON.parse(await kp.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 gb(e,t={}){let r;try{r=await kp.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-(${mb})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await Sp(e,a[1],t);o&&i.push(o)}return i}var IO=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Qc(e,t){let r=sr.normalize(Ep(e)),i=sr.normalize(Ep(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Ep(e){let t=sr.resolve(e);try{return AO.native(t)}catch{return t}}function jO(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function wb(e,t){let r=[];for(let i of await UN(e))t!==void 0&&i!==t||r.push({name:i,kind:await hc(e,i)?"portable":"legacy"});return r}async function kb(e,t){let r=sr.resolve(e),i=go(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>Qc(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>sr.resolve(l)).sort()){let l=Qc(c,r)?r:c,u=Ep(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let f=await Pe(l);if(!f)continue;let p=await Gt(l,f.native.artifact_root);o.push({projectRoot:l,config:f,paths:p,gitContext:nl(l,i)??he(l),changes:await wb(p,t)})}if(o.length===0){let c=await Pe(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Gt(e,c.native.artifact_root);o.push({projectRoot:sr.resolve(e),config:c,paths:l,gitContext:nl(e,i)??he(e),changes:await wb(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await YN(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 Sp(c.paths,t,{onError:l})].filter(u=>u!==null):await gb(c.paths,{onError:l})}return o}function yb(e,t){return e.workspace.bindingState==="aligned"?0:Qc(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Sb(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 yt(d.paths,n);return{source:d,name:n,kind:f,workspace:Yc(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 ja(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=bp({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 yp(f.source.paths,sr.join(f.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(f=>[...o,...s.filter(p=>!QN(f.record,p.record))].every(p=>p.record&&XN(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)=>yb(d,e)-yb(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>or.maxChanges)throw new Error(`Native status discovery exceeds ${or.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function Nb(e,t){let r=t.toString(36),i=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function TO(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=IO.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or 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 workspace status cursor offset is invalid");let i=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:r});if(t[3]!==i)throw new Error("Native workspace status cursor integrity failed");return r}function bb(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?jO(r):null,nextPageArgs:r}}async function $O(e,t,r){let i=await ja(e.source.paths,e.name),n=null;try{n=await vw(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}}}:vp(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 xp(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 bp({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await fb({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return xp({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return $O(e,t,r)}async function Eb(e){let{sources:t,candidates:r}=await OO(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>Qc(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),vp(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),xp(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function OO(e,t){let r=await kb(e,t),i=(await Sb(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}}async function xb(e){let t=await kb(e.projectRoot),r=await Sb(e.projectRoot,t),i=j("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=TO({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+or.maxItems).map(u=>xp(u,!1))),o=[],s=r.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<r.length?Nb(i,f):null,m={schema:s,total:r.length,offset:n,items:d,nextCursor:p,...bb(sr.resolve(e.projectRoot),p),limits:{...or}};if(Buffer.byteLength(JSON.stringify(m),"utf8")>or.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<r.length?Nb(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...bb(sr.resolve(e.projectRoot),l),limits:{...or}}}da();import po from"path";import{realpathSync as e0}from"fs";function Cb(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 cr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Pb(e){return e?e.command?`${cr.next} ${e.command}`:e.ask_user?`${cr.next} ${e.ask_user}`:null:null}function Rb(e,t){let r=[e.summary],i=Pb(e.next);return i&&r.push(i),e.user_message&&r.push("",cr.relay,e.user_message),t!==void 0&&r.push("",cr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
181
|
+
${e.sessionId}`)}:{}},f=e.binding?{schema:"comet.native.workspace.v3",...p,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...p};return Oc(f),f}async function or(e,t){let r=await qI(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Oc(r),r)}async function Hc(e){Oc(e.identity);let t=await MI({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")),Hp==="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 Sn(e){if(Oc(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 Hc(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ve(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 hy(e,t){let r=await or(e,t);if(r===null)return null;let i=await Sn({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}Fa();cc();cc();var Dc=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"},ro=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"},Bc=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"},FV=Ks("en");function Ne(e,t){sn(t);let r=Vr.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Fc(e,t){let r=Y(e,t),i=Vr.join(r,"schema-migration.json");await K(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await vy.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function gy(e,t){let r=Y(e,t),i=Vr.join(r,"checkpoint-journal.json");await K(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await vy.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function wy(e,t=Vr.dirname(e)){let r=Vr.relative(t,e).split(Vr.sep).join("/"),i=await ne({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Bp.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 Fp(e,t){let r=Vr.join(Ne(e,t),Dt);await K(e.nativeRoot,r);let i=sc(await wy(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Fc(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 zI(e,i.state),i)}async function yy(e,t){let r=Vr.join(Ne(e,t),Dt);await K(e.nativeRoot,r);let i=sc(await wy(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function zI(e,t){if(await Cc(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function sr(e,t){let r=await Fp(e,t);if(r.status==="migration-required")throw new on(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new ir(r.schema,r.minimumRuntimeVersion);return await hy(e,t),r.state}Je();import{promises as xH}from"fs";pi();import{promises as Lp}from"fs";import by from"path";et();Lt();U();var qp=["outcome","scope","nonGoals","acceptanceExamples"],Ny=[...qp,"constraints","decisions","openQuestions","verificationExpectations"],GI=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],JI=new Set(["nonGoals","decisions","openQuestions"]),io=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},ky={maxFileBytes:Sd};function Sy(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
182
|
+
`).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 UI(e,t){let r=by.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Lp.realpath(e),n=await Lp.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Lp.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function no(e){return{valid:e.length===0,findings:e}}function Ey(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 KI(e){return Ey(e).trim()}function Mp(e){let t=KI(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(`
|
|
183
|
+
`).trim()}function YI(e){let t=Mp(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 XI(e){let t=Mp(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 xy(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 Lc(e,t,r={}){let i=[],n;try{n=(await ne({root:e,ref:t,maxBytes:ky.maxFileBytes})).text}catch(s){return no([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of Sy(n))a.set(Us(s)??s,c);for(let s of r.compact?qp:Ny)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?Ny.filter(s=>!r.compact||a.has(s)):qp;for(let s of o){let c=a.get(s)??"";Mp(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):XI(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!JI.has(s)&&YI(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return xy(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),no(i)}async function Vp(e,t){let r=[],i;try{i=(await ne({root:e,ref:t,maxBytes:ky.maxFileBytes})).text}catch(a){return no([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Sy(i))n.set(Rg(a)??a,o);for(let a of GI)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 no(r)}function ao(e,t){return by.join(e.specsDir,t,"spec.md")}async function Cy(e,t){let r=[],i=Ne(e,t.name);for(let n of t.spec_changes){let a=ao(e,n.capability),o=null;try{await K(e.nativeRoot,a),o=await bp(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 UI(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return no(r)}Va();ue();et();Va();ue();import Ry from"node:path";var QI="comet.native.contract.v1",ZI="comet.native.acceptance-set.v1",Py=/^[a-f0-9]{64}$/u,oo={maxAcceptanceCriteria:Ma.maxCriteria};function _y(e,t){let r=Ry.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})||Ry.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 Ay(e){return T("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
184
|
+
`))}function eT(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(Py))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(Py))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=_y(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Ay(e.markdown)},markdown:e.markdown}}function tT(e,t){return Iy(e.id,t.id)}function Iy(e,t){return e<t?-1:e>t?1:0}function Ty(e){let t=_y(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(eT).sort((d,p)=>Iy(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=ap(e.briefMarkdown,t,oo.maxAcceptanceCriteria);for(let{snapshot:d,markdown:p}of r)p===null||d.source===null||(a.push(...op(p,d.source,oo.maxAcceptanceCriteria-a.length)),a.push(...sw(p,d.source,oo.maxAcceptanceCriteria-a.length)));if(a.sort(tT),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>oo.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${oo.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:Ay(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=T(ZI,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:T(QI,u)}}var rT={maxSpecs:64};async function En(e){if(e.specChanges.length>rT.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ne({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 ne({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:Ty({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Je();Se();import{promises as hT}from"node:fs";import Kp from"node:path";ot();import{promises as sT}from"node:fs";ae();za();import jy from"node:path";function so(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function co(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 De(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function xn(e,t){return e===null?null:De(e,t)}function Cn(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 cT(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 lT(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Rn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function zp(e,t){if(e===null)return null;let r=De(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function uT(e,t){let r=De(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Gp(e,t){let r=De(e,t);if(!jy.isAbsolute(r))throw new Error(`${t} must be absolute`);return jy.resolve(r)}function dT(e,t){let r=`Native local checks[${t}]`,i=so(e,r);if(co(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>De(u,`${r}.argv[${d}]`,!0)),a=Rn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=zp(i.startedAt,`${r}.startedAt`),s=zp(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=Cn(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=so(i.activeProcess,`${r}.activeProcess`),d=Rn(u.status,["starting","running"],`${r}.activeProcess.status`);if(co(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:Cn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:De(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:De(i.id,`${r}.id`),name:De(i.name,`${r}.name`),operationId:De(i.operationId,`${r}.operationId`),status:a,repeatable:lT(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Cn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Gp(i.cwd,`${r}.cwd`),exitCode:cT(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:De(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:Rn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:De(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function pT(e){let t="Native local execution state",r=so(e,t);if(co(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==pc)throw new Error(`Native local execution schema must be ${pc}`);let i=so(r.workspace,"Native local workspace");co(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=so(r.execution,"Native local execution");co(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=zp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:De(o.operationId,"Native local execution.operationId"),stage:Rn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Rn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:xn(o.executionId,"Native local execution.executionId"),status:Rn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Cn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:uT(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Cn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:De(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(dT);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:pc,change:De(r.change,"Native local change"),basedOnStateVersion:Cn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:xn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:xn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:xn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:xn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Gp(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Gp(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:xn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:De(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function qc(e){let t;try{t=await sT.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 pT(r)}function Jp(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 Up(e,t){if(Jp(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}gt();U();var $y=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Oy="comet-state.yaml",Hy="state.json";function bi(e,t){if(!$y.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Kp.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function Mc(e,t){return Kp.join(bi(e,t),Oy)}function Wr(e,t){return Kp.join(vt(e,t),Hy)}async function Vc(e,t){try{let r=await hT.readFile(Mc(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 St(e,t){return Br(Mc(e,t))}async function Yp(e){let t=await St(e.paths,e.name),r=Wr(e.paths,e.name);try{let i=await qc(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 ef(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ei=ef();function Wy(e){Ei=e}var ki={exec:()=>null};function Pn(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(xe.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var mT=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),xe={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:Pn(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Pn(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Pn(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Pn(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Pn(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Pn(e=>new RegExp(`^ {0,${e}}>`))},vT=/^(?:[ \t]*(?:\n|$))+/,gT=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,wT=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,po=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,yT=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,tf=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,zy=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Gy=M(zy).replace(/bull/g,tf).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(),NT=M(zy).replace(/bull/g,tf).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(),rf=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,bT=/^[^\n]+/,nf=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,kT=M(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",nf).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ST=M(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,tf).getRegex(),Uc="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",af=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ET=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",af).replace("tag",Uc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Jy=e=>M(rf).replace("hr",po).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",Uc).getRegex(),xT=Jy(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),CT=Jy(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),RT=M(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",CT).getRegex(),of={blockquote:RT,code:gT,def:kT,fences:wT,heading:yT,hr:po,html:ET,lheading:Gy,list:ST,newline:vT,paragraph:xT,table:ki,text:bT},Dy=M("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",po).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",Uc).getRegex(),PT={...of,lheading:NT,table:Dy,paragraph:M(rf).replace("hr",po).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Dy).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",Uc).getRegex()},_T={...of,html:M(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",af).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:ki,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:M(rf).replace("hr",po).replace("heading",` *#{1,6} *[^
|
|
185
|
+
]`).replace("lheading",Gy).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},AT=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,IT=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Uy=/^( {2,}|\\)\n(?!\s*$)/,TT=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,cr=/[\p{P}\p{S}]/u,_n=/[\s\p{P}\p{S}]/u,fo=/[^\s\p{P}\p{S}]/u,jT=M(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_n).getRegex(),$T=/[\p{Pi}\p{Ps}"']/u,Ky=/(?!~)[\p{P}\p{S}]/u,OT=/(?!~)[\s\p{P}\p{S}]/u,HT=/(?:[^\s\p{P}\p{S}]|~)/u,DT=M(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",mT?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Yy=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,BT=M(Yy,"u").replace(/punct/g,cr).getRegex(),FT=M(Yy,"u").replace(/punct/g,Ky).getRegex(),LT=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,qT=M(LT,"u").replace(/openQuote/g,$T).replace(/punct/g,cr).getRegex(),Xy="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",MT=M(Xy,"gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),VT=M(Xy,"gu").replace(/notPunctSpace/g,HT).replace(/punctSpace/g,OT).replace(/punct/g,Ky).getRegex(),WT="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",zT=M(WT,"gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),GT=M("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),JT="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",UT=M(JT,"gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),KT=M(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,cr).getRegex(),YT="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",XT=M(YT,"gu").replace(/notPunctSpace/g,fo).replace(/punctSpace/g,_n).replace(/punct/g,cr).getRegex(),QT=M(/\\(punct)/,"gu").replace(/punct/g,cr).getRegex(),ZT=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(),ej=M(af).replace("(?:-->|$)","-->").getRegex(),tj=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",ej).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),zc=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,rj=M(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",zc).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Qy=M(/^!?\[(label)\]\[(ref)\]/).replace("label",zc).replace("ref",nf).getRegex(),Zy=M(/^!?\[(ref)\](?:\[\])?/).replace("ref",nf).getRegex(),ij=M("reflink|nolink(?!\\()","g").replace("reflink",Qy).replace("nolink",Zy).getRegex(),By=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,sf={_backpedal:ki,anyPunctuation:QT,autolink:ZT,blockSkip:DT,br:Uy,code:IT,del:ki,delLDelim:ki,delRDelim:ki,emStrongLDelim:BT,emStrongRDelimAst:MT,emStrongRDelimUnd:GT,escape:AT,link:rj,nolink:Zy,punctuation:jT,reflink:Qy,reflinkSearch:ij,tag:tj,text:TT,url:ki},nj={...sf,emStrongLDelim:qT,emStrongRDelimAst:zT,emStrongRDelimUnd:UT,link:M(/^!?\[(label)\]\((.*?)\)/).replace("label",zc).getRegex(),reflink:M(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",zc).getRegex()},Xp={...sf,emStrongRDelimAst:VT,emStrongLDelim:FT,delLDelim:KT,delRDelim:XT,url:M(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",By).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",By).getRegex()},aj={...Xp,br:M(Uy).replace("{2,}","*").getRegex(),text:M(Xp.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Wc={normal:of,gfm:PT,pedantic:_T},lo={normal:sf,gfm:Xp,breaks:aj,pedantic:nj},oj={"&":"&","<":"<",">":">",'"':""","'":"'"},Fy=e=>oj[e];function Mt(e,t){if(t){if(xe.escapeTest.test(e))return e.replace(xe.escapeReplace,Fy)}else if(xe.escapeTestNoEncode.test(e))return e.replace(xe.escapeReplaceNoEncode,Fy);return e}function Ly(e){try{e=encodeURI(e).replace(xe.percentDecode,"%")}catch{return null}return e}function qy(e,t){let r=e.replace(xe.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split(xe.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(xe.slashPipe,"|");return i}function zr(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 My(e){let t=e.split(`
|
|
186
|
+
`),r=t.length-1;for(;r>=0&&xe.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
187
|
+
`)}function sj(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 cj(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 Vy(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 lj(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
|
|
188
|
+
`).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(`
|
|
189
|
+
`)}var Gc=class{options;rules;lexer;constructor(e){this.options=e||Ei}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]:My(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=lj(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=zr(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:zr(t[0],`
|
|
190
|
+
`),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:zr(t[0],`
|
|
191
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=zr(t[0],`
|
|
192
|
+
`).split(`
|
|
193
|
+
`),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(`
|
|
194
|
+
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
195
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
196
|
+
${l}`:l,n=n?`${n}
|
|
197
|
+
${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(`
|
|
198
|
+
`),h=f.raw+`
|
|
199
|
+
`+m.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(h);a[a.length-1]=v,i=`${i}
|
|
200
|
+
${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="list"){let f=p,m=f.raw+`
|
|
201
|
+
`+r.join(`
|
|
202
|
+
`),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(`
|
|
203
|
+
`);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=cj(t[2].split(`
|
|
204
|
+
`,1)[0],t[1].length),p=e.split(`
|
|
205
|
+
`,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+`
|
|
206
|
+
`,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(`
|
|
207
|
+
`,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+=`
|
|
208
|
+
`+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+=`
|
|
209
|
+
`+p}f=!p.trim(),l+=x+`
|
|
210
|
+
`,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=My(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:zr(t[0],`
|
|
211
|
+
`),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=qy(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
212
|
+
`):[],a={type:"table",raw:zr(t[0],`
|
|
213
|
+
`),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(qy(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:zr(t[0],`
|
|
214
|
+
`),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)===`
|
|
215
|
+
`?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=zr(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=sj(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)),Vy(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 Vy(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}}}},st=class Qp{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ei,this.options.tokenizer=this.options.tokenizer||new Gc,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:xe,block:Wc.normal,inline:lo.normal};this.options.pedantic?(r.block=Wc.pedantic,r.inline=lo.pedantic):this.options.gfm&&(r.block=Wc.gfm,this.options.breaks?r.inline=lo.breaks:r.inline=lo.gfm),this.tokenizer.rules=r}static get rules(){return{block:Wc,inline:lo}}static lex(t,r){return new Qp(r).lex(t)}static lexInline(t,r){return new Qp(r).inlineTokens(t)}lex(t){t=t.replace(xe.carriageReturn,`
|
|
216
|
+
`),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(xe.tabCharGlobal," ").replace(xe.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+=`
|
|
217
|
+
`: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(`
|
|
218
|
+
`)?"":`
|
|
219
|
+
`)+a.raw,s.text+=`
|
|
220
|
+
`+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(`
|
|
221
|
+
`)?"":`
|
|
222
|
+
`)+a.raw,s.text+=`
|
|
223
|
+
`+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(`
|
|
224
|
+
`)?"":`
|
|
225
|
+
`)+a.raw,s.text+=`
|
|
226
|
+
`+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(`
|
|
227
|
+
`)?"":`
|
|
228
|
+
`)+a.raw,s.text+=`
|
|
229
|
+
`+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)}},Jc=class{options;parser;constructor(e){this.options=e||Ei}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(xe.notSpaceStart)?.[0],n=e.replace(xe.endingNewline,"")+`
|
|
230
|
+
`;return i?'<pre><code class="language-'+Mt(i)+'">'+(r?n:Mt(n,!0))+`</code></pre>
|
|
231
|
+
`:"<pre><code>"+(r?n:Mt(n,!0))+`</code></pre>
|
|
232
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
233
|
+
${this.parser.parse(e)}</blockquote>
|
|
234
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
235
|
+
`}hr(e){return`<hr>
|
|
236
|
+
`}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+`>
|
|
237
|
+
`+i+"</"+n+`>
|
|
238
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
239
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
240
|
+
`}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>
|
|
241
|
+
<thead>
|
|
242
|
+
`+t+`</thead>
|
|
243
|
+
`+i+`</table>
|
|
244
|
+
`}tablerow({text:e}){return`<tr>
|
|
245
|
+
${e}</tr>
|
|
246
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
247
|
+
`}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>${Mt(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=Ly(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+Mt(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=Ly(e);if(n===null)return Mt(r);e=n;let a=`<img src="${e}" alt="${Mt(r)}"`;return t&&(a+=` title="${Mt(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Mt(e.text)}},cf=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}},Et=class Zp{options;renderer;textRenderer;constructor(t){this.options=t||Ei,this.options.renderer=this.options.renderer||new Jc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new cf}static parse(t,r){return new Zp(r).parse(t)}static parseInline(t,r){return new Zp(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}},uo=class{options;block;constructor(e){this.options=e||Ei}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?st.lex:st.lexInline}provideParser(e=this.block){return e?Et.parse:Et.parseInline}},uj=class{defaults=ef();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Et;Renderer=Jc;TextRenderer=cf;Lexer=st;Tokenizer=Gc;Hooks=uo;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 Jc(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 Gc(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 uo;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];uo.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&uo.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 st.lex(e,t??this.defaults)}parser(e,t){return Et.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?st.lex:st.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?Et.parse:Et.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?st.lex:st.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?Et.parse:Et.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+=`
|
|
248
|
+
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Mt(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},Si=new uj;function X(e,t){return Si.parse(e,t)}X.options=X.setOptions=function(e){return Si.setOptions(e),X.defaults=Si.defaults,Wy(X.defaults),X};X.getDefaults=ef;X.defaults=Ei;function dj(...e){return Si.use(...e),X.defaults=Si.defaults,Wy(X.defaults),X}X.use=dj;X.walkTokens=function(e,t){return Si.walkTokens(e,t)};X.parseInline=Si.parseInline;X.Parser=Et;X.parser=Et.parse;X.Renderer=Jc;X.TextRenderer=cf;X.Lexer=st;X.lexer=st.lex;X.Tokenizer=Gc;X.Hooks=uo;X.parse=X;var NW=X.options,bW=X.setOptions,kW=X.walkTokens,SW=X.parseInline;var EW=Et.parse,xW=st.lex;ae();et();ue();var gN=Kt(It(),1);import{promises as Jj}from"node:fs";import xt from"node:path";ot();et();ue();Je();U();gt();Xc();Xc();Ci();Kr();ot();oc();ae();ue();rl();Se();U();pN();Ci();Kr();il();ot();Je();il();Da();U();var nl=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function mf(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 Wj from"node:path";ot();Je();Se();Ci();Kr();async function al(e){let t=mf(e.parent),r=Yt(e.paths.projectRoot,t);if(!r)return null;let i=Yt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=yr(e.paths.projectRoot).map(o=>Wj.resolve(o)).find(o=>ve(o).currentBranch===t);if(!n)return null;let a=el({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 df(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function vf(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 Uj(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 Kj(e){let t=Uj(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 gf(e){try{let t=await ne({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return Kj(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function wf(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 Yj(e){let t=yr(e.projectRoot);t.some(i=>vf(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>xt.resolve(n)))]){let n=await Te(i);n&&r.push({projectRoot:i,paths:await tr(i,n.native.artifact_root),parent:vf(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Xj(e,t){let r=xt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Br(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Qj(e,t){let r;try{r=await Jj.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 Br(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function Zj(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,gN.parseDocument)(Ve(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:qe(a.toJS({mapAsMap:!1}))}catch{return null}}function e$(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 vN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function wo(e){let t=xt.join(e.paths.changesDir,e.state.name),r=await gf(t),i=null,n;try{n=await Vt({changeDir:t,validation:Jr(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 Ue(e.paths,e.state.name,{diagnostics:!0});if(g){let b=tl(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=wf({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===Gr){let g=await Ue(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 al({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await Ur(e.paths,x))}}if(g){let N=tl(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 Yj(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 Qj(g,l)){let N={...k,source:g,committedState:Zj(g,k.file,b)};u.set(k.state.name,[...u.get(k.state.name)??[],N])}for(let k of l){let N=await Xj(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&&vN(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,e$(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:j,committedState:Q})=>vf(j.projectRoot,w.projectRoot)&&Q?.name===O&&vN(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")}}dc();gt();gi();ho();Qc();Se();sp();Xd();gt();gi();ae();pi();ho();U();pi();ti();Je();var ab=Kt(It(),1);er();var $G=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 LG=256*1024;gt();gi();Kr();var N0=Ks("en",{compact:!0});Je();Se();Ci();Kr();gt();gi();ot();oc();ue();import Dn from"node:path";ot();er();ae();var tU=8*1024*1024;rl();Se();gi();U();function S0(e,t){let r=Dn.relative(Dn.resolve(e),Dn.resolve(t));if(Dn.isAbsolute(r)||r===".."||r.startsWith(`..${Dn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Dn.sep).join("/");return dN(e,i),i}function lb(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:S0(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var EU=1024*1024*1024;Se();Qc();ho();Kr();Se();Kr();Se();wp();var m6=16*1024;async function ub(e){let t=await Ip(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(sn(t.selection.change),t.selection)}U();async function db(e,t){let r=[],i=Y(e,t.name),n=Or(i,at.stateRef),a;try{a=await bn(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=Or(i,a.trajectoryRef),s=await ay(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 Ni(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=Or(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}yn();import W0 from"path";import{isDeepStrictEqual as zf}from"util";ae();Lt();Da();Se();U();wt();Ri();ue();ue();var Bn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var E0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function x0(e,t){return e<t?-1:e>t?1:0}function C0(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"||!E0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(x0)}function Bf(e=[]){return C0(e,"Native repair failed check IDs",Bn.maxFailedCheckIds,!0)}function pb(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function R0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:pb(e.failedAcceptanceIds,t.failedAcceptanceIds)&&pb(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Ff(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(R0(i,a))break;r+=1,i=a}return r}ul();Ii();function Lf(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 fb="repairStagnation",Ye={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},_0=/^[a-f0-9]{64}$/u;var A0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),I0=["data","runId","sequence","timestamp","type"],hb=["disposition","overrideSummaryHash","signatureHash"],T0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],mb=12;function Mf(e,t){return e<t?-1:e>t?1:0}function vb(e,t,r){let i=Object.keys(e).sort(Mf);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function hl(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 $o(e,t){if(typeof e!="string"||!_0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function j0(e){if(!Array.isArray(e)||e.length>Bn.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(Mf)}function gb(e){if(typeof e!="string"||e.length===0||e.length>Ye.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 qf(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Ye.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ye.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>Ye.maxTextCharacters&&(!n||e.length>Ye.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Ye.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>Ye.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>qf(s,t+1,r,`${i}[${c}]`));return}let a=hl(e,i),o=Object.keys(a);if(o.length>Ye.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ye.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Ye.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");qf(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function $0(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 O0(e,t,r){let i=hl(e,`Native repair trajectory event ${t+1}`);if(vb(i,I0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if($0(i.timestamp),typeof i.type!="string"||!A0.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(gb(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 qf(i.data,0,n,"Native trajectory event data"),hl(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Vf(e){let t=hl(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Mf),i=r.length===hb.length&&r.every((l,u)=>l===hb[u]);i||vb(t,T0,"Native repair trajectory projection");let n=$o(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:$o(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=$o(t.contractHash,"Native repair trajectory contract hash"),s=j0(t.failedAcceptanceIds),c=Bf(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 H0(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 D0(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??mb;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Ff({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<Bn.warningAtConsecutiveFailures?"continue":a<Bn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function B0(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??mb;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 wb(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ye.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=gb(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=O0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ye.maxTotalDataNodes||c>Ye.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let p=d.data,f=Object.hasOwn(p,"repairScopeHash")?$o(p.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(p,"implementationScopeHash")?$o(p.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(p,fb)){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=Vf(p[fb]);if(H0(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),D0(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");B0(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>Bn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function yb(e){return wb(e).history}function Nb(e){let t=wb(e).latestProjection;return t?{...t}:null}Lt();var Fn={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:[]},Wf=ee("comet-native-runtime:v3:scope-reopen"),F0=[{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 bb(e){return e.skillVersion===Fn.definition.metadata.version&&e.skillHash===Wf||F0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Lt();Lt();function kb(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}))}Fa();var Rb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],z0=new Set(Rb),Pb=new Set([...Rb,"minimum_runtime_version","revision"]),G0=new Set([...Pb,"operation"]),Gf=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),J0=new Set([...Gf,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Jf=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 Kf(e,t){return W0.join(Y(e,t),"transition.json")}function vl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Yf(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 ml(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Uf(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=>!J0.has(u)),a=[...Gf].find(u=>!Object.hasOwn(r,u)),o=Gf.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(Lf(r.summary,"Native transition journal event summary"),ct(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&&(Lf(r.noCodeReason,"Native transition journal event no-code reason"),ct(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")?Vf(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 U0(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 Uf({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Uf(e,t)}function Xf(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?U0(e.eventData,e.evidenceHash):Uf(e.eventData,e.evidenceHash),n=jp(e.nextRun),a=e.previousRun===null?null:jp(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function Sb(e,t,r=!1){if(e.skill!==Fn.definition.metadata.name||(r?!bb(e):e.skillVersion!==Fn.definition.metadata.version||e.skillHash!==Wf)||e.orchestration!==Fn.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 Eb(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 xb(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 Qf(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(Sb(o,"next Run",i||a!==null),xb(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(Sb(a,"previous Run",!0),xb(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(!zf(Eb(a),Eb(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function K0(e,t,r){return ee(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 Cb(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Zf(e,t,r,i,n=!1){let a=r.eventData,o=Cb(e),s=Cb(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&&zf(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&&zf(e.spec_changes,t.spec_changes),l=kb({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=K0(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 Y0(e,t){let r=vl(e);if(Yf(r,G0),r.schema!==nn)throw new Error(`Expected Native transition schema ${nn}`);let i=ml(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 ${nn} minimum_runtime_version must be ${3}`);let n=ml(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=Xf(r,t),o=Bt(r.previousState),s=Bt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Zf(o,s,a,r.operation),Qf(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:nn,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 X0(e,t){let r=vl(e);if(Yf(r,z0),r.schema!==Ba)throw new Error(`Expected Native transition schema ${Ba}`);let i=Xf(r,t,!0),n=hi(r.previousState),a=hi(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Zf(n,a,i,_b(n,a,i.eventData),!0),Qf(n,a,i,!0),{schema:Ba,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 Q0(e,t){let r=vl(e);if(Yf(r,Pb),r.schema!==an)throw new Error(`Expected Native transition schema ${an}`);if(ml(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${an} minimum_runtime_version must be 2`);let n=ml(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Xf(r,t,!0),o=mi(r.previousState),s=mi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Zf(o,s,a,_b(o,s,a.eventData),!0),Qf(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:an,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 Z0(e,t){let r=vl(e);if(r.schema===nn)return{status:"current",journal:Y0(r,t)};if(r.schema===Ba)return{status:"migration-required",journal:X0(r,t)};if(r.schema===an)return{status:"migration-required",journal:Q0(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function eO(e,t){let r=Kf(e,t),i=we(e,r);await K(i,r);try{let n=await wi({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return Z0(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ab(e,t){let r=await eO(e,t);if(!r)return null;if(r.status==="migration-required")throw new Jf(t);return r.journal}var tO=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function rO(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function iO(e){return e?e.map(rO).join(" "):null}function nO(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 lt(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 aO(e){return e.map(t=>lt(t,[],null))}function oO(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[lt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(lt("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(lt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),lt("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(lt("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(lt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),lt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Re(e,t){let r=t.commandArgs===void 0?nO(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?iO(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??aO(t.requiredInputs??[])}}function gl(e){let r=(e.findings??[]).filter(d=>!kn(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||tO.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 Re(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Re(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[lt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Re(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Re(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Re(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[lt("summary",["--summary"],"<summary>")]});if(n)return Re(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 Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[lt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Re(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Re(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Re(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Re(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"),Re(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[lt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Re(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Re(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=oO(e.state);return Re(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Oo from"path";U();var Ib=8,sO={"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 cO(e){let t=sO[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"}:kn(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 lO(e,t,r){if(!r.path)return null;let i;if(Oo.isAbsolute(r.path)?i=Oo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Oo.resolve(Ne(e,t.name),...r.path.split(/[\\/]/u)):i=Oo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Oo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function uO(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 eh(e){return e.findings.map(t=>{let r=cO(t.code);return{code:t.code,message:t.message,severity:r.severity,path:lO(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:uO(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 th(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,Ib),truncated:t.length>Ib}}ae();import Ln from"path";Lt();U();wt();Ra();Ri();var Ho={maxArtifacts:128},qn=/^[a-f0-9]{64}$/u;function wl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yl(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 ri(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 Tb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function dO(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Ln.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Ln.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function jb(e,t){return Ln.join(Y(e,t),"checkpoints","progress.json")}function Do(e,t){return Ln.join(Y(e,t),"checkpoint-journal.json")}function $b(e,t,r){if(!qn.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Ln.join(Y(e,t),"checkpoints","manifests",`${r}.json`)}function pO(e){if(!qn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function ih(e,t,r){let i=await wi({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function fO(e,t){let r=wl(e,`checkpoint manifest artifact ${t}`);yl(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=dO(ri(r.path,`checkpoint artifact ${t} path`,4096)),n=Tt(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!qn.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:rh(r.size,`checkpoint artifact ${t} size`)}}function nh(e,t){let r=wl(e,"Native checkpoint manifest");if(yl(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>Ho.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(fO),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=rh(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 Ob(e){return ee(JSON.stringify(nh(e,e.change)))}function Hb(e,t){let r=wl(e,"Native progress checkpoint");if(yl(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=Tb(r.previousRevision,"Native checkpoint previousRevision"),a=Tb(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ri(r.manifestHash,"Native checkpoint manifestHash",64);if(!qn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=pO(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ri(r.inputHash,"Native checkpoint inputHash",64);if(!qn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ri(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=rh(r.artifactCount,"Native checkpoint artifactCount");if(u>Ho.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ri(r.summary,"Native checkpoint summary"),p=ri(r.nextAction,"Native checkpoint nextAction");if(ct(d)!==d||ct(p)!==p)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ri(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 hO(e,t){let r=wl(e,"Native checkpoint journal");if(yl(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=Bt(r.previousState),n=Bt(r.nextState),a=Hb(r.checkpoint,t),o=nh(r.manifest,t),s=ri(r.inputHash,"Native checkpoint journal inputHash",64),c=ee(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!qn.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!==Ob(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 mO(e,t,r){let i=Ln.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=bd(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await yp({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 vO(e,t){let r=jb(e,t),i=we(e,r);await K(i,r);try{return Hb(await ih(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function gO(e,t,r){let i=$b(e,t,r),n=we(e,i);await K(n,i);let a=await ih(n,i,"Native checkpoint manifest"),o=nh(a,t);if(Db(e,o),Ob(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function ah(e,t){let r=Do(e,t),i=we(e,r);await K(i,r);try{let n=hO(await ih(i,r,"Native checkpoint journal"),t);return Db(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Db(e,t){for(let r of t.artifacts){let i=bd(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function Bb(e){let t;try{t=await vO(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:jb(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 gO(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 mO(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:$b(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var Fb=240,Lb=8,Nl=50;function qb(e){let t=Array.from(e);return t.length<=Fb?e:`${t.slice(0,Fb-1).join("")}…`}function wO(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function yO(e){let t=[...new Set(e.map(wO))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Lb),reasonCount:e.length,codesTruncated:t.length>Lb};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Nl),reasonsTruncated:e.length>Nl}}}async function Mb(e){let t=null;try{let s=await ah(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Do(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:Do(e.paths,e.state.name)}}let r=await Bb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=yO(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ho.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:qb(r.checkpoint.summary),nextAction:qb(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:Ho.maxArtifacts}}import{promises as wH}from"node:fs";import sk from"node:path";ue();import Vb from"node:path";var NO="comet.native.archive-preflight.v1",bO="comet.native.archive-preflight.v1",kO="comet.native.archive-operation.v1",SO=/^[a-f0-9]{64}$/u,Wb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function bl(e,t){return e<t?-1:e>t?1:0}function xO(e,t){if(typeof e!="string"||!SO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hr(e,t){return e===null?null:xO(e,t)}function CO(e,t){let r=Vb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Vb.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 RO(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function PO(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 _O(e,t){if(!Wb.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=hr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=hr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=hr(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 AO(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:hr(e.contractHash,"Native archive contract hash"),acceptanceHash:hr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:hr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:hr(e.reportHash,"Native archive report hash"),envelopeHash:hr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:hr(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 IO(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!EO.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(bl);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function TO(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(bl)}function zb(e){if(!Wb.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(_O).sort((l,u)=>bl(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(kO,l)})),i=AO(e.evidence),n=PO(e.workspace),a=[...new Set([...IO(e.findingCodes??[]),...TO({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(bl),o=RO(e.revision),s=CO(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:NO,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(bO,c)}}et();ue();import{createHash as jO}from"node:crypto";import Gb from"node:path";var $O="comet.native.conflict-radar.v1",ze=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}),OO="comet.native.conflict-radar.v1",HO="comet.native.conflict-radar-signals.v1",DO=/^[a-f0-9]{64}$/u,Kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BO=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),FO=new Set(["capability","operation","baseHash"]),LO=new Set(["path","kind"]);function Mn(e,t){return e<t?-1:e>t?1:0}function oh(e){return Buffer.byteLength(e,"utf8")}function sh(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 ch(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(oh(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function qO(e,t){let r=ch(e,t,ze.maxArtifactPathBytes),i=Gb.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)||Gb.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 Yb(e,t){if(typeof e!="string"||!DO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MO(e,t){let r=sh(e,FO,t),i=ch(r.capability,`${t} capability`,ze.maxCapabilityBytes);if(!Kb.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:Yb(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 VO(e,t){let r=sh(e,LO,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:qO(r.path,`${t} path`),kind:r.kind}}function WO(e,t){let r=sh(e,BO,`Conflict radar change ${t}`),i=ch(r.name,`Conflict radar change ${t} name`,ze.maxNameBytes);if(!Kb.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>ze.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>ze.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>MO(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>Mn(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)=>VO(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>Mn(c.path,l.path)||Mn(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:Yb(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function zO(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ze.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(WO).sort((n,a)=>Mn(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)>ze.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ze.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function GO(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 JO(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 UO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function KO(e,t){let r=[],i=jO("sha256").update(`${HO}
|
|
249
|
+
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Yn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<ze.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(GO(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=JO(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:UO(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function Jb(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function YO(e,t){return Jb(e.classification)-Jb(t.classification)||Mn(e.left,t.left)||Mn(e.right,t.right)}function Ub(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:$O,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 Xb(e){let t=zO(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(KO(t[s],t[c]));r.sort(YO);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(OO,{changes:t,relationships:i}),a=r.slice(0,ze.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Ub(t,r,a,n);for(;a.length>0&&oh(JSON.stringify(o))>ze.maxSerializedBytes;)a=a.slice(0,-1),o=Ub(t,r,a,n);if(oh(JSON.stringify(o))>ze.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}ti();wt();var XO=4096;async function QO(e,t=ze.maxChanges){try{let r=await Ka({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 Qb(e,t){let r=await sr(e,t),[i,n]=await Promise.all([r.implementation_scope?pl(e,t,r.implementation_scope):null,or(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 kl(e,t,r={}){let n=(await QO(e,XO)).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 Qb(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await Qb(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Xb([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"]:[]]}}Je();U();Va();et();ti();yn();Ii();ul();import{execFile as lH}from"node:child_process";Hi();Gn();hf();import{promisify as uH}from"node:util";Se();ae();Tf();U();jt();import{constants as lh,promises as ut}from"node:fs";import Vn from"node:path";var eH=/^[a-f0-9]{64}$/u,tH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function rH(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Qe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function iH(e,t){let r=Vn.resolve(e),i=Vn.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["",...Vn.relative(r,i).split(Vn.sep).filter(Boolean)]){o&&(a=Vn.join(a,o));let s=await ut.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await ut.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 ek(e){for(let t of e){let r=await ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!rH(t,r)||await ut.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function nH(e){if(!eH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function aH(e){let t=tH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function oH(e,t,r){return Or(Y(e,t),nH(r))}async function sH(e,t,r){let i=await iH(r,Vn.dirname(e)),n=await ut.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([ut.realpath(t),ut.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":lh.O_RDONLY|lh.O_NOFOLLOW|lh.O_NONBLOCK,c=await ut.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(),ut.lstat(e),ut.realpath(e)]);if(await ek(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Sl(n,l)||!Sl(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(),ut.lstat(e),ut.realpath(e)]);if(await ek(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!Sl(l,h)||!Sl(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 tk(e,t,r){let i=aH(r),n=Y(e,t),a=oH(e,t,i),o=we(e,a);await K(o,a);let s=XN(await sH(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}ti();Se();Ri();var Bo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};yn();Ro();Ii();var R9=64*1024;var P9=3600*1e3;var _9=uH(lH);var dH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function rk(e,t){let r=[];for(let i of dH){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 ik(e){if(e.receipt.kind!=="static-inspection")return null;let t=await tk(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}Ro();var ii=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 pH(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 fH(e){let t=pH(e.bundle.baseline),r=await _p(e.paths,t,{origin:"explicit",now:e.now});return Cf({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 ak(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Po(e.paths,e.state.name,e.state.implementation_scope),r=await En({changeDir:Ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await fH({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 ok(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await ak(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 hH(e){let t=await ne({root:Ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:lw(t.text)}}function mH(e){let{receipt:t,implementationScope:r}=e,i=[],n=xf({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 vH(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:Of(e.implementationScope.scope.declaredArtifacts)}}async function nk(e){let t=await _o(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=rk(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 ii([{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 ik({paths:e.paths,state:e.state,receipt:t});if(n){let a=mH({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 gH(e){let t=vH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await nk({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof ii)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 nk({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof ii)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 ii(r)}function uh(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function dh(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:uh(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([ak(e),Hn(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:uh(e.state.verification_result,"stale"),envelope:null};let i=await hH({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 gH({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:uh(e.state.verification_result,"invalid"),envelope:null}}}function yH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function ck(e){try{return await wH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function NH(e,t){try{return(await ne({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function bH(e,t,r){let i=ao(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=sk.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await NH(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await ne({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 kH(e,t){return ck(Kf(e,t))}async function ph(e){let t=e.now??new Date,r=await sr(e.paths,e.name),i=await or(e.paths,e.name),n=await Te(e.paths.projectRoot),a=yH(r.name,t),o=sk.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=>bH(e.paths,r.name,m))),dh({paths:e.paths,state:r,now:t}),kl(e.paths,r.name),Fc(e.paths,r.name),gy(e.paths,r.name),kH(e.paths,r.name),ck(o)]);return zb({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]})}U();ti();Ro();Ii();async function SH(e,t){let r=Y(e,t.name),i=await bn(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 Ni(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function EH(e,t){let r=await SH(e,t);return{committed:r,latest:Nb(r),history:yb(r)}}async function lk(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await EH(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)}}ti();wt();U();function Fo(e,t){try{return Ha(e,t)}catch{return}}var mr=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function CH(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function RH(e){return(await ub(e))?.change??null}function PH(e,t,r=!1,i){return gl({state:e,archiveReady:t,evidenceRetreat:r}).command}async function _H(e,t){let r=Ne(e,t.name),i=[...(await Lc(r,t.brief)).findings,...(await Cy(e,t)).findings,...await db(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Cc(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 Uw(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 En({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 Ab(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 Vp(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 fh(e,t,r){let i=await RH(e)===t,n=await Kd(e,t),a=await to(e,t),o;try{let y=await Fp(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:Fo(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:Fo(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:Fo(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=eh({paths:e,state:o,findings:[y]}),O=gl({state:o,findings:C});return{name:o.name,artifacts:Fo(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:th(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 Mb({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await lk(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 En({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 Q=await Hn(e,o.name,o.verification_evidence);for(let Pe of Q.acceptanceTrace.entries)C.set(Pe.acceptanceId,Pe.status==="failed"?"failed":Pe.status==="missing"?"missing":"satisfied")}let O=ow({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:CH(j),nextPageArgs:j}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await kl(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 or(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await Sn({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 Hc({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 ok({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 ph({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 _H(e,o),...s.findings,...d,...p,...f,...l,...v].filter((y,C,O)=>O.findIndex(j=>j.code===y.code&&j.path===y.path)===C),b=eh({paths:e,state:o,findings:g}),k=b.filter(y=>!kn(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:Fo(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:PH(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:th(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:gl({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:Nl,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 uk(e){let t;try{t=await Np({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await xH.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>mr.maxChanges))throw new Error(`Native status exceeds ${mr.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 mh=Kt(It(),1);ot();ue();et();gt();import{promises as AH}from"node:fs";import hh from"node:path";var El=class extends Error{};async function Cl(e,t){let r=await ne({root:e.nativeRoot,ref:hh.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,mh.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new El("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:qe(i)}}async function pk(e,t,r){let i;try{i=await AH.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=hh.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await Cl(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof El)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 xl(e){return T("comet.native.status-record.v1",e)}function dk(e){let t=hh.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Ve(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=qe((0,mh.parse)(Ve(e.projectRoot,["show",`${r}:${t}`])));return xl(i)===xl(e.state)?r:null}catch{return null}}function fk(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=dk(e),i=dk(t);if(!r||!i)return!1;try{return Ve(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function hk(e,t){return e.state.archived&&t.state.archived&&xl(e.state)===xl(t.state)}import Sk from"node:path";import{promises as mk}from"node:fs";import IH from"node:path";ue();var TH=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),jH=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),$H=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),OH=new Set(["status","summary"]);function Rl(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Pl(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 HH(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function ji(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function DH(e,t,r,i){let n=Rl(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Pl(n,TH,"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=Rl(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Pl(o,jH,"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=Rl(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Pl(c,OH,"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=Rl(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:m,...h}=p,v=Pl(h,$H,`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!==T("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||!HH(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 vk(e){let t=go(e.paths,e.state.name),r;try{let c=await mk.lstat(t);if(!c.isFile()||c.isSymbolicLink())return ji(t,"","Native Supervisor overlay is not a regular file");r=await mk.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:ji(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return ji(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=IH.join(e.paths.changesDir,e.state.name),a;try{a=await Vt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return ji(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 Ue(e.paths,e.state.name)}catch(c){return ji(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return ji(t,r,"Native Supervisor overlay disappeared during inspection");let s=DH(i,e.state,a.contract,o);return s?ji(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}}za();Ci();function be(e,t,r){return e.language==="zh-CN"?r:t}function BH(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:be(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:be(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:be(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(be(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(be(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"?be(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):be(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} ${be(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:be(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:be(e,"Accept the result","接受结果"),agentInstruction:be(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)>=Zc)??!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(be(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(be(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 FH(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 LH(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:be(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:be(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Nk(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function $i(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function gk(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function qH(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function wk(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function MH(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function VH(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Jt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Nk({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[$i("summary","--summary"),qH(e.name,e.flag)]}}function yk(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:be(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function WH(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function _l(e){return[Jt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Jt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function zH(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 Lo(e,t,r={}){let i=MH(t)&&e.coordination_mode===void 0,n=BH(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:[$i("summary","--summary")],commandAlternatives:i?uw.map(s=>{let c=Jt({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,wk("coordination-mode","--coordination-mode",[s])]}}):[Jt({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:[$i("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=Jt({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]}}):[],Jt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),..._l({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:[$i("summary","--summary")],commandAlternatives:[Jt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Jt({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:[$i("summary","--summary")],commandAlternatives:[Jt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),..._l({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:[$i("summary","--summary")],commandAlternatives:_l({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:_l({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?Nk({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:VH({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:[gk()],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)>=Zc)??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:be(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]:[$i("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=gk();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} ${be(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:zH([{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=yk(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>WH(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:yk(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:[wk("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...LH(e)],userCommunication:FH(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Jt({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 bk from"node:path";function kk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function vh(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:kk(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:kk(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=>bk.relative(t.projectRoot,bk.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}U();function Ek(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function xk(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 Ck(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:UH(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:KH(i,r)}))]:[]]}function Rk(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 GH(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=Up(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 Al(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:Sk.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 gh(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=vh(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...Lo(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:{...Lo(t).runnerAction,kind:"none"}}:Lo(t),c=e.details?Ck(t,null,[]):[],l=xk(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?Ek(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:Ha(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:Sk.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:Rk(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 JH(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 Il(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function UH(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:Il(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function KH(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:Il(e.summary,t)??""}}async function Pk(e){let t=await Yp(e),r=vh(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await wo({paths:e.paths,state:t.state}),a=await vk({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Ue(e.paths,e.name,{diagnostics:!0}),s=o?{...Al(e.paths,t.state,e.gitContext),projectRoot:"."}:Al(e.paths,t.state,e.gitContext),c=Lo(t.state,n,{verifierExecutionRef:Jp(t.state,t.local),verifierStartup:Up(t.state,t.localStatus==="available"?t.local:null),...t.local?{verificationCheckPlans:lb(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?JH(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:Il(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let S=Il(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=Ck(t.state,o,u),v=xk(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?Ek(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:Ha(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:Rk(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=GH(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 k3,constants as S3,promises as wh}from"node:fs";import Wn from"node:path";ae();Di();ot();il();Di();var _k="comet.native.workspace-finish.v1",Ik="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Tk=new RegExp(`^${Ik}$`,"u"),XH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,qo=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Ak(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function QH(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"||!Tk.test(t.name)||typeof t.transactionId!="string"||!XH.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Wn.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"&&Wn.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!Wn.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");Ak(r.commitMessage,"commit-message"),r.mergeMessage!==null&&Ak(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||!qo.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!Wn.posix.isAbsolute(i)&&!Wn.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!qo.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!qo.test(r.target)||!qo.test(r.source)||r.sha!==null&&!qo.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:_k,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 ZH(e,t){if(!Tk.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Wn.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function yh(e,t,r={}){let i=ZH(e,t);try{let n=await wh.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=QH(JSON.parse(await wh.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 jk(e,t={}){let r;try{r=await wh.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-(${Ik})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await yh(e,a[1],t);o&&i.push(o)}return i}var tD=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Tl(e,t){let r=vr.normalize(Nh(e)),i=vr.normalize(Nh(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Nh(e){let t=vr.resolve(e);try{return eD.native(t)}catch{return t}}function rD(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function $k(e,t){let r=[];for(let i of await uk(e))t!==void 0&&i!==t||r.push({name:i,kind:await Vc(e,i)?"portable":"legacy"});return r}async function Bk(e,t){let r=vr.resolve(e),i=Go(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>Tl(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>vr.resolve(l)).sort()){let l=Tl(c,r)?r:c,u=Nh(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let p=await Te(l);if(!p)continue;let f=await tr(l,p.native.artifact_root);o.push({projectRoot:l,config:p,paths:f,gitContext:Kn(l,i)??ve(l),changes:await $k(f,t)})}if(o.length===0){let c=await Te(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await tr(e,c.native.artifact_root);o.push({projectRoot:vr.resolve(e),config:c,paths:l,gitContext:Kn(e,i)??ve(e),changes:await $k(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await pk(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 yh(c.paths,t,{onError:l})].filter(u=>u!==null):await jk(c.paths,{onError:l})}return o}function Ok(e,t){return e.workspace.bindingState==="aligned"?0:Tl(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function Fk(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 St(d.paths,n);return{source:d,name:n,kind:p,workspace:Al(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 to(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=gh({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 Cl(p.source.paths,vr.join(p.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(p=>[...o,...s.filter(f=>!hk(p.record,f.record))].every(f=>f.record&&fk(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)=>Ok(d,e)-Ok(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>mr.maxChanges)throw new Error(`Native status discovery exceeds ${mr.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function Hk(e,t){let r=t.toString(36),i=T("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function iD(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=tD.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or 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 workspace status cursor offset is invalid");let i=T("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:r});if(t[3]!==i)throw new Error("Native workspace status cursor integrity failed");return r}function Dk(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?rD(r):null,nextPageArgs:r}}async function nD(e,t,r){let i=await to(e.source.paths,e.name),n=null;try{n=await yy(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}}}:fh(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 bh(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 gh({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await Pk({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return bh({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return nD(e,t,r)}async function Lk(e){let{sources:t,candidates:r}=await aD(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>Tl(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),fh(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),bh(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function aD(e,t){let r=await Bk(e,t),i=(await Fk(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}}async function qk(e){let t=await Bk(e.projectRoot),r=await Fk(e.projectRoot,t),i=T("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=iD({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+mr.maxItems).map(u=>bh(u,!1))),o=[],s=r.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],p=n+d.length,f=p<r.length?Hk(i,p):null,m={schema:s,total:r.length,offset:n,items:d,nextCursor:f,...Dk(vr.resolve(e.projectRoot),f),limits:{...mr}};if(Buffer.byteLength(JSON.stringify(m),"utf8")>mr.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<r.length?Hk(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...Dk(vr.resolve(e.projectRoot),l),limits:{...mr}}}ja();import Mo from"path";import{realpathSync as ED}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 gr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Vk(e){return e?e.command?`${gr.next} ${e.command}`:e.ask_user?`${gr.next} ${e.ask_user}`:null:null}function Wk(e,t){let r=[e.summary],i=Vk(e.next);return i&&r.push(i),e.user_message&&r.push("",gr.relay,e.user_message),t!==void 0&&r.push("",gr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
173
250
|
`)}
|
|
174
|
-
`}function
|
|
175
|
-
`)}
|
|
176
|
-
`)}}let r=t.continuation;if(
|
|
251
|
+
`}function zk(e,t,r){let i=[e.summary],n=Vk(e.next);return n&&i.push(n),e.user_message&&i.push("",gr.relay,e.user_message),i.push("",`${gr.detail} ${t}`),r!==void 0&&i.push("",gr.details,JSON.stringify(r,null,2)),i.join(`
|
|
252
|
+
`)}Lt();wt();ae();jt();U();wt();yc();ae();pi();ti();var x5=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Lt();Da();Se();U();wt();yc();var jl=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"},$l=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"};U();Je();function L(e,t,r){return e==="zh-CN"?r:t}var kh={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Gk(e,t){return typeof e=="string"&&kh[e]?L(t,kh[e].en,kh[e].zh):typeof e=="string"?e:""}function Sh(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 lD(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 Jk(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 Uk(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 Eh(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function uD(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 dD(e,t,r){let i=Eh(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=Gk(e.phase,i),s=uD(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Jk(t,i));let c=e.userCommunication,l=Kk(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Kk(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 pD(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function fD(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Gk(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=Sh(e.acceptance)?`${L(t,", ",",")}${Jk(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function hD(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 mD(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 vD(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=gD(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 gD(e){return Uk(e)?Kk(e,Eh(e)):void 0}function Yk(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(mD(t))return vD(t);if(pD(t)){let i=hD(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=>fD(a,i))].join(`
|
|
253
|
+
`)}}let r=t.continuation;if(Uk(r)){let i=Eh(r),n=dD(r,wD(t),ND(t,i));return yD(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 wD(e){if(Sh(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Sh(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return lD(r.acceptance)}return null}function yD(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 ND(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 Xk(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}}uc();dc();var Qk=["--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."],xh=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:Qk,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
|
|
177
254
|
comet native spec remove <change-name> <capability>
|
|
178
255
|
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>]
|
|
179
256
|
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>]
|
|
180
|
-
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
|
|
181
|
-
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
|
|
257
|
+
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>]
|
|
258
|
+
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 Ol(e,t){return`${e}:
|
|
182
259
|
${t.map(r=>` ${r}`).join(`
|
|
183
|
-
`)}`}function
|
|
184
|
-
${r.output}`),r.examples&&i.push("",
|
|
260
|
+
`)}`}function bD(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return xh[r]||t.length>1&&xh[t[0]]?.subcommands?r:t[0]}function kD(e=[]){let t=bD(e),r=xh[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",Ol("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",Ol("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Qk];return n&&n.length>0&&i.push("",Ol("Options",n)),i.push("",`Output:
|
|
261
|
+
${r.output}`),r.examples&&i.push("",Ol("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
185
262
|
`)}
|
|
186
|
-
`}}var
|
|
187
|
-
`}function
|
|
188
|
-
`}:e.error?{exitCode:e.exitCode,stderr:i?
|
|
189
|
-
${
|
|
263
|
+
`}}var SD=kD().usage;var j8=10*1024*1024,Ut=class extends Error{};function Vo(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Ut(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Hl(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Ut(`${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 Ut(`${t} requires a value`);return e.splice(i,2),n}function eS(e){if(e.length>0)throw new Ut(`Unexpected argument: ${e[0]}`)}function Ch(e,t){let r=Mo.normalize(Zk(e)),i=Mo.normalize(Zk(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Zk(e){let t=Mo.resolve(e);try{return ED.native(t)}catch{return t}}function xD(e,t){let r=Mo.resolve(t,e),i=ve(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=ve(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!Ch(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||Ch(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:Ch(t,i.currentWorktreeRoot)?Mo.resolve(t):i.currentWorktreeRoot}async function tS(e,t=process.cwd()){return e?xD(e,t):Gd(t)}function rS(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}function iS(e){return JSON.stringify(e,null,2)+`
|
|
264
|
+
`}function nS(e,t,r){return{command:e,exitCode:0,data:t,text:r??iS(t)}}function CD(e,t){if(t instanceof io)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof ln)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 Wa)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Ut)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof jl)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 $l)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Dc)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 ro)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 nl)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Bc)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 ii)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Bo)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 aS(e,t){let r=CD(e,t),i=r.error;if(!i)return r;let n=Xk({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function RD(e,t,r=!1){let i=e.envelope??Yk(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:Mk(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}})+`
|
|
265
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?zk(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Wk(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==iS(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
266
|
+
${gr.details}
|
|
190
267
|
${JSON.stringify(e.data,null,2)}
|
|
191
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function
|
|
268
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function PD(e,t,r=!1){let i=RD(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 oS(e,t,r=!1){return PD(e,t,r).output}async function sS(e,t){let r=Vo(e,"--details"),i=Hl(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new Ut("status --details requires a change name");if(i&&n&&!r)throw new Ut("--cursor for a named status requires --details");eS(e);let a=t,o=n?await Lk({projectRoot:t,name:n,onSelectedRoot:s=>{a=s},details:r,...i?{detailsCursor:i}:{}}):await qk({projectRoot:t,...i?{cursor:i}:{}});return{...nS("status",o),executionCwd:a}}async function cS(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{Vo(n,"--json"),Vo(n,"--verbose"),c=Hl(n,"--project-root");let d=[...n,...a],p=async()=>{let f=await tS(c);return{executionCwd:f,...await t(d,f)}};l=rS(e,d)?await jh(p):await p()}catch(d){l=aS(e,d)}let u=oS(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
192
269
|
`)?"":`
|
|
193
|
-
`)),u.exitCode}process.exitCode=await
|
|
270
|
+
`)),u.exitCode}process.exitCode=await cS("status",sS);
|