@rpamis/comet 0.4.3 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +332 -332
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +109 -96
- package/assets/skills/comet/scripts/comet-check.mjs +117 -104
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +59 -59
- package/assets/skills/comet/scripts/comet-guard.mjs +173 -160
- package/assets/skills/comet/scripts/comet-handoff.mjs +110 -97
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +110 -97
- package/assets/skills/comet/scripts/comet-hook-router.mjs +269 -159
- package/assets/skills/comet/scripts/comet-intent.mjs +31 -31
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +104 -91
- package/assets/skills/comet/scripts/comet-runtime.mjs +272 -259
- package/assets/skills/comet/scripts/comet-state.mjs +204 -191
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +25 -25
- package/assets/skills/comet-archive/SKILL.md +4 -4
- package/assets/skills/comet-build/SKILL.md +4 -6
- package/assets/skills/comet-classic/SKILL.md +1 -1
- package/assets/skills/comet-classic/reference/scripts.md +9 -1
- package/assets/skills/comet-design/SKILL.md +0 -2
- package/assets/skills/comet-hotfix/SKILL.md +1 -3
- package/assets/skills/comet-native/SKILL.md +8 -7
- package/assets/skills/comet-native/reference/artifacts.md +7 -7
- package/assets/skills/comet-native/reference/clarification.md +4 -4
- package/assets/skills/comet-native/reference/commands.md +15 -13
- package/assets/skills/comet-native/reference/recovery.md +3 -3
- package/assets/skills/comet-native/reference/workspace.md +10 -4
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +230 -149
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +239 -161
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +232 -122
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +184 -107
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +219 -142
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +239 -161
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +205 -128
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +276 -195
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +204 -127
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +202 -125
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +203 -125
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +200 -123
- package/assets/skills/comet-open/SKILL.md +0 -2
- package/assets/skills/comet-tweak/SKILL.md +1 -1
- package/assets/skills/comet-verify/SKILL.md +0 -2
- package/assets/skills-zh/comet-archive/SKILL.md +4 -4
- package/assets/skills-zh/comet-build/SKILL.md +4 -6
- package/assets/skills-zh/comet-classic/SKILL.md +1 -1
- package/assets/skills-zh/comet-classic/reference/scripts.md +9 -1
- package/assets/skills-zh/comet-design/SKILL.md +0 -2
- package/assets/skills-zh/comet-hotfix/SKILL.md +1 -3
- package/assets/skills-zh/comet-native/SKILL.md +8 -7
- package/assets/skills-zh/comet-native/reference/artifacts.md +7 -7
- package/assets/skills-zh/comet-native/reference/clarification.md +4 -4
- package/assets/skills-zh/comet-native/reference/commands.md +16 -10
- package/assets/skills-zh/comet-native/reference/recovery.md +3 -3
- package/assets/skills-zh/comet-native/reference/workspace.md +10 -4
- package/assets/skills-zh/comet-open/SKILL.md +0 -2
- package/assets/skills-zh/comet-tweak/SKILL.md +1 -1
- package/assets/skills-zh/comet-verify/SKILL.md +0 -2
- package/bin/comet-daemon-router.js +23 -7
- package/bin/fast-runtime-router.js +1 -1
- package/dist/app/commands/daemon-server.d.ts.map +1 -1
- package/dist/app/commands/daemon-server.js +13 -2
- package/dist/app/commands/daemon-server.js.map +1 -1
- package/dist/domains/comet-classic/classic-archive-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-archive-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-archive-entry.js +5 -2
- package/dist/domains/comet-classic/classic-archive-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-branch-binding.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-branch-binding.js +5 -4
- package/dist/domains/comet-classic/classic-branch-binding.js.map +1 -1
- package/dist/domains/comet-classic/classic-check-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-check-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-check-entry.js +5 -2
- package/dist/domains/comet-classic/classic-check-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.js +68 -26
- package/dist/domains/comet-classic/classic-check-snapshot.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-guard-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-guard-entry.js +5 -2
- package/dist/domains/comet-classic/classic-guard-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-handoff-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-handoff-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-handoff-entry.js +5 -2
- package/dist/domains/comet-classic/classic-handoff-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-resume-probe.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-resume-probe.js +3 -2
- package/dist/domains/comet-classic/classic-resume-probe.js.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.d.ts +3 -1
- package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.js +34 -3
- package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.js +3 -2
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-entry.d.ts +1 -1
- package/dist/domains/comet-classic/classic-state-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-entry.js +5 -2
- package/dist/domains/comet-classic/classic-state-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-store.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-store.js +67 -1
- package/dist/domains/comet-classic/classic-store.js.map +1 -1
- package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
- package/dist/domains/comet-entry/resume-probe.js +3 -2
- package/dist/domains/comet-entry/resume-probe.js.map +1 -1
- package/dist/domains/comet-native/native-acceptance.d.ts +5 -1
- package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
- package/dist/domains/comet-native/native-acceptance.js +13 -2
- package/dist/domains/comet-native/native-acceptance.js.map +1 -1
- package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-archive-command.js +167 -37
- package/dist/domains/comet-native/native-archive-command.js.map +1 -1
- package/dist/domains/comet-native/native-artifact-language.d.ts +3 -1
- package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifact-language.js +4 -11
- package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
- package/dist/domains/comet-native/native-artifacts.d.ts +8 -1
- package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
- package/dist/domains/comet-native/native-artifacts.js +14 -2
- package/dist/domains/comet-native/native-artifacts.js.map +1 -1
- package/dist/domains/comet-native/native-builder-acceptance-review.d.ts +16 -0
- package/dist/domains/comet-native/native-builder-acceptance-review.d.ts.map +1 -0
- package/dist/domains/comet-native/native-builder-acceptance-review.js +65 -0
- package/dist/domains/comet-native/native-builder-acceptance-review.js.map +1 -0
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +8 -4
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.d.ts +4 -2
- package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.js +37 -9
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
- package/dist/domains/comet-native/native-cli.d.ts +4 -1
- package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli.js +9 -5
- package/dist/domains/comet-native/native-cli.js.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-doctor-command.js +144 -3
- package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
- package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -1
- package/dist/domains/comet-native/native-git-provenance.js +3 -2
- package/dist/domains/comet-native/native-git-provenance.js.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-native/native-hook-guard.js +56 -26
- package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
- package/dist/domains/comet-native/native-local-execution.d.ts +1 -0
- package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -1
- package/dist/domains/comet-native/native-local-execution.js +7 -0
- package/dist/domains/comet-native/native-local-execution.js.map +1 -1
- package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
- package/dist/domains/comet-native/native-lock.js +12 -0
- package/dist/domains/comet-native/native-lock.js.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts +2 -0
- package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.js +6 -0
- package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +57 -28
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-output-language.js +7 -0
- package/dist/domains/comet-native/native-output-language.js.map +1 -1
- package/dist/domains/comet-native/native-portable-acceptance.d.ts +2 -0
- package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-acceptance.js +11 -1
- package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -1
- package/dist/domains/comet-native/native-portable-archive.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-archive.js +3 -0
- package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.d.ts +14 -4
- package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.js +159 -60
- package/dist/domains/comet-native/native-portable-checks.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts +2 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +121 -39
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-requirements.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-requirements.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-requirements.js +61 -18
- package/dist/domains/comet-native/native-portable-requirements.js.map +1 -1
- package/dist/domains/comet-native/native-portable-shape-coordination.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-shape-coordination.js +18 -5
- package/dist/domains/comet-native/native-portable-shape-coordination.js.map +1 -1
- package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-state.js +10 -3
- package/dist/domains/comet-native/native-portable-state.js.map +1 -1
- package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-status.js +10 -4
- package/dist/domains/comet-native/native-portable-status.js.map +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts +2 -1
- package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-types.js.map +1 -1
- package/dist/domains/comet-native/native-portable-verification.d.ts +3 -0
- package/dist/domains/comet-native/native-portable-verification.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-verification.js +28 -35
- package/dist/domains/comet-native/native-portable-verification.js.map +1 -1
- package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts +2 -0
- package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-verifier-coordination.js +9 -0
- package/dist/domains/comet-native/native-portable-verifier-coordination.js.map +1 -1
- package/dist/domains/comet-native/native-runner-input-artifacts.d.ts +9 -0
- package/dist/domains/comet-native/native-runner-input-artifacts.d.ts.map +1 -0
- package/dist/domains/comet-native/native-runner-input-artifacts.js +102 -0
- package/dist/domains/comet-native/native-runner-input-artifacts.js.map +1 -0
- package/dist/domains/comet-native/native-runner-input.d.ts +90 -64
- package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
- package/dist/domains/comet-native/native-runner-input.js +107 -22
- package/dist/domains/comet-native/native-runner-input.js.map +1 -1
- package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-native/native-script-entry.js +9 -3
- package/dist/domains/comet-native/native-script-entry.js.map +1 -1
- package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-native/native-snapshot.js +7 -2
- package/dist/domains/comet-native/native-snapshot.js.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-verification-receipt-runtime.js +5 -4
- package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.d.ts +26 -0
- package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-finish.js +520 -15
- package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
- package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-qlcciI25.js → abnfDiagram-VCTEODGH-CFEU4PQU.js} +1 -1
- package/dist/domains/dashboard/web/assets/{arc-KVm4k9kp.js → arc-BeYYJor9.js} +1 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-YphM8Wtg.js +1 -0
- package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-C366RdBK.js → architectureDiagram-5GKGNRK7-CqTy4fyH.js} +1 -1
- package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-DAuTc2OO.js → blockDiagram-I7D4REHJ-SR_5S4SA.js} +1 -1
- package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-CFB0RZmL.js → c4Diagram-7LVT6UL2-DzphG2XS.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-BkwcGbYR.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-DTV6lyGQ.js → chunk-4HAMMTFA-BpthUtIs.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-DgJm4cEX.js → chunk-75Z2AOVW-CxAdhPhG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-NAtcgGZr.js → chunk-DU6HZSFF-5peVNfxp.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-BcFXHZMJ.js → chunk-F27PBJKO-CwG4xi2V.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-wNemar9b.js → chunk-GMAD6QVW-BuFFY783.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-BiVCDO9d.js → chunk-GVQU2GXP-OyUFmjE-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-D9GDj4b6.js → chunk-IMKFNOWR-DmTme45C.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-DkPl5vac.js → chunk-L3NEJ4N5-D6BHbKty.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-RbbxGqtJ.js → chunk-OSK3NFVY-CCz1v1Nv.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-B9_X57eT.js → chunk-P2QGCYS3-C1_7kDYS.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DE4bOH0D.js → chunk-POPQ4Y6H-buFKlAdG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Bo-W1iA1.js → chunk-PWAF6VOD-B_K6Jrsv.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BhLxs4rZ.js → chunk-SHT3W25Y-CRRLsXmS.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-BCXfn8uF.js → chunk-SVP7TREG-Q5zCQTul.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-DqSBgE5L.js → chunk-TICWLB2K-Zc5XaO5Z.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-Dbkt1xEZ.js → chunk-XXDRQBXY-BAIB2h_r.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DzpQhyL3.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DzpQhyL3.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-DrwNpMyX.js → cose-bilkent-JH36ORCC-C7jkFYhm.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-BbDlivxs.js → cynefin-OW5HDTMX-4yS-l7kx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DmLmRN42.js → cynefinDiagram-5FMLGOSQ-DAkfQ8jW.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-Cgm5DNgI.js → dagre-GXQ25YYZ-D3b16ruz.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-Bnht1X2m.js → diagram-S7CK7UJ4-BXZHtdNz.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-LELTI4PR.js → diagram-UQ7AKVKN-B4nIzofw.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-Do0fZuNG.js → diagram-VSXAHHWV-B6d7KNj1.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-B0rZTUwt.js → diagram-VX7I27RA-CHr0Rg8a.js} +1 -1
- package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-wn8xCc_j.js → diagram-Z3DM3KII-BO2IxR9N.js} +1 -1
- package/dist/domains/dashboard/web/assets/{dist-CYwDKy2m.js → dist-0wyW4qbm.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CMDOpP2T.js → ebnfDiagram-PWID7BFC-CHRK8Hyg.js} +1 -1
- package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-C2d43bdq.js → erDiagram-RLTQ6QDP-_HFHzZlc.js} +1 -1
- package/dist/domains/dashboard/web/assets/{es-BzaOcXwu.js → es-kjndkyYX.js} +1 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-CG-cVTEg.js +1 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-C3RaJz-z.js +1 -0
- package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-hTH7TzhY.js → ganttDiagram-EL5Y4UJY-CxhSw1PI.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-C3CCywb-.js → gitGraph-4MIJSDKK-Cbw-3Dnk.js} +1 -1
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-DW6jDckj.js → gitGraphDiagram-WWUBYQGX-Cx93hwtL.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-CTZPz_mx.js → index-CQb8j5OE.js} +3 -3
- package/dist/domains/dashboard/web/assets/{index-CWNqBYyI.css → index-Gaxnq6Jd.css} +1 -1
- package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-Bg3eKis8.js → info-A6RAGUB7--d4EMiIK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-7zk6ytVJ.js → infoDiagram-27XIBGKW-DMkRRNGB.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CGDCTmCQ.js → ishikawaDiagram-5VMMS53U-CjKh_jHT.js} +1 -1
- package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-C8_L_e8a.js → journeyDiagram-3NMN7TZE-CG735M_M.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-D5x6qTgM.js → kanban-definition-UXKFOSKX-CgXFmhFM.js} +1 -1
- package/dist/domains/dashboard/web/assets/{line-DC93oja4.js → line-Bhf8l3gG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{linear-81TNubkB.js → linear-YWT9mnmu.js} +1 -1
- package/dist/domains/dashboard/web/assets/{mermaid-parser.core-D60d8uy9.js → mermaid-parser.core-COzQ1kq0.js} +3 -3
- package/dist/domains/dashboard/web/assets/{mermaid.core-l4Wgjz2Q.js → mermaid.core-Cc1lMpx-.js} +4 -4
- package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-Dfqu1201.js → mindmap-definition-YA3MSWOX-B_VOgUSO.js} +1 -1
- package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CsFZBhTs.js → packet-AYTQ26CC-CXbJLNC9.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-myFMaA7n.js → pegDiagram-XKGWAZYB-BuS0hioo.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-FMuCTNSk.js → pie-WAS4IAKB-BEaGwdWZ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-CSR4B4Z1.js → pieDiagram-E7YTZNPT-DDzYv-_9.js} +1 -1
- package/dist/domains/dashboard/web/assets/purify.es-Bvo9QlJ8.js +3 -0
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-BiE4kEeP.js → quadrantDiagram-AXDQQJYC-DExT--Ut.js} +1 -1
- package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-BZ-n7JtG.js → radar-RG4KPBEZ-C1JtzGr8.js} +1 -1
- package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CWVtRfHu.js → railroad-74A4TZTK-CMpkXATR.js} +1 -1
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-BM35gYWg.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CN60GGp0.js +1 -0
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DRUSW4g7.js +1 -0
- package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-CBj7v1de.js → railroadDiagram-O6MQD6OU-BCE65sLR.js} +1 -1
- package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-DSDgb54n.js → requirementDiagram-BXWQKSXE-CmyX3vGG.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-1-oXLUAP.js → sankeyDiagram-P5KCCOFB-BFKrX2dv.js} +1 -1
- package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DAF4nGs_.js → sequenceDiagram-WJ2MYXX4-DqodS9W-.js} +1 -1
- package/dist/domains/dashboard/web/assets/{src-CTWLVUqE.js → src-BVUP3QzK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-DzENBaJT.js → stateDiagram-D77RDMKH-nHai_EZh.js} +1 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-BL6vE1m9.js +1 -0
- package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-CnxFUZJc.js → swimlanes-42K2YHIH-BODBARYN.js} +1 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-XHK_nuTj.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-KtvPzpZM.js → timeline-definition-24CTP7MA-RVnG8rgK.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bdu3P9iY.js → treeView-Q6P3EWNA-B6lrg3KQ.js} +1 -1
- package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-DFnn23JR.js → treemap-WGGIJYW6-CJfMKVf4.js} +1 -1
- package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-BjpviP26.js → vennDiagram-4TSXK5OY-CZMWJiN7.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-CEo4a-j4.js → wardley-WFR3VGLG-BoUsbNlx.js} +1 -1
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-Bf54n6im.js → wardleyDiagram-VM6X3IG4-BwBCykVb.js} +1 -1
- package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-CU-hI0Cm.js → xychartDiagram-S5SC5T6Z-vutnbx57.js} +1 -1
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/workflow-contract/hook-target-scope.d.ts.map +1 -1
- package/dist/domains/workflow-contract/hook-target-scope.js +2 -1
- package/dist/domains/workflow-contract/hook-target-scope.js.map +1 -1
- package/dist/platform/paths/git-worktree-cache.d.ts +3 -0
- package/dist/platform/paths/git-worktree-cache.d.ts.map +1 -0
- package/dist/platform/paths/git-worktree-cache.js +109 -0
- package/dist/platform/paths/git-worktree-cache.js.map +1 -0
- package/dist/platform/paths/git-worktree.d.ts +6 -0
- package/dist/platform/paths/git-worktree.d.ts.map +1 -1
- package/dist/platform/paths/git-worktree.js +191 -30
- package/dist/platform/paths/git-worktree.js.map +1 -1
- package/dist/platform/process/comet-daemon.d.ts +3 -0
- package/dist/platform/process/comet-daemon.d.ts.map +1 -1
- package/dist/platform/process/comet-daemon.js +8 -6
- package/dist/platform/process/comet-daemon.js.map +1 -1
- package/dist/platform/process/external-command.d.ts +3 -0
- package/dist/platform/process/external-command.d.ts.map +1 -1
- package/dist/platform/process/external-command.js +69 -2
- package/dist/platform/process/external-command.js.map +1 -1
- package/dist/platform/process/git.d.ts.map +1 -1
- package/dist/platform/process/git.js +3 -4
- package/dist/platform/process/git.js.map +1 -1
- package/dist/platform/process/hook-adapter.d.ts +2 -0
- package/dist/platform/process/hook-adapter.d.ts.map +1 -1
- package/dist/platform/process/hook-adapter.js +32 -3
- package/dist/platform/process/hook-adapter.js.map +1 -1
- package/dist/platform/process/hook-read-cache.d.ts +2 -0
- package/dist/platform/process/hook-read-cache.d.ts.map +1 -1
- package/dist/platform/process/hook-read-cache.js +25 -13
- package/dist/platform/process/hook-read-cache.js.map +1 -1
- package/dist/platform/process/process-identity.d.ts.map +1 -1
- package/dist/platform/process/process-identity.js +18 -51
- package/dist/platform/process/process-identity.js.map +1 -1
- package/dist/platform/process/runtime-metrics.d.ts +10 -1
- package/dist/platform/process/runtime-metrics.d.ts.map +1 -1
- package/dist/platform/process/runtime-metrics.js +37 -2
- package/dist/platform/process/runtime-metrics.js.map +1 -1
- package/dist/platform/process/windows-process-broker.d.ts +1 -0
- package/dist/platform/process/windows-process-broker.d.ts.map +1 -1
- package/dist/platform/process/windows-process-broker.js +70 -11
- package/dist/platform/process/windows-process-broker.js.map +1 -1
- package/dist/platform/process/windows-process-identity.d.ts +6 -0
- package/dist/platform/process/windows-process-identity.d.ts.map +1 -0
- package/dist/platform/process/windows-process-identity.js +190 -0
- package/dist/platform/process/windows-process-identity.js.map +1 -0
- package/package.json +1 -1
- package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-QeljAKq2.js +0 -1
- package/dist/domains/dashboard/web/assets/channel-_AqwP0KA.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-CRo4aB_7.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-CRo4aB_7.js +0 -1
- package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-KYANo3DQ.js +0 -1
- package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-CSROlLuj.js +0 -1
- package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +0 -3
- package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CkHwwI2i.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-8xzEHL6v.js +0 -1
- package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-nSHBw0tH.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-CNw52Fkn.js +0 -1
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-6TRvbqqI.js +0 -8
|
@@ -1,149 +1,149 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};
|
|
6
|
-
`)?
|
|
4
|
+
var IE=Object.create;var Xu=Object.defineProperty;var TE=Object.getOwnPropertyDescriptor;var $E=Object.getOwnPropertyNames;var jE=Object.getPrototypeOf,OE=Object.prototype.hasOwnProperty;var Os=(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 T=(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}},Qu=(e,t)=>{for(var r in t)Xu(e,r,{get:t[r],enumerable:!0})},HE=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of $E(t))!OE.call(e,n)&&n!==r&&Xu(e,n,{get:()=>t[n],enumerable:!(i=TE(t,n))||i.enumerable});return e};var fr=(e,t,r)=>(r=e!=null?IE(jE(e)):{},HE(t||!e||!e.__esModule?Xu(r,"default",{value:e,enumerable:!0}):r,e));var U=R(Ie=>{"use strict";var Zu=Symbol.for("yaml.alias"),tv=Symbol.for("yaml.document"),Hs=Symbol.for("yaml.map"),rv=Symbol.for("yaml.pair"),ed=Symbol.for("yaml.scalar"),Ds=Symbol.for("yaml.seq"),mr=Symbol.for("yaml.node.type"),DE=e=>!!e&&typeof e=="object"&&e[mr]===Zu,BE=e=>!!e&&typeof e=="object"&&e[mr]===tv,LE=e=>!!e&&typeof e=="object"&&e[mr]===Hs,qE=e=>!!e&&typeof e=="object"&&e[mr]===rv,iv=e=>!!e&&typeof e=="object"&&e[mr]===ed,FE=e=>!!e&&typeof e=="object"&&e[mr]===Ds;function nv(e){if(e&&typeof e=="object")switch(e[mr]){case Hs:case Ds:return!0}return!1}function ME(e){if(e&&typeof e=="object")switch(e[mr]){case Zu:case Hs:case ed:case Ds:return!0}return!1}var VE=e=>(iv(e)||nv(e))&&!!e.anchor;Ie.ALIAS=Zu;Ie.DOC=tv;Ie.MAP=Hs;Ie.NODE_TYPE=mr;Ie.PAIR=rv;Ie.SCALAR=ed;Ie.SEQ=Ds;Ie.hasAnchor=VE;Ie.isAlias=DE;Ie.isCollection=nv;Ie.isDocument=BE;Ie.isMap=LE;Ie.isNode=ME;Ie.isPair=qE;Ie.isScalar=iv;Ie.isSeq=FE});var wa=R(td=>{"use strict";var Ne=U(),Me=Symbol("break visit"),av=Symbol("skip children"),Wt=Symbol("remove node");function Bs(e,t){let r=ov(t);Ne.isDocument(e)?sn(null,e.contents,r,Object.freeze([e]))===Wt&&(e.contents=null):sn(null,e,r,Object.freeze([]))}Bs.BREAK=Me;Bs.SKIP=av;Bs.REMOVE=Wt;function sn(e,t,r,i){let n=sv(e,t,r,i);if(Ne.isNode(n)||Ne.isPair(n))return cv(e,i,n),sn(e,n,r,i);if(typeof n!="symbol"){if(Ne.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=sn(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Me)return Me;o===Wt&&(t.items.splice(a,1),a-=1)}}}else if(Ne.isPair(t)){i=Object.freeze(i.concat(t));let a=sn("key",t.key,r,i);if(a===Me)return Me;a===Wt&&(t.key=null);let o=sn("value",t.value,r,i);if(o===Me)return Me;o===Wt&&(t.value=null)}}return n}async function Ls(e,t){let r=ov(t);Ne.isDocument(e)?await cn(null,e.contents,r,Object.freeze([e]))===Wt&&(e.contents=null):await cn(null,e,r,Object.freeze([]))}Ls.BREAK=Me;Ls.SKIP=av;Ls.REMOVE=Wt;async function cn(e,t,r,i){let n=await sv(e,t,r,i);if(Ne.isNode(n)||Ne.isPair(n))return cv(e,i,n),cn(e,n,r,i);if(typeof n!="symbol"){if(Ne.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await cn(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Me)return Me;o===Wt&&(t.items.splice(a,1),a-=1)}}}else if(Ne.isPair(t)){i=Object.freeze(i.concat(t));let a=await cn("key",t.key,r,i);if(a===Me)return Me;a===Wt&&(t.key=null);let o=await cn("value",t.value,r,i);if(o===Me)return Me;o===Wt&&(t.value=null)}}return n}function ov(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 sv(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(Ne.isMap(t))return r.Map?.(e,t,i);if(Ne.isSeq(t))return r.Seq?.(e,t,i);if(Ne.isPair(t))return r.Pair?.(e,t,i);if(Ne.isScalar(t))return r.Scalar?.(e,t,i);if(Ne.isAlias(t))return r.Alias?.(e,t,i)}function cv(e,t,r){let i=t[t.length-1];if(Ne.isCollection(i))i.items[e]=r;else if(Ne.isPair(i))e==="key"?i.key=r:i.value=r;else if(Ne.isDocument(i))i.contents=r;else{let n=Ne.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}td.visit=Bs;td.visitAsync=Ls});var rd=R(uv=>{"use strict";var lv=U(),WE=wa(),zE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},GE=e=>e.replace(/[!,[\]{}]/g,t=>zE[t]),ya=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+GE(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&&lv.isNode(t.contents)){let a={};WE.visit(t.contents,(o,s)=>{lv.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(`
|
|
5
|
+
`)}};ya.defaultYaml={explicit:!1,version:"1.2"};ya.defaultTags={"!!":"tag:yaml.org,2002:"};uv.Directives=ya});var qs=R(ba=>{"use strict";var dv=U(),JE=wa();function UE(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 pv(e){let t=new Set;return JE.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function hv(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function KE(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=pv(e));let o=hv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(dv.isScalar(o.node)||dv.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}}ba.anchorIsValid=UE;ba.anchorNames=pv;ba.createNodeAnchors=KE;ba.findNewAnchor=hv});var id=R(fv=>{"use strict";function Na(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=Na(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=Na(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=Na(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=Na(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}fv.applyReviver=Na});var Hr=R(vv=>{"use strict";var YE=U();function mv(e,t,r){if(Array.isArray(e))return e.map((i,n)=>mv(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!YE.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}vv.toJS=mv});var Fs=R(wv=>{"use strict";var XE=id(),gv=U(),QE=Hr(),nd=class{constructor(t){Object.defineProperty(this,gv.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(!gv.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=QE.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?XE.applyReviver(a,{"":s},"",s):s}};wv.NodeBase=nd});var ka=R(yv=>{"use strict";var ZE=qs(),ex=wa(),ln=U(),tx=Fs(),rx=Hr(),ad=class extends tx.NodeBase{constructor(t){super(ln.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=[],ex.visit(t,{Node:(a,o)=>{(ln.isAlias(o)||ln.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||(rx.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Ms(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(ZE.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Ms(e,t,r){if(ln.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(ln.isCollection(t)){let i=0;for(let n of t.items){let a=Ms(e,n,r);a>i&&(i=a)}return i}else if(ln.isPair(t)){let i=Ms(e,t.key,r),n=Ms(e,t.value,r);return Math.max(i,n)}return 1}yv.Alias=ad});var we=R(od=>{"use strict";var ix=U(),nx=Fs(),ax=Hr(),ox=e=>!e||typeof e!="function"&&typeof e!="object",Dr=class extends nx.NodeBase{constructor(t){super(ix.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:ax.toJS(this.value,t,r)}toString(){return String(this.value)}};Dr.BLOCK_FOLDED="BLOCK_FOLDED";Dr.BLOCK_LITERAL="BLOCK_LITERAL";Dr.PLAIN="PLAIN";Dr.QUOTE_DOUBLE="QUOTE_DOUBLE";Dr.QUOTE_SINGLE="QUOTE_SINGLE";od.Scalar=Dr;od.isScalarValue=ox});var Sa=R(Nv=>{"use strict";var sx=ka(),wi=U(),bv=we(),cx="tag:yaml.org,2002:";function lx(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 ux(e,t,r){if(wi.isDocument(e)&&(e=e.contents),wi.isNode(e))return e;if(wi.isPair(e)){let d=r.schema[wi.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 sx.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=cx+t.slice(2));let l=lx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new bv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[wi.MAP]:Symbol.iterator in Object(e)?o[wi.SEQ]:o[wi.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 bv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Nv.createNode=ux});var Ws=R(Vs=>{"use strict";var dx=Sa(),zt=U(),px=Fs();function sd(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 dx.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 kv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,cd=class extends px.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=>zt.isNode(i)||zt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(kv(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(zt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,sd(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(zt.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&&zt.isScalar(a)?a.value:a:zt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!zt.isPair(r))return!1;let i=r.value;return i==null||t&&zt.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 zt.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(zt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,sd(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Vs.Collection=cd;Vs.collectionFromPath=sd;Vs.isEmptyPath=kv});var Ea=R(zs=>{"use strict";var hx=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ld(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var fx=(e,t,r)=>e.endsWith(`
|
|
6
|
+
`)?ld(r,t):r.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)r===
|
|
10
|
-
`&&
|
|
11
|
-
`&&
|
|
12
|
-
${t}${e.slice(0,
|
|
13
|
-
${t}${e.slice(
|
|
14
|
-
`);i=t,n=t+1,a=e[n]}return i}
|
|
15
|
-
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function
|
|
8
|
+
`+ld(r,t):(e.endsWith(" ")?"":" ")+r;zs.indentComment=ld;zs.lineComment=fx;zs.stringifyComment=hx});var Ev=R(xa=>{"use strict";var mx="flow",ud="block",Gs="quoted";function vx(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let p,h,f=!1,m=-1,v=-1,g=-1;r===ud&&(m=Sv(e,m,t.length),m!==-1&&(d=m+c));for(let N;N=e[m+=1];){if(r===Gs&&N==="\\"){switch(v=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(N===`
|
|
9
|
+
`)r===ud&&(m=Sv(e,m,t.length)),d=m+t.length+c,p=void 0;else{if(N===" "&&h&&h!==" "&&h!==`
|
|
10
|
+
`&&h!==" "){let y=e[m+1];y&&y!==" "&&y!==`
|
|
11
|
+
`&&y!==" "&&(p=m)}if(m>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===Gs){for(;h===" "||h===" ";)h=N,N=e[m+=1],f=!0;let y=m>g+1?m-2:v-1;if(u[y])return e;l.push(y),u[y]=!0,d=y+c,p=void 0}else f=!0}h=N}if(f&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let N=0;N<l.length;++N){let y=l[N],E=l[N+1]||e.length;y===0?w=`
|
|
12
|
+
${t}${e.slice(0,E)}`:(r===Gs&&u[y]&&(w+=`${e[y]}\\`),w+=`
|
|
13
|
+
${t}${e.slice(y+1,E)}`)}return w}function Sv(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!==`
|
|
14
|
+
`);i=t,n=t+1,a=e[n]}return i}xa.FOLD_BLOCK=ud;xa.FOLD_FLOW=mx;xa.FOLD_QUOTED=Gs;xa.foldFlowLines=vx});var Ca=R(xv=>{"use strict";var Rt=we(),Br=Ev(),Us=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Ks=e=>/^(%|---|\.\.\.)/m.test(e);function gx(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]===`
|
|
15
|
+
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Ra(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Ks(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${r}`)+"'";return t.implicitKey?i:
|
|
18
|
+
`,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:Br.foldFlowLines(o,a,Br.FOLD_QUOTED,Us(t,!1))}function dd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Ra(e,t);let r=t.indent||(Ks(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${r}`)+"'";return t.implicitKey?i:Br.foldFlowLines(i,r,Br.FOLD_FLOW,Us(t,!1))}function un(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Ra;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=dd:a&&!n?i=Ra:i=r?dd:Ra}return i(e,t)}var pd;try{pd=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{pd=/\n+(?!\n|$)/g}function Js({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 un(r,i);let l=i.indent||(i.forceBlockIndent||Ks(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===Rt.Scalar.BLOCK_FOLDED?!1:t===Rt.Scalar.BLOCK_LITERAL?!0:!gx(r,c,l.length);if(!r)return u?`|
|
|
24
24
|
`:`>
|
|
25
|
-
`;let
|
|
26
|
-
`&&
|
|
27
|
-
`);
|
|
28
|
-
`&&(
|
|
29
|
-
`)v
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
31
|
-
${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${
|
|
32
|
-
${l}${w}${r}${
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(
|
|
39
|
-
`:"",w){let x=l(w);
|
|
40
|
-
${
|
|
41
|
-
`&&
|
|
25
|
+
`;let d,p;for(p=r.length;p>0;--p){let E=r[p-1];if(E!==`
|
|
26
|
+
`&&E!==" "&&E!==" ")break}let h=r.substring(p),f=h.indexOf(`
|
|
27
|
+
`);f===-1?d="-":r===h||f!==h.length-1?(d="+",a&&a()):d="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
|
|
28
|
+
`&&(h=h.slice(0,-1)),h=h.replace(pd,`$&${l}`));let m=!1,v,g=-1;for(v=0;v<r.length;++v){let E=r[v];if(E===" ")m=!0;else if(E===`
|
|
29
|
+
`)g=v;else break}let w=r.substring(0,g<v?g+1:v);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let y=(m?l?"2":"1":"")+d;if(e&&(y+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=r.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=Us(i,!0);o!=="folded"&&t!==Rt.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{b=!0});let k=Br.foldFlowLines(`${w}${E}${h}`,l,Br.FOLD_BLOCK,x);if(!b)return`>${y}
|
|
31
|
+
${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${y}
|
|
32
|
+
${l}${w}${r}${h}`}function wx(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(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return un(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?un(a,t):Js(e,t,r,i);if(!s&&!u&&n!==Rt.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return Js(e,t,r,i);if(Ks(a)){if(c==="")return t.forceBlockIndent=!0,Js(e,t,r,i);if(s&&c===l)return un(a,t)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let p=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:f}=t.doc.schema;if(f.some(p)||h?.some(p))return un(a,t)}return s?d:Br.foldFlowLines(d,c,Br.FOLD_FLOW,Us(t,!1))}function yx(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!==Rt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Rt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Rt.Scalar.BLOCK_FOLDED:case Rt.Scalar.BLOCK_LITERAL:return n||a?un(o.value,t):Js(o,t,r,i);case Rt.Scalar.QUOTE_DOUBLE:return Ra(o.value,t);case Rt.Scalar.QUOTE_SINGLE:return dd(o.value,t);case Rt.Scalar.PLAIN:return wx(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}xv.stringifyString=yx});var Pa=R(hd=>{"use strict";var bx=qs(),Lr=U(),Nx=Ea(),kx=Ca();function Sx(e,t){let r=Object.assign({blockQuote:!0,commentString:Nx.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 Ex(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(Lr.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 xx(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Lr.isScalar(e)||Lr.isCollection(e))&&e.anchor;a&&bx.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 Rx(e,t,r,i){if(Lr.isPair(e))return e.toString(t,r,i);if(Lr.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=Lr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Ex(t.doc.schema.tags,a));let o=xx(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):Lr.isScalar(a)?kx.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Lr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}hd.createStringifyContext=Sx;hd.stringify=Rx});var _v=R(Pv=>{"use strict";var vr=U(),Rv=we(),Cv=Pa(),_a=Ea();function Cx({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=vr.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(vr.isCollection(e)||!vr.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let h=!d&&(!e||p&&t==null&&!r.inFlow||vr.isCollection(e)||(vr.isScalar(e)?e.type===Rv.Scalar.BLOCK_FOLDED||e.type===Rv.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let f=!1,m=!1,v=Cv.stringify(e,r,()=>f=!0,()=>m=!0);if(!h&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||t==null)return f&&i&&i(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||t==null&&h)return v=`? ${v}`,p&&!f?v+=_a.lineComment(v,r.indent,l(p)):m&&n&&n(),v;f&&(p=null),h?(p&&(v+=_a.lineComment(v,r.indent,l(p))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,p&&(v+=_a.lineComment(v,r.indent,l(p))));let g,w,N;vr.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,N=t.comment):(g=!1,w=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!h&&!p&&vr.isScalar(t)&&(r.indentAtStart=v.length+1),m=!1,!u&&c.length>=2&&!r.inFlow&&!h&&vr.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let y=!1,E=Cv.stringify(t,r,()=>y=!0,()=>m=!0),b=" ";if(p||g||w){if(b=g?`
|
|
39
|
+
`:"",w){let x=l(w);b+=`
|
|
40
|
+
${_a.indentComment(x,r.indent)}`}E===""&&!r.inFlow?b===`
|
|
41
|
+
`&&N&&(b=`
|
|
42
42
|
|
|
43
|
-
`):
|
|
44
|
-
${r.indent}`}else if(!
|
|
45
|
-
`),
|
|
46
|
-
${r.indent}`)}}else(
|
|
47
|
-
`)&&(
|
|
48
|
-
${c}${
|
|
49
|
-
`}}return e?(
|
|
50
|
-
`+
|
|
51
|
-
`)),
|
|
52
|
-
${a}${n}${
|
|
53
|
-
`;return`${
|
|
54
|
-
${n}${
|
|
55
|
-
`:" ")}return
|
|
43
|
+
`):b+=`
|
|
44
|
+
${r.indent}`}else if(!h&&vr.isCollection(t)){let x=E[0],k=E.indexOf(`
|
|
45
|
+
`),S=k!==-1,C=r.inFlow??t.flow??t.items.length===0;if(S||!C){let P=!1;if(S&&(x==="&"||x==="!")){let _=E.indexOf(" ");x==="&"&&_!==-1&&_<k&&E[_+1]==="!"&&(_=E.indexOf(" ",_+1)),(_===-1||k<_)&&(P=!0)}P||(b=`
|
|
46
|
+
${r.indent}`)}}else(E===""||E[0]===`
|
|
47
|
+
`)&&(b="");return v+=b+E,r.inFlow?y&&i&&i():N&&!y?v+=_a.lineComment(v,r.indent,l(N)):m&&n&&n(),v}Pv.stringifyPair=Cx});var md=R(fd=>{"use strict";var Av=Os("process");function Px(e,...t){e==="debug"&&console.log(...t)}function _x(e,t){(e==="debug"||e==="warn")&&(typeof Av.emitWarning=="function"?Av.emitWarning(t):console.warn(t))}fd.debug=Px;fd.warn=_x});var ec=R(Zs=>{"use strict";var Qs=U(),Iv=we(),Ys="<<",Xs={identify:e=>e===Ys||typeof e=="symbol"&&e.description===Ys,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Iv.Scalar(Symbol(Ys)),{addToJSMap:Tv}),stringify:()=>Ys},Ax=(e,t)=>(Xs.identify(t)||Qs.isScalar(t)&&(!t.type||t.type===Iv.Scalar.PLAIN)&&Xs.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Xs.tag&&r.default);function Tv(e,t,r){let i=$v(e,r);if(Qs.isSeq(i))for(let n of i.items)vd(e,t,n);else if(Array.isArray(i))for(let n of i)vd(e,t,n);else vd(e,t,i)}function vd(e,t,r){let i=$v(e,r);if(!Qs.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 $v(e,t){return e&&Qs.isAlias(t)?t.resolve(e.doc,e):t}Zs.addMergeToJSMap=Tv;Zs.isMergeKey=Ax;Zs.merge=Xs});var wd=R(Hv=>{"use strict";var Ix=md(),jv=ec(),Tx=Pa(),Ov=U(),gd=Hr();function $x(e,t,{key:r,value:i}){if(Ov.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(jv.isMergeKey(e,r))jv.addMergeToJSMap(e,t,i);else{let n=gd.toJS(r,"",e);if(t instanceof Map)t.set(n,gd.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=jx(r,n,e),o=gd.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 jx(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Ov.isNode(e)&&r?.doc){let i=Tx.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)+'..."'),Ix.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)}Hv.addPairToJSMap=$x});var qr=R(yd=>{"use strict";var Dv=Sa(),Ox=_v(),Hx=wd(),tc=U();function Dx(e,t,r){let i=Dv.createNode(e,void 0,r),n=Dv.createNode(t,void 0,r);return new rc(i,n)}var rc=class e{constructor(t,r=null){Object.defineProperty(this,tc.NODE_TYPE,{value:tc.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return tc.isNode(r)&&(r=r.clone(t)),tc.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Hx.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?Ox.stringifyPair(this,t,r,i):JSON.stringify(this)}};yd.Pair=rc;yd.createPair=Dx});var bd=R(Lv=>{"use strict";var yi=U(),Bv=Pa(),ic=Ea();function Bx(e,t,r){return(t.inFlow??e.flow?qx:Lx)(e,t,r)}function Lx({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 f=0;f<t.length;++f){let m=t[f],v=null;if(yi.isNode(m))!d&&m.spaceBefore&&p.push(""),nc(r,p,m.commentBefore,d),m.comment&&(v=m.comment);else if(yi.isPair(m)){let w=yi.isNode(m.key)?m.key:null;w&&(!d&&w.spaceBefore&&p.push(""),nc(r,p,w.commentBefore,d))}d=!1;let g=Bv.stringify(m,u,()=>v=null,()=>d=!0);v&&(g+=ic.lineComment(g,a,l(v))),d&&v&&(d=!1),p.push(i+g)}let h;if(p.length===0)h=n.start+n.end;else{h=p[0];for(let f=1;f<p.length;++f){let m=p[f];h+=m?`
|
|
48
|
+
${c}${m}`:`
|
|
49
|
+
`}}return e?(h+=`
|
|
50
|
+
`+ic.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function qx({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 f=0;f<e.length;++f){let m=e[f],v=null;if(yi.isNode(m))m.spaceBefore&&d.push(""),nc(t,d,m.commentBefore,!1),m.comment&&(v=m.comment);else if(yi.isPair(m)){let w=yi.isNode(m.key)?m.key:null;w&&(w.spaceBefore&&d.push(""),nc(t,d,w.commentBefore,!1),w.comment&&(l=!0));let N=yi.isNode(m.value)?m.value:null;N?(N.comment&&(v=N.comment),N.commentBefore&&(l=!0)):m.value==null&&w?.comment&&(v=w.comment)}v&&(l=!0);let g=Bv.stringify(m,c,()=>v=null);l||(l=d.length>u||g.includes(`
|
|
51
|
+
`)),f<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((w,N)=>w+N.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=ic.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:p,end:h}=r;if(d.length===0)return p+h;if(!l){let f=d.reduce((m,v)=>m+v.length+2,2);l=t.options.lineWidth>0&&f>t.options.lineWidth}if(l){let f=p;for(let m of d)f+=m?`
|
|
52
|
+
${a}${n}${m}`:`
|
|
53
|
+
`;return`${f}
|
|
54
|
+
${n}${h}`}else return`${p}${o}${d.join(" ")}${o}${h}`}function nc({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=ic.indentComment(t(i),e);r.push(a.trimStart())}}Lv.stringifyCollection=Bx});var Mr=R(kd=>{"use strict";var Fx=bd(),Mx=wd(),Vx=Ws(),Fr=U(),ac=qr(),Wx=we();function Aa(e,t){let r=Fr.isScalar(t)?t.value:t;for(let i of e)if(Fr.isPair(i)&&(i.key===t||i.key===r||Fr.isScalar(i.key)&&i.key.value===r))return i}var Nd=class extends Vx.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Fr.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(ac.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;Fr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new ac.Pair(t,t?.value):i=new ac.Pair(t.key,t.value);let n=Aa(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Fr.isScalar(n.value)&&Wx.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=Aa(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Aa(this.items,t)?.value;return(!r&&Fr.isScalar(n)?n.value:n)??void 0}has(t){return!!Aa(this.items,t)}set(t,r){this.add(new ac.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)Mx.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Fr.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})),Fx.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};kd.YAMLMap=Nd;kd.findPair=Aa});var dn=R(Fv=>{"use strict";var zx=U(),qv=Mr(),Gx={collection:"map",default:!0,nodeClass:qv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return zx.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>qv.YAMLMap.from(e,t,r)};Fv.map=Gx});var Vr=R(Mv=>{"use strict";var Jx=Sa(),Ux=bd(),Kx=Ws(),sc=U(),Yx=we(),Xx=Hr(),Sd=class extends Kx.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(sc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=oc(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=oc(t);if(typeof i!="number")return;let n=this.items[i];return!r&&sc.isScalar(n)?n.value:n}has(t){let r=oc(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=oc(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];sc.isScalar(n)&&Yx.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(Xx.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Ux.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(Jx.createNode(s,void 0,i))}}return a}};function oc(e){let t=sc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Mv.YAMLSeq=Sd});var pn=R(Wv=>{"use strict";var Qx=U(),Vv=Vr(),Zx={collection:"seq",default:!0,nodeClass:Vv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Qx.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Vv.YAMLSeq.from(e,t,r)};Wv.seq=Zx});var Ia=R(zv=>{"use strict";var eR=Ca(),tR={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),eR.stringifyString(e,t,r,i)}};zv.string=tR});var cc=R(Uv=>{"use strict";var Gv=we(),Jv={identify:e=>e==null,createNode:()=>new Gv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Gv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Jv.test.test(e)?e:t.options.nullStr};Uv.nullTag=Jv});var Ed=R(Yv=>{"use strict";var rR=we(),Kv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new rR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Kv.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Yv.boolTag=Kv});var hn=R(Xv=>{"use strict";function iR({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}Xv.stringifyNumber=iR});var Rd=R(lc=>{"use strict";var nR=we(),xd=hn(),aR={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:xd.stringifyNumber},oR={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():xd.stringifyNumber(e)}},sR={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 nR.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:xd.stringifyNumber};lc.float=sR;lc.floatExp=oR;lc.floatNaN=aR});var Pd=R(dc=>{"use strict";var Qv=hn(),uc=e=>typeof e=="bigint"||Number.isInteger(e),Cd=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Zv(e,t,r){let{value:i}=e;return uc(i)&&i>=0?r+i.toString(t):Qv.stringifyNumber(e)}var cR={identify:e=>uc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Cd(e,2,8,r),stringify:e=>Zv(e,8,"0o")},lR={identify:uc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Cd(e,0,10,r),stringify:Qv.stringifyNumber},uR={identify:e=>uc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Cd(e,2,16,r),stringify:e=>Zv(e,16,"0x")};dc.int=lR;dc.intHex=uR;dc.intOct=cR});var tg=R(eg=>{"use strict";var dR=dn(),pR=cc(),hR=pn(),fR=Ia(),mR=Ed(),_d=Rd(),Ad=Pd(),vR=[dR.map,hR.seq,fR.string,pR.nullTag,mR.boolTag,Ad.intOct,Ad.int,Ad.intHex,_d.floatNaN,_d.floatExp,_d.float];eg.schema=vR});var ng=R(ig=>{"use strict";var gR=we(),wR=dn(),yR=pn();function rg(e){return typeof e=="bigint"||Number.isInteger(e)}var pc=({value:e})=>JSON.stringify(e),bR=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:pc},{identify:e=>e==null,createNode:()=>new gR.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:pc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:pc},{identify:rg,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})=>rg(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:pc}],NR={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},kR=[wR.map,yR.seq].concat(bR,NR);ig.schema=kR});var Td=R(ag=>{"use strict";var Ta=Os("buffer"),Id=we(),SR=Ca(),ER={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ta.Buffer=="function")return Ta.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 Ta.Buffer=="function")s=o instanceof Ta.Buffer?o.toString("base64"):Ta.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=Id.Scalar.BLOCK_LITERAL),t!==Id.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===Id.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return SR.stringifyString({comment:e,type:t,value:s},i,n,a)}};ag.binary=ER});var mc=R(fc=>{"use strict";var hc=U(),$d=qr(),xR=we(),RR=Vr();function og(e,t){if(hc.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!hc.isPair(i)){if(hc.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new $d.Pair(new xR.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
|
|
57
|
-
${a.comment}`:i.comment}i=n}e.items[r]=As.isPair(i)?i:new Ju.Pair(i)}}else t("Expected a sequence for this tag");return e}function Km(e,t,r){let{replacer:i}=r,n=new $E.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(Ju.createPair(s,c,r))}return n}var OE={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Um,createNode:Km};Is.createPairs=Km;Is.pairs=OE;Is.resolvePairs=Um});var Ku=R(Uu=>{"use strict";var Ym=G(),Gu=kr(),sa=Pr(),HE=_r(),Xm=Ts(),ai=class e extends HE.YAMLSeq{constructor(){super(),this.add=sa.YAMLMap.prototype.add.bind(this),this.delete=sa.YAMLMap.prototype.delete.bind(this),this.get=sa.YAMLMap.prototype.get.bind(this),this.has=sa.YAMLMap.prototype.has.bind(this),this.set=sa.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(Ym.isPair(n)?(a=Gu.toJS(n.key,"",r),o=Gu.toJS(n.value,a,r)):a=Gu.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=Xm.createPairs(t,r,i),a=new this;return a.items=n.items,a}};ai.tag="tag:yaml.org,2002:omap";var DE={collection:"seq",identify:e=>e instanceof Map,nodeClass:ai,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Xm.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Ym.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new ai,r)},createNode:(e,t,r)=>ai.from(e,t,r)};Uu.YAMLOMap=ai;Uu.omap=DE});var rv=R(Yu=>{"use strict";var Qm=de();function Zm({value:e,source:t},r){return t&&(e?ev:tv).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var ev={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 Qm.Scalar(!0),stringify:Zm},tv={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 Qm.Scalar(!1),stringify:Zm};Yu.falseTag=tv;Yu.trueTag=ev});var iv=R(js=>{"use strict";var BE=de(),Xu=Wi(),LE={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},qE={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)}},FE={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 BE.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};js.float=FE;js.floatExp=qE;js.floatNaN=LE});var av=R(la=>{"use strict";var nv=Wi(),ca=e=>typeof e=="bigint"||Number.isInteger(e);function $s(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 Qu(e,t,r){let{value:i}=e;if(ca(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return nv.stringifyNumber(e)}var VE={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>$s(e,2,2,r),stringify:e=>Qu(e,2,"0b")},ME={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>$s(e,1,8,r),stringify:e=>Qu(e,8,"0")},WE={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>$s(e,0,10,r),stringify:nv.stringifyNumber},zE={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>$s(e,2,16,r),stringify:e=>Qu(e,16,"0x")};la.int=WE;la.intBin=VE;la.intHex=zE;la.intOct=ME});var ed=R(Zu=>{"use strict";var Ds=G(),Os=Cr(),Hs=Pr(),oi=class e extends Hs.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Ds.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Os.Pair(t.key,null):r=new Os.Pair(t,null),Hs.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Hs.findPair(this.items,t);return!r&&Ds.isPair(i)?Ds.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Hs.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Os.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(Os.createPair(o,null,i));return a}};oi.tag="tag:yaml.org,2002:set";var JE={collection:"map",identify:e=>e instanceof Set,nodeClass:oi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>oi.from(e,t,r),resolve(e,t){if(Ds.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new oi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Zu.YAMLSet=oi;Zu.set=JE});var rd=R(Bs=>{"use strict";var GE=Wi();function td(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 ov(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return GE.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 UE={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})=>td(e,r),stringify:ov},KE={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=>td(e,!1),stringify:ov},sv={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(sv.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 f=td(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Bs.floatTime=KE;Bs.intTime=UE;Bs.timestamp=sv});var uv=R(lv=>{"use strict";var YE=Vi(),XE=xs(),QE=Mi(),ZE=aa(),ex=zu(),cv=rv(),id=iv(),Ls=av(),tx=gs(),rx=Ku(),ix=Ts(),nx=ed(),nd=rd(),ax=[YE.map,QE.seq,ZE.string,XE.nullTag,cv.trueTag,cv.falseTag,Ls.intBin,Ls.intOct,Ls.int,Ls.intHex,id.floatNaN,id.floatExp,id.float,ex.binary,tx.merge,rx.omap,ix.pairs,nx.set,nd.intTime,nd.floatTime,nd.timestamp];lv.schema=ax});var Nv=R(sd=>{"use strict";var hv=Vi(),ox=xs(),mv=Mi(),sx=aa(),cx=Du(),ad=Lu(),od=Fu(),lx=Mm(),ux=Jm(),vv=zu(),ua=gs(),gv=Ku(),wv=Ts(),dv=uv(),yv=ed(),qs=rd(),fv=new Map([["core",lx.schema],["failsafe",[hv.map,mv.seq,sx.string]],["json",ux.schema],["yaml11",dv.schema],["yaml-1.1",dv.schema]]),pv={binary:vv.binary,bool:cx.boolTag,float:ad.float,floatExp:ad.floatExp,floatNaN:ad.floatNaN,floatTime:qs.floatTime,int:od.int,intHex:od.intHex,intOct:od.intOct,intTime:qs.intTime,map:hv.map,merge:ua.merge,null:ox.nullTag,omap:gv.omap,pairs:wv.pairs,seq:mv.seq,set:yv.set,timestamp:qs.timestamp},dx={"tag:yaml.org,2002:binary":vv.binary,"tag:yaml.org,2002:merge":ua.merge,"tag:yaml.org,2002:omap":gv.omap,"tag:yaml.org,2002:pairs":wv.pairs,"tag:yaml.org,2002:set":yv.set,"tag:yaml.org,2002:timestamp":qs.timestamp};function fx(e,t,r){let i=fv.get(t);if(i&&!e)return r&&!i.includes(ua.merge)?i.concat(ua.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(fv.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(ua.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?pv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(pv).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},[])}sd.coreKnownTags=dx;sd.getTags=fx});var ud=R(bv=>{"use strict";var cd=G(),px=Vi(),hx=Mi(),mx=aa(),Fs=Nv(),vx=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ld=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Fs.getTags(t,"compat"):t?Fs.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Fs.coreKnownTags:{},this.tags=Fs.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,cd.MAP,{value:px.map}),Object.defineProperty(this,cd.SCALAR,{value:mx.string}),Object.defineProperty(this,cd.SEQ,{value:hx.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?vx:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};bv.Schema=ld});var Sv=R(kv=>{"use strict";var gx=G(),dd=ra(),da=Qn();function wx(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=dd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(da.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(gx.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(da.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=dd.stringify(e.contents,n,()=>s=null,c);s&&(l+=da.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(dd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(r.push("..."),r.push(
|
|
57
|
+
${a.comment}`:i.comment}i=n}e.items[r]=hc.isPair(i)?i:new $d.Pair(i)}}else t("Expected a sequence for this tag");return e}function sg(e,t,r){let{replacer:i}=r,n=new RR.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($d.createPair(s,c,r))}return n}var CR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:og,createNode:sg};fc.createPairs=sg;fc.pairs=CR;fc.resolvePairs=og});var Hd=R(Od=>{"use strict";var cg=U(),jd=Hr(),$a=Mr(),PR=Vr(),lg=mc(),bi=class e extends PR.YAMLSeq{constructor(){super(),this.add=$a.YAMLMap.prototype.add.bind(this),this.delete=$a.YAMLMap.prototype.delete.bind(this),this.get=$a.YAMLMap.prototype.get.bind(this),this.has=$a.YAMLMap.prototype.has.bind(this),this.set=$a.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(cg.isPair(n)?(a=jd.toJS(n.key,"",r),o=jd.toJS(n.value,a,r)):a=jd.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=lg.createPairs(t,r,i),a=new this;return a.items=n.items,a}};bi.tag="tag:yaml.org,2002:omap";var _R={collection:"seq",identify:e=>e instanceof Map,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=lg.resolvePairs(e,t),i=[];for(let{key:n}of r.items)cg.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new bi,r)},createNode:(e,t,r)=>bi.from(e,t,r)};Od.YAMLOMap=bi;Od.omap=_R});var fg=R(Dd=>{"use strict";var ug=we();function dg({value:e,source:t},r){return t&&(e?pg:hg).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var pg={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 ug.Scalar(!0),stringify:dg},hg={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 ug.Scalar(!1),stringify:dg};Dd.falseTag=hg;Dd.trueTag=pg});var mg=R(vc=>{"use strict";var AR=we(),Bd=hn(),IR={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:Bd.stringifyNumber},TR={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():Bd.stringifyNumber(e)}},$R={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 AR.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:Bd.stringifyNumber};vc.float=$R;vc.floatExp=TR;vc.floatNaN=IR});var gg=R(Oa=>{"use strict";var vg=hn(),ja=e=>typeof e=="bigint"||Number.isInteger(e);function gc(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 Ld(e,t,r){let{value:i}=e;if(ja(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return vg.stringifyNumber(e)}var jR={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>gc(e,2,2,r),stringify:e=>Ld(e,2,"0b")},OR={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>gc(e,1,8,r),stringify:e=>Ld(e,8,"0")},HR={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>gc(e,0,10,r),stringify:vg.stringifyNumber},DR={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>gc(e,2,16,r),stringify:e=>Ld(e,16,"0x")};Oa.int=HR;Oa.intBin=jR;Oa.intHex=DR;Oa.intOct=OR});var Fd=R(qd=>{"use strict";var bc=U(),wc=qr(),yc=Mr(),Ni=class e extends yc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;bc.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new wc.Pair(t.key,null):r=new wc.Pair(t,null),yc.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=yc.findPair(this.items,t);return!r&&bc.isPair(i)?bc.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=yc.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new wc.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(wc.createPair(o,null,i));return a}};Ni.tag="tag:yaml.org,2002:set";var BR={collection:"map",identify:e=>e instanceof Set,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Ni.from(e,t,r),resolve(e,t){if(bc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ni,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};qd.YAMLSet=Ni;qd.set=BR});var Vd=R(Nc=>{"use strict";var LR=hn();function Md(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 wg(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return LR.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 qR={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})=>Md(e,r),stringify:wg},FR={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=>Md(e,!1),stringify:wg},yg={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(yg.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=Md(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$/,"")??""};Nc.floatTime=FR;Nc.intTime=qR;Nc.timestamp=yg});var kg=R(Ng=>{"use strict";var MR=dn(),VR=cc(),WR=pn(),zR=Ia(),GR=Td(),bg=fg(),Wd=mg(),kc=gg(),JR=ec(),UR=Hd(),KR=mc(),YR=Fd(),zd=Vd(),XR=[MR.map,WR.seq,zR.string,VR.nullTag,bg.trueTag,bg.falseTag,kc.intBin,kc.intOct,kc.int,kc.intHex,Wd.floatNaN,Wd.floatExp,Wd.float,GR.binary,JR.merge,UR.omap,KR.pairs,YR.set,zd.intTime,zd.floatTime,zd.timestamp];Ng.schema=XR});var Tg=R(Ud=>{"use strict";var Rg=dn(),QR=cc(),Cg=pn(),ZR=Ia(),eC=Ed(),Gd=Rd(),Jd=Pd(),tC=tg(),rC=ng(),Pg=Td(),Ha=ec(),_g=Hd(),Ag=mc(),Sg=kg(),Ig=Fd(),Sc=Vd(),Eg=new Map([["core",tC.schema],["failsafe",[Rg.map,Cg.seq,ZR.string]],["json",rC.schema],["yaml11",Sg.schema],["yaml-1.1",Sg.schema]]),xg={binary:Pg.binary,bool:eC.boolTag,float:Gd.float,floatExp:Gd.floatExp,floatNaN:Gd.floatNaN,floatTime:Sc.floatTime,int:Jd.int,intHex:Jd.intHex,intOct:Jd.intOct,intTime:Sc.intTime,map:Rg.map,merge:Ha.merge,null:QR.nullTag,omap:_g.omap,pairs:Ag.pairs,seq:Cg.seq,set:Ig.set,timestamp:Sc.timestamp},iC={"tag:yaml.org,2002:binary":Pg.binary,"tag:yaml.org,2002:merge":Ha.merge,"tag:yaml.org,2002:omap":_g.omap,"tag:yaml.org,2002:pairs":Ag.pairs,"tag:yaml.org,2002:set":Ig.set,"tag:yaml.org,2002:timestamp":Sc.timestamp};function nC(e,t,r){let i=Eg.get(t);if(i&&!e)return r&&!i.includes(Ha.merge)?i.concat(Ha.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Eg.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(Ha.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?xg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(xg).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},[])}Ud.coreKnownTags=iC;Ud.getTags=nC});var Xd=R($g=>{"use strict";var Kd=U(),aC=dn(),oC=pn(),sC=Ia(),Ec=Tg(),cC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Yd=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ec.getTags(t,"compat"):t?Ec.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ec.coreKnownTags:{},this.tags=Ec.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Kd.MAP,{value:aC.map}),Object.defineProperty(this,Kd.SCALAR,{value:sC.string}),Object.defineProperty(this,Kd.SEQ,{value:oC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?cC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};$g.Schema=Yd});var Og=R(jg=>{"use strict";var lC=U(),Qd=Pa(),Da=Ea();function uC(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=Qd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Da.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(lC.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Da.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Qd.stringify(e.contents,n,()=>s=null,c);s&&(l+=Da.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Qd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(r.push("..."),r.push(Da.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(Da.indentComment(a(c),"")))}return r.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}jg.stringifyDocument=uC});var Ba=R(Hg=>{"use strict";var dC=ka(),fn=Ws(),ht=U(),pC=qr(),hC=Hr(),fC=Xd(),mC=Og(),Zd=qs(),vC=id(),gC=Sa(),ep=rd(),tp=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ht.NODE_TYPE,{value:ht.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 ep.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,{[ht.NODE_TYPE]:{value:ht.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=ht.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){mn(this.contents)&&this.contents.add(t)}addIn(t,r){mn(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Zd.anchorNames(this);t.anchor=!r||i.has(r)?Zd.findNewAnchor(r||"a",i):r}return new dC.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=r.filter(v).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:h}=Zd.createNodeAnchors(this,o||"a"),f={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=gC.createNode(t,u,f);return s&&ht.isCollection(m)&&(m.flow=!0),p(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new pC.Pair(n,a)}delete(t){return mn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return fn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):mn(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return ht.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return fn.isEmptyPath(t)?!r&&ht.isScalar(this.contents)?this.contents.value:this.contents:ht.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return ht.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return fn.isEmptyPath(t)?this.contents!==void 0:ht.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=fn.collectionFromPath(this.schema,[t],r):mn(this.contents)&&this.contents.set(t,r)}setIn(t,r){fn.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=fn.collectionFromPath(this.schema,Array.from(t),r):mn(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 ep.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 ep.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 fC.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=hC.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"?vC.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 mC.stringifyDocument(this,t)}};function mn(e){if(ht.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Hg.Document=tp});var Fa=R(qa=>{"use strict";var La=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},rp=class extends La{constructor(t,r,i){super("YAMLParseError",t,r,i)}},ip=class extends La{constructor(t,r,i){super("YAMLWarning",t,r,i)}},wC=(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)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(
|
|
67
|
-
`+
|
|
68
|
-
`+
|
|
69
|
-
`+
|
|
70
|
-
`+x:k.comment=x,
|
|
71
|
-
`+
|
|
72
|
-
`+
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",
|
|
74
|
-
`;for(let
|
|
75
|
-
`):
|
|
76
|
-
`:!p
|
|
77
|
-
`&&(
|
|
65
|
+
`}};qa.YAMLError=La;qa.YAMLParseError=rp;qa.YAMLWarning=ip;qa.prettifyError=wC});var Ma=R(Dg=>{"use strict";function yC(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",p="",h=!1,f=!1,m=null,v=null,g=null,w=null,N=null,y=null,E=null;for(let k of e)switch(f&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f=!1),m&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),k.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(m=k),u=!0;break;case"comment":{u||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=k.source.substring(1)||" ";d?d+=p+S:d=S,p="",l=!1;break}case"newline":l?d?d+=k.source:(!y||r!=="seq-item-ind")&&(c=!0):p+=k.source,l=!0,h=!0,(v||g)&&(w=k),u=!0;break;case"anchor":v&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=k,E??(E=k.offset),l=!1,u=!1,f=!0;break;case"tag":{g&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),g=k,E??(E=k.offset),l=!1,u=!1,f=!0;break}case r:(v||g)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),y&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),y=k,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=k,l=!1,u=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,u=!1}let b=e[e.length-1],x=b?b.offset+b.source.length:n;return f&&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"),m&&(l&&m.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:y,spaceBefore:c,comment:d,hasNewline:h,anchor:v,tag:g,newlineAfterProp:w,end:x,start:E??x}}Dg.resolveProps=yC});var xc=R(Bg=>{"use strict";function np(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(np(t.key)||np(t.value))return!0}return!1;default:return!0}}Bg.containsNewline=np});var ap=R(Lg=>{"use strict";var bC=xc();function NC(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&bC.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Lg.flowIndentCheck=NC});var op=R(Fg=>{"use strict";var qg=U();function kC(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||qg.isScalar(a)&&qg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Fg.mapIncludes=kC});var Jg=R(Gg=>{"use strict";var Mg=qr(),SC=Mr(),Vg=Ma(),EC=xc(),Wg=ap(),xC=op(),zg="All mapping items must start at the same column";function RC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??SC.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:h,value:f}=u,m=Vg.resolveProps(d,{indicator:"explicit-key-ind",next:p??h?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!m.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",zg)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||EC.containsNewline(p))&&n(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",zg);r.atKey=!0;let g=m.end,w=p?e(r,p,m,n):t(r,g,d,null,m,n);r.schema.compat&&Wg.flowIndentCheck(i.indent,p,n),r.atKey=!1,xC.mapIncludes(r,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let N=Vg.resolveProps(h??[],{indicator:"map-value-ind",next:f,offset:w.range[2],onError:n,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=N.end,N.found){v&&(f?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<N.found.offset-1024&&n(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let y=f?e(r,f,N,n):t(r,c,h,null,N,n);r.schema.compat&&Wg.flowIndentCheck(i.indent,f,n),c=y.range[2];let E=new Mg.Pair(w,y);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{v&&n(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(w.comment?w.comment+=`
|
|
68
|
+
`+N.comment:w.comment=N.comment);let y=new Mg.Pair(w);r.options.keepSourceTokens&&(y.srcToken=u),s.items.push(y)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Gg.resolveBlockMap=RC});var Kg=R(Ug=>{"use strict";var CC=Vr(),PC=Ma(),_C=ap();function AC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??CC.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=PC.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 h=d?e(r,d,p,n):t(r,p.end,u,null,p,n);r.schema.compat&&_C.flowIndentCheck(i.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[i.offset,c,l??c],s}Ug.resolveBlockSeq=AC});var vn=R(Yg=>{"use strict";function IC(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}}Yg.resolveEnd=IC});var ew=R(Zg=>{"use strict";var TC=U(),$C=qr(),Xg=Mr(),jC=Vr(),OC=vn(),Qg=Ma(),HC=xc(),DC=op(),sp="Block collections are not allowed within flow collections",cp=e=>e&&(e.type==="block-map"||e.type==="block-seq");function BC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Xg.YAMLMap:jC.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:w,key:N,sep:y,value:E}=g,b=Qg.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:N??y?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!y&&!E){v===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+b.comment:l.comment=b.comment),d=b.end;continue}!o&&r.options.strict&&HC.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let x="";e:for(let k of w)switch(k.type){case"comma":case"space":break;case"comment":x=k.source.substring(1);break e;default:break e}if(x){let k=l.items[l.items.length-1];TC.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
|
|
70
|
+
`+x:k.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!y&&!b.found){let x=E?e(r,E,b,n):t(r,b.end,y,null,b,n);l.items.push(x),d=x.range[2],cp(E)&&n(x.range,"BLOCK_IN_FLOW",sp)}else{r.atKey=!0;let x=b.end,k=N?e(r,N,b,n):t(r,x,w,null,b,n);cp(N)&&n(k.range,"BLOCK_IN_FLOW",sp),r.atKey=!1;let S=Qg.resolveProps(y??[],{flow:s,indicator:"map-value-ind",next:E,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(S.found){if(!o&&!b.found&&r.options.strict){if(y)for(let _ of y){if(_===S.found)break;if(_.type==="newline"){n(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<S.found.offset-1024&&n(S.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(S.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=E?e(r,E,S,n):S.found?t(r,S.end,y,null,S,n):null;C?cp(E)&&n(C.range,"BLOCK_IN_FLOW",sp):S.comment&&(k.comment?k.comment+=`
|
|
71
|
+
`+S.comment:k.comment=S.comment);let P=new $C.Pair(k,C);if(r.options.keepSourceTokens&&(P.srcToken=g),o){let _=l;DC.mapIncludes(r,_.items,k)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),_.items.push(P)}else{let _=new Xg.YAMLMap(r.schema);_.flow=!0,_.items.push(P);let j=(C??k).range;_.range=[k.range[0],j[1],j[2]],l.items.push(_)}d=C?C.range[2]:S.end}}let p=o?"}":"]",[h,...f]=i.end,m=d;if(h?.source===p)m=h.offset+h.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),h&&h.source.length!==1&&f.unshift(h)}if(f.length>0){let v=OC.resolveEnd(f,m,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+v.comment:l.comment=v.comment),l.range=[i.offset,m,v.offset]}else l.range=[i.offset,m,m];return l}Zg.resolveFlowCollection=BC});var rw=R(tw=>{"use strict";var LC=U(),qC=we(),FC=Mr(),MC=Vr(),VC=Jg(),WC=Kg(),zC=ew();function lp(e,t,r,i,n,a){let o=r.type==="block-map"?VC.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?WC.resolveBlockSeq(e,t,r,i,a):zC.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 GC(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:h}=i,f=p&&a?p.offset>a.offset?p:a:p??a;f&&(!h||h.offset<f.offset)&&n(f,"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===FC.YAMLMap.tagName&&s==="map"||o===MC.YAMLSeq.tagName&&s==="seq")return lp(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),lp(e,t,r,n,o)}let l=lp(e,t,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),t.options)??l,d=LC.isNode(u)?u:new qC.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}tw.composeCollection=GC});var dp=R(iw=>{"use strict";var up=we();function JC(e,t,r){let i=t.offset,n=UC(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?up.Scalar.BLOCK_FOLDED:up.Scalar.BLOCK_LITERAL,o=t.source?KC(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let v=o[m][1];if(v===""||v==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let m=0;m<s;++m){let[v,g]=o[m];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=m,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 m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",p="",h=!1;for(let m=0;m<u;++m)d+=o[m][0].slice(c)+`
|
|
74
|
+
`;for(let m=u;m<s;++m){let[v,g]=o[m];l+=v.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&v.length<c){let y=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(w?2:1),"BAD_INDENT",y),v=""}a===up.Scalar.BLOCK_LITERAL?(d+=p+v.slice(c)+g,p=`
|
|
75
|
+
`):v.length>c||g[0]===" "?(p===" "?p=`
|
|
76
|
+
`:!h&&p===`
|
|
77
|
+
`&&(p=`
|
|
78
78
|
|
|
79
|
-
`),
|
|
80
|
-
`,
|
|
81
|
-
`?
|
|
82
|
-
`:
|
|
83
|
-
`:(
|
|
84
|
-
`+o[
|
|
85
|
-
`&&(
|
|
86
|
-
`);break;default:
|
|
87
|
-
`}let
|
|
79
|
+
`),d+=p+v.slice(c)+g,p=`
|
|
80
|
+
`,h=!0):g===""?p===`
|
|
81
|
+
`?d+=`
|
|
82
|
+
`:p=`
|
|
83
|
+
`:(d+=p+g,p=" ",h=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)d+=`
|
|
84
|
+
`+o[m][0].slice(c);d[d.length-1]!==`
|
|
85
|
+
`&&(d+=`
|
|
86
|
+
`);break;default:d+=`
|
|
87
|
+
`}let f=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,f,f]}}function UC({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 h=n[p];if(!s&&(h==="-"||h==="+"))s=h;else{let f=Number(h);!o&&f?o=f: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 h=t[p];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":r&&!l&&i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":i(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let f=`Unexpected token in block scalar header: ${h.type}`;i(h,"UNEXPECTED_TOKEN",f);let m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function KC(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}iw.resolveBlockScalar=JC});var hp=R(aw=>{"use strict";var pp=we(),YC=vn();function XC(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(p,h,f)=>r(i+p,h,f);switch(n){case"scalar":s=pp.Scalar.PLAIN,c=QC(a,l);break;case"single-quoted-scalar":s=pp.Scalar.QUOTE_SINGLE,c=ZC(a,l);break;case"double-quoted-scalar":s=pp.Scalar.QUOTE_DOUBLE,c=eP(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=YC.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function QC(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}`),nw(e)}function ZC(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),nw(e.slice(1,-1)).replace(/''/g,"'")}function nw(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"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===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function
|
|
91
|
+
`:(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 eP(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=tP(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=rP[a];if(o)r+=o;else if(a===`
|
|
94
94
|
`)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
|
|
95
|
-
`)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+=
|
|
95
|
+
`)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+=iP(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!==`
|
|
96
96
|
`&&!(o==="\r"&&e[i+2]===`
|
|
97
|
-
`)&&(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
|
|
97
|
+
`)&&(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 tP(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
|
|
98
98
|
`||i==="\r")&&!(i==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)i===`
|
|
100
100
|
`&&(r+=`
|
|
101
|
-
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var rP={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function iP(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}}aw.resolveFlowScalar=XC});var cw=R(sw=>{"use strict";var ki=U(),ow=we(),nP=dp(),aP=hp();function oP(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?nP.resolveBlockScalar(e,t,i):aP.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[ki.SCALAR]:c?l=sP(e.schema,n,c,r,i):t.type==="scalar"?l=cP(e,n,t,i):l=e.schema[ki.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??t,"TAG_RESOLVE_FAILED",p),e.options);u=ki.isScalar(d)?d:new ow.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",p),u=new ow.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 sP(e,t,r,i,n){if(r==="!")return e[ki.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[ki.SCALAR])}function cP({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[ki.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[ki.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}sw.composeScalar=oP});var uw=R(lw=>{"use strict";function lP(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}lw.emptyScalarPosition=lP});var hw=R(mp=>{"use strict";var uP=ka(),dP=U(),pP=rw(),dw=cw(),hP=vn(),fP=uw(),mP={composeNode:pw,composeEmptyNode:fp};function pw(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=vP(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=dw.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=pP.composeCollection(mP,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=fp(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&&(!dP.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 fp(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:fP.emptyScalarPosition(t,r,i),indent:-1,source:""},d=dw.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function vP({options:e},{offset:t,source:r,end:i},n){let a=new uP.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=hP.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}mp.composeEmptyNode=fp;mp.composeNode=pw});var vw=R(mw=>{"use strict";var gP=Ba(),fw=hw(),wP=vn(),yP=Ma();function bP(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new gP.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=yP.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?fw.composeNode(l,n,u,o):fw.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=wP.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}mw.composeDoc=bP});var gp=R(yw=>{"use strict";var NP=Os("process"),kP=rd(),SP=Ba(),Va=Fa(),gw=U(),EP=vw(),xP=vn();function Wa(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 ww(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?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(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
|
|
106
|
-
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(
|
|
105
|
+
`)+(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 vp=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Wa(r);a?this.warnings.push(new Va.YAMLWarning(o,i,n)):this.errors.push(new Va.YAMLParseError(o,i,n))},this.directives=new kP.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=ww(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(gw.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];gw.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
|
|
107
107
|
${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
|
|
108
|
-
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)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:
|
|
109
|
-
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)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:ww(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(NP.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Wa(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=EP.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 Va.YAMLParseError(Wa(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 Va.YAMLParseError(Wa(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=xP.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}
|
|
109
|
+
${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Va.YAMLParseError(Wa(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 SP.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}}};yw.Composer=vp});var kw=R(Rc=>{"use strict";var RP=dp(),CP=hp(),PP=Fa(),bw=Ca();function _P(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 PP.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return CP.resolveFlowScalar(e,t,i);case"block-scalar":return RP.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function AP(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=bw.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:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
|
-
`),u=s.substring(0,l),
|
|
112
|
-
`,
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:i,props:
|
|
111
|
+
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
+
`,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Nw(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function IP(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=bw.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">":TP(e,c);break;case'"':wp(e,c,"double-quoted-scalar");break;case"'":wp(e,c,"single-quoted-scalar");break;default:wp(e,c,"scalar")}}function TP(e,t){let r=t.indexOf(`
|
|
114
114
|
`),i=t.substring(0,r),n=t.substring(r+1)+`
|
|
115
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=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}];
|
|
116
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function
|
|
117
|
-
`};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})}}}
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=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}];Nw(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Nw(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 wp(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:`
|
|
117
|
+
`};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})}}}Rc.createScalarToken=AP;Rc.resolveAsScalar=_P;Rc.setScalarValue=IP});var Ew=R(Sw=>{"use strict";var $P=e=>"type"in e?Pc(e):Cc(e);function Pc(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Pc(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Cc(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Cc(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Cc(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 Cc({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Pc(t)),r)for(let a of r)n+=a.source;return i&&(n+=Pc(i)),n}Sw.stringify=$P});var Pw=R(Cw=>{"use strict";var yp=Symbol("break visit"),jP=Symbol("skip children"),xw=Symbol("remove item");function Si(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Rw(Object.freeze([]),e,t)}Si.BREAK=yp;Si.SKIP=jP;Si.REMOVE=xw;Si.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};Si.parentCollection=(e,t)=>{let r=Si.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 Rw(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=Rw(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===yp)return yp;s===xw&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Cw.visit=Si});var _c=R(Ve=>{"use strict";var bp=kw(),OP=Ew(),HP=Pw(),Np="\uFEFF",kp="",Sp="",Ep="",DP=e=>!!e&&"items"in e,BP=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function LP(e){switch(e){case Np:return"<BOM>";case kp:return"<DOC>";case Sp:return"<FLOW_END>";case Ep:return"<SCALAR>";default:return JSON.stringify(e)}}function qP(e){switch(e){case Np:return"byte-order-mark";case kp:return"doc-mode";case Sp:return"flow-error-end";case Ep:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
121
|
-
\r `),
|
|
119
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Ve.createScalarToken=bp.createScalarToken;Ve.resolveAsScalar=bp.resolveAsScalar;Ve.setScalarValue=bp.setScalarValue;Ve.stringify=OP.stringify;Ve.visit=HP.visit;Ve.BOM=Np;Ve.DOCUMENT=kp;Ve.FLOW_END=Sp;Ve.SCALAR=Ep;Ve.isCollection=DP;Ve.isScalar=BP;Ve.prettyToken=LP;Ve.tokenType=qP});var Cp=R(Aw=>{"use strict";var za=_c();function Ct(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var _w=new Set("0123456789ABCDEFabcdef"),FP=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ac=new Set(",[]{}"),MP=new Set(` ,[]{}
|
|
121
|
+
\r `),xp=e=>!e||MP.has(e),Rp=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===`
|
|
122
122
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!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===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
125
|
-
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&
|
|
126
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
125
|
+
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Ct(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===za.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 za.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==="...")&&Ct(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&&!Ct(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===":")&&Ct(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(xp),"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("..."))&&Ct(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield za.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(xp),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ct(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(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
128
|
-
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let 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=>
|
|
128
|
+
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let 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=>Ct(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`
|
|
129
129
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,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===`
|
|
132
132
|
`;)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===`
|
|
133
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield za.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(Ct(a)||t&&Ac.has(a))break;r=i}else if(Ct(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(i+=1,n=`
|
|
135
|
-
`,a=this.buffer[i+1]):r=i),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[i+1]):r=i),a==="#"||t&&Ac.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Ac.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield za.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(xp),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Ct(i)||r&&Ac.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(;!Ct(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(FP.has(r))r=this.buffer[++t];else if(r==="%"&&_w.has(this.buffer[t+1])&&_w.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,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)}};
|
|
138
|
+
`?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)}};Aw.Lexer=Rp});var _p=R(Iw=>{"use strict";var Pp=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}}}};Iw.LineCounter=Pp});var Ip=R(Hw=>{"use strict";var VP=Os("process"),Tw=_c(),WP=Cp();function Wr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function $w(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 Ow(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 Ic(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 gn(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 Tc(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 jw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Wr(t.start,"explicit-key-ind")&&!Wr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Ow(t.value)?t.value.end?Tc(t.value.end,t.sep):t.value.end=t.sep:Tc(t.start,t.sep),delete t.sep)}var Ap=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 WP.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,VP.env.LOG_TOKENS&&console.log("|",Tw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Tw.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"&&jw(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&&$w(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":{$w(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=Ic(this.peek(2)),i=gn(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(`
|
|
139
139
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
140
|
-
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let 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)){
|
|
140
|
+
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let 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)){Tc(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(Wr(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(Ow(r.key)&&!Wr(r.sep,"newline")){let o=gn(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(Wr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=gn(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]}):Wr(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&&!Wr(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)){Tc(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||Wr(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=Ic(i),a=gn(n);jw(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
|
-
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Us(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=Us(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())}}};Eg.Parser=Md});var _g=R(ba=>{"use strict";var xg=Ad(),ZC=fa(),Na=ma(),eR=Pu(),tR=G(),rR=Vd(),Cg=Wd();function Rg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new rR.LineCounter||null,prettyErrors:t}}function iR(e,t={}){let{lineCounter:r,prettyErrors:i}=Rg(t),n=new Cg.Parser(r?.addNewLine),a=new xg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Na.prettifyError(e,r)),s.warnings.forEach(Na.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Pg(e,t={}){let{lineCounter:r,prettyErrors:i}=Rg(t),n=new Cg.Parser(r?.addNewLine),a=new xg.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 Na.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Na.prettifyError(e,r)),o.warnings.forEach(Na.prettifyError(e,r))),o}function nR(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Pg(e,r);if(!n)return null;if(n.warnings.forEach(a=>eR.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 aR(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 tR.isDocument(e)&&!i?e.toString(r):new ZC.Document(e,i,r).toString(r)}ba.parse=nR;ba.parseAllDocuments=iR;ba.parseDocument=Pg;ba.stringify=aR});var rr=R(Y=>{"use strict";var oR=Ad(),sR=fa(),cR=ud(),zd=ma(),lR=Yn(),Ir=G(),uR=Cr(),dR=de(),fR=Pr(),pR=_r(),hR=Js(),mR=qd(),vR=Vd(),gR=Wd(),Ys=_g(),Ag=Jn();Y.Composer=oR.Composer;Y.Document=sR.Document;Y.Schema=cR.Schema;Y.YAMLError=zd.YAMLError;Y.YAMLParseError=zd.YAMLParseError;Y.YAMLWarning=zd.YAMLWarning;Y.Alias=lR.Alias;Y.isAlias=Ir.isAlias;Y.isCollection=Ir.isCollection;Y.isDocument=Ir.isDocument;Y.isMap=Ir.isMap;Y.isNode=Ir.isNode;Y.isPair=Ir.isPair;Y.isScalar=Ir.isScalar;Y.isSeq=Ir.isSeq;Y.Pair=uR.Pair;Y.Scalar=dR.Scalar;Y.YAMLMap=fR.YAMLMap;Y.YAMLSeq=pR.YAMLSeq;Y.CST=hR;Y.Lexer=mR.Lexer;Y.LineCounter=vR.LineCounter;Y.Parser=gR.Parser;Y.parse=Ys.parse;Y.parseAllDocuments=Ys.parseAllDocuments;Y.parseDocument=Ys.parseDocument;Y.stringify=Ys.stringify;Y.visit=Ag.visit;Y.visitAsync=Ag.visitAsync});function jg(){NR+=1}var NR,$g=A(()=>{"use strict";NR=0});import{execFileSync as bR}from"node:child_process";function Og(e,t){jg();try{return bR("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:kR,maxBuffer:SR,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Jd(e,t,i)}}function I(e,t){return Og(e,t).trim()}function Zs(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Gd(e,t){I(e,["check-ref-format","--branch",t])}function ka(e){let t=Og(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var kR,SR,Jd,rt=A(()=>{"use strict";$g();kR=3e4,SR=8*1024*1024,Jd=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function CR(e){return e.toLowerCase().startsWith(".env")}function Xi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>CR(i))?"environment-file":r.some(i=>xR.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>ER.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var ER,xR,Sa=A(()=>{"use strict";ER=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),xR=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Tr(e){return e!==0&&e!==0n&&e!=="0"}function wt(e,t){return Tr(e.dev)&&Tr(t.dev)&&Tr(e.ino)&&Tr(t.ino)}function Z(e,t){let r=Tr(e.dev)&&Tr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Tr(e.ino)&&Tr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Ea=A(()=>{"use strict"});var Dt=A(()=>{"use strict";Ea()});import{createHash as RR}from"node:crypto";import{promises as yt}from"node:fs";import it from"node:path";import{TextDecoder as PR}from"node:util";function Ud(e,t){let r=it.relative(e,t);return r===""||!it.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${it.sep}`)}function _R(e){let t=it.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})||it.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=Xi(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 AR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function IR(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ec(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wt(r,i)?Z(r,i):Z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Hg(e){let t=await yt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await yt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function TR(e,t){let r=it.resolve(e),i=it.resolve(t);if(!Ud(r,i))throw new Error("Native artifact path is outside its root");let n=[await Hg(r)],a=r;for(let o of it.relative(r,i).split(it.sep).filter(Boolean)){a=it.join(a,o);let s=await Hg(a);if(!Ud(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Dg(e){for(let t of e){let r=await yt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!IR(t,r)||await yt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Q(e){let t=_R(e.ref),r=e.maxBytes===null?null:AR(e.maxBytes??Kd),i=it.resolve(e.root,...t.split("/")),n=await TR(e.root,it.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await yt.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 yt.realpath(i);if(!Ud(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await yt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),yt.lstat(i),yt.realpath(i)]);if(await Dg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!ec(a,c)||!ec(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?p.length:r+1-d,b=await s.read(p,0,Math.min(p.length,y),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([s.stat(),yt.lstat(i),yt.realpath(i)]);if(await Dg(n),!h.isFile()||h.isSymbolicLink()||g!==o||!ec(c,m)||!ec(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(f,d),w;try{w=new PR("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:RR("sha256").update(v).digest("hex"),text:w}}finally{await s.close()}}var Kd,nt=A(()=>{"use strict";Sa();Dt();Kd=1024*1024});import{createHash as jR}from"crypto";function Nt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function $R(e,t){t.has(e)&&Nt("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)||Nt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Nt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Nt("symbol properties are not supported"),`[${e.map(i=>Yd(i,t)).join(",")}]`}finally{t.delete(e)}}function OR(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Nt("only plain objects are supported"),t.has(e)&&Nt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Nt("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))&&Nt("accessor properties are not supported"),`${JSON.stringify(o)}:${Yd(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Yd(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)||Nt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?$R(e,t):OR(e,t);case"bigint":case"function":case"symbol":case"undefined":return Nt(`${typeof e} values are not supported`)}return Nt("unsupported value type")}function tc(e){return Yd(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 jR("sha256").update(`${e}
|
|
143
|
-
${
|
|
144
|
-
`)){let s=
|
|
142
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Ic(t),i=gn(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=Ic(t),i=gn(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())}}};Hw.Parser=Ap});var Fw=R(Ja=>{"use strict";var Dw=gp(),zP=Ba(),Ga=Fa(),GP=md(),JP=U(),UP=_p(),Bw=Ip();function Lw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new UP.LineCounter||null,prettyErrors:t}}function KP(e,t={}){let{lineCounter:r,prettyErrors:i}=Lw(t),n=new Bw.Parser(r?.addNewLine),a=new Dw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ga.prettifyError(e,r)),s.warnings.forEach(Ga.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function qw(e,t={}){let{lineCounter:r,prettyErrors:i}=Lw(t),n=new Bw.Parser(r?.addNewLine),a=new Dw.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 Ga.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ga.prettifyError(e,r)),o.warnings.forEach(Ga.prettifyError(e,r))),o}function YP(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=qw(e,r);if(!n)return null;if(n.warnings.forEach(a=>GP.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 XP(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 JP.isDocument(e)&&!i?e.toString(r):new zP.Document(e,i,r).toString(r)}Ja.parse=YP;Ja.parseAllDocuments=KP;Ja.parseDocument=qw;Ja.stringify=XP});var Gt=R(Q=>{"use strict";var QP=gp(),ZP=Ba(),e_=Xd(),Tp=Fa(),t_=ka(),zr=U(),r_=qr(),i_=we(),n_=Mr(),a_=Vr(),o_=_c(),s_=Cp(),c_=_p(),l_=Ip(),$c=Fw(),Mw=wa();Q.Composer=QP.Composer;Q.Document=ZP.Document;Q.Schema=e_.Schema;Q.YAMLError=Tp.YAMLError;Q.YAMLParseError=Tp.YAMLParseError;Q.YAMLWarning=Tp.YAMLWarning;Q.Alias=t_.Alias;Q.isAlias=zr.isAlias;Q.isCollection=zr.isCollection;Q.isDocument=zr.isDocument;Q.isMap=zr.isMap;Q.isNode=zr.isNode;Q.isPair=zr.isPair;Q.isScalar=zr.isScalar;Q.isSeq=zr.isSeq;Q.Pair=r_.Pair;Q.Scalar=i_.Scalar;Q.YAMLMap=n_.YAMLMap;Q.YAMLSeq=a_.YAMLSeq;Q.CST=o_;Q.Lexer=s_.Lexer;Q.LineCounter=c_.LineCounter;Q.Parser=l_.Parser;Q.parse=$c.parse;Q.parseAllDocuments=$c.parseAllDocuments;Q.parseDocument=$c.parseDocument;Q.stringify=$c.stringify;Q.visit=Mw.visit;Q.visitAsync=Mw.visitAsync});import{AsyncLocalStorage as u_}from"node:async_hooks";import{performance as jc}from"node:perf_hooks";function $p(e=0){d_+=1,p_+=e;let t=h_.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function Ua(e){let t=jc.now();try{return e()}finally{$p(jc.now()-t)}}async function jp(e){let t=jc.now();try{return await e()}finally{$p(jc.now()-t)}}var d_,p_,h_,wn=T(()=>{"use strict";d_=0,p_=0,h_=new u_});import{spawn as Op}from"node:child_process";import{existsSync as Vw}from"node:fs";import Ei from"node:path";function Hp(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function w_(e){let t=(Hp(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function y_(e,t,r){let n=Ei.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Hp(t,"PATH")??"").split(Ei.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ei.win32.extname(e)?[e]:w_(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Ei.join(s,c):Ei.resolve(r,c)))}function xi(e,t,r){return y_(e,t,r).find(i=>Vw(i))??e}function b_(e){let t=Hp(e,"SystemRoot");if(t){let r=Ei.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Vw(r))return r}return"powershell.exe"}function Ka(e){if(e.some(t=>v_.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function N_(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(g_,"utf16le").toString("base64");return Op(b_(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Dp(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Op(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=xi(e,i,r.cwd),a=Ei.win32.extname(n).toLowerCase();return m_.has(a)&&Ka(t),f_.has(a)?N_(n,t,{cwd:r.cwd,env:i}):Op(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var f_,m_,v_,g_,Ya=T(()=>{"use strict";f_=new Set([".bat",".cmd",".ps1"]),m_=new Set([".bat",".cmd"]),v_=/[&|<>()^%"!\r\n]/u,g_=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFile as k_,execFileSync as XL}from"node:child_process";import Ww from"node:path";async function Gr(e,t,r={}){let i=r.timeoutMs??S_,n=r.maxBufferBytes??E_;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Ww.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?xi(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&Ka(t);let l=()=>new Promise((u,d)=>{let p=!1,h=k_(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(g,w,N)=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",m),g?d(new Xa(e,t,N.trim(),{cause:g,timedOut:x_(g)})):u(w))}),f=g=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",m),h.kill("SIGKILL"),h.stdin?.destroy(),h.stdout?.destroy(),h.stderr?.destroy(),h.unref(),d(new Xa(e,t,"",{timedOut:g})))},m=()=>f(!1),v=setTimeout(()=>f(!0),i);r.signal?.addEventListener("abort",m,{once:!0}),r.signal?.aborted&&m(),h.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Ww.win32.basename(e))?jp(l):l()}function x_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var S_,E_,Xa,yn=T(()=>{"use strict";wn();Ya();S_=6e4,E_=8*1024*1024;Xa=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{execFileSync as A_}from"node:child_process";function Xw(e,t){try{return Ua(()=>A_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:I_,maxBuffer:T_,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Bp(e,t,i)}}function I(e,t){return Xw(e,t).trim()}function Hc(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Lp(e,t){I(e,["check-ref-format","--branch",t])}function Qa(e){let t=Xw(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var I_,T_,Bp,We=T(()=>{"use strict";wn();I_=3e4,T_=8*1024*1024,Bp=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function O_(e){return e.toLowerCase().startsWith(".env")}function Nn(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>O_(i))?"environment-file":r.some(i=>j_.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>$_.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var $_,j_,Za=T(()=>{"use strict";$_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),j_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Yr(e){return e!==0&&e!==0n&&e!=="0"}function Pt(e,t){return Yr(e.dev)&&Yr(t.dev)&&Yr(e.ino)&&Yr(t.ino)}function te(e,t){let r=Yr(e.dev)&&Yr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Yr(e.ino)&&Yr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var eo=T(()=>{"use strict"});var Jt=T(()=>{"use strict";eo()});import{createHash as H_}from"node:crypto";import{promises as _t}from"node:fs";import ft from"node:path";import{TextDecoder as D_}from"node:util";function qp(e,t){let r=ft.relative(e,t);return r===""||!ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ft.sep}`)}function B_(e){let t=ft.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})||ft.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=Nn(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 L_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function q_(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Dc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Pt(r,i)?te(r,i):te(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Qw(e){let t=await _t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await _t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function F_(e,t){let r=ft.resolve(e),i=ft.resolve(t);if(!qp(r,i))throw new Error("Native artifact path is outside its root");let n=[await Qw(r)],a=r;for(let o of ft.relative(r,i).split(ft.sep).filter(Boolean)){a=ft.join(a,o);let s=await Qw(a);if(!qp(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Zw(e){for(let t of e){let r=await _t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!q_(t,r)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=B_(e.ref),r=e.maxBytes===null?null:L_(e.maxBytes??Fp),i=ft.resolve(e.root,...t.split("/")),n=await F_(e.root,ft.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await _t.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 _t.realpath(i);if(!qp(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await _t.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),_t.lstat(i),_t.realpath(i)]);if(await Zw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Dc(a,c)||!Dc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],p=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?h.length:r+1-p,y=await s.read(h,0,Math.min(h.length,N),null);if(y.bytesRead===0)break;if(p+=y.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,y.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[f,m,v]=await Promise.all([s.stat(),_t.lstat(i),_t.realpath(i)]);if(await Zw(n),!m.isFile()||m.isSymbolicLink()||v!==o||!Dc(c,f)||!Dc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),w;try{w=new D_("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:p,hash:e.includeHash===!1?null:H_("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var Fp,rt=T(()=>{"use strict";Za();Jt();Fp=1024*1024});import{createHash as M_}from"crypto";function At(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function V_(e,t){t.has(e)&&At("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)||At("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&At("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&At("symbol properties are not supported"),`[${e.map(i=>Mp(i,t)).join(",")}]`}finally{t.delete(e)}}function W_(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&At("only plain objects are supported"),t.has(e)&&At("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&At("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))&&At("accessor properties are not supported"),`${JSON.stringify(o)}:${Mp(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Mp(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)||At("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?V_(e,t):W_(e,t);case"bigint":case"function":case"symbol":case"undefined":return At(`${typeof e} values are not supported`)}return At("unsupported value type")}function Bc(e){return Mp(e,new Set)}function $(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 M_("sha256").update(`${e}
|
|
143
|
+
${Bc(t)}`).digest("hex")}var pe=T(()=>{"use strict"});import Xr from"path";function ay(e,t){return kn[t][e]}function K_(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in kn.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in kn.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in kn.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in kn.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in kn.en)return s}return null}function ao(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,io.stringify)(e).trimEnd().split(`
|
|
144
|
+
`)){let s=K_(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of ay(s,t).split(`
|
|
145
145
|
`))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
|
|
146
|
-
`)}function FR(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||jr.posix.isAbsolute(r)||jr.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 li(e){let t=FR(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Wg(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 ac(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||jr.posix.isAbsolute(i)||jr.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 or(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function zg(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 oc(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>rc)throw new Error(`${t} exceeds ${rc} 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>ic)throw new Error(`${t} contains more than ${ic} wildcard tokens`);return e}function Fg(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=>oc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function xa(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 Vg(e,t,r){let i=xa(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 VR(e){if(e===void 0)return{...Le,include:[...Le.include],exclude:[...Le.exclude]};let t=or(e,"native.snapshot");return{include:Fg(t.include,"native.snapshot.include",Le.include),exclude:Fg(t.exclude,"native.snapshot.exclude",Le.exclude),max_files:xa(t.max_files,Le.max_files,"native.snapshot.max_files"),max_total_bytes:xa(t.max_total_bytes,Le.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:xa(t.max_duration_ms,Le.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:xa(t.max_selection_records,Le.max_selection_records,"native.snapshot.max_selection_records")}}function MR(e){if(e===void 0)return;let t=or(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=or(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:li(i),toArtifactRoot:li(n),stage:a,...o?{cleanup:o}:{}}}function WR(e){if(e===void 0)return;let t=or(e,"native.finish");if(t.pull_request===void 0)return{};let r=or(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(jr.posix.isAbsolute(i[0])||jr.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??HR;if(!Number.isSafeInteger(n)||n<1||n>qg)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${qg}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function zR(e,t={}){let r=or(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??Xd;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=MR(r.pending_root_move),l=WR(r.finish);return{artifact_root:li(i),language:zg(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:VR(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function JR(e){let t=or(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:Wg(t.artifact_layout),language:zg(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function GR(e){let r=or(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)=>ac(i,`hook.allow_paths[${n}]`)))]}}function UR(e){if(e===void 0)return{...Ca};let t=or(e,"memory"),r=t.learning??Ca.learning,i=t.retrieval??Ca.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 Zd(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function KR(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")||jr.posix.isAbsolute(r)||jr.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>Bg)throw new Error(`${t} exceeds ${Bg} 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>Lg)throw new Error(`${t} contains more than ${Lg} wildcard tokens`);return r}function YR(e){let t=Zd(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)=>KR(n,`knowledge.local.include[${a}]`)))],max_file_mb:Vg(t.max_file_mb,nc.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Vg(t.max_total_mb,nc.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 XR(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 QR(e){let t=Zd(e,"knowledge.remote"),r=XR(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 ZR(e){if(e===void 0)return{...Qd};let t=Zd(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:YR(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:QR(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 eP(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function tP(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(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let f=[...new Set(u)];if(!f.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(f.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:f,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Zi(e,t={}){let r=(0,Ra.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=eP(n.ambient_resume),o=n.hook===void 0?void 0:GR(n.hook),s=UR(n.memory),c=ZR(n.knowledge),l=n.native===void 0?void 0:zR(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:JR(n.classic),f=tP(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:f,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Jg(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Gg(e){let t=e.knowledge??{...Qd};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Ca},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??nc.max_file_mb,max_total_mb:t.local.max_total_mb??nc.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Jg(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function Ge(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Aa(e,t){let r=Gg(t),i=Zi((0,Ra.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...Ge(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=Ge(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=Ge(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...Ge(a.local),include:[...i.knowledge.local.include],max_file_mb:i.knowledge.local.max_file_mb,max_total_mb:i.knowledge.local.max_total_mb}:delete o.local,i.knowledge.remote){let c={...Ge(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=Ge(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures,...i.native.document_writes?{document_writes:i.native.document_writes}:{}};if(i.native.finish?.pull_request){let s=Ge(a.finish);o.finish={...s,pull_request:{...Ge(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...Ge(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=Ge(a.pending_root_move),c=Jg(i.native.pending_root_move),l=Ge(s.cleanup),u=Ge(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...Ge(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition,...i.classic.document_evidence?{document_evidence:i.classic.document_evidence}:{}}),n}function sc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Ca},knowledge:{...Qd},native:{artifact_root:li(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Xd,snapshot:{...Le,include:[...Le.include],exclude:[...Le.exclude]}}}}var Ra,Pa,rc,ic,Bg,Lg,Xd,Ca,nc,Qd,HR,qg,DR,BR,LR,Le,Qi,$r=A(()=>{"use strict";Ra=br(rr(),1),Pa=Number.MAX_SAFE_INTEGER,rc=1024,ic=64,Bg=1024,Lg=64,Xd=5,Ca={learning:!0,retrieval:!0},nc={include:[],max_file_mb:1,max_total_mb:32},Qd={provider:"local"},HR=12e4,qg=6e5,DR=[".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/**"],BR=["**/.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"],LR=[...DR,...BR].sort((e,t)=>e.localeCompare(t,"en")),Le={include:["**/*"],exclude:[...LR],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},Qi={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
146
|
+
`)}function Y_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Xr.posix.isAbsolute(r)||Xr.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 Pi(e){let t=Y_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function oy(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Mc(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Xr.posix.isAbsolute(i)||Xr.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 yr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function sy(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Vc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Lc)throw new Error(`${t} exceeds ${Lc} 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>qc)throw new Error(`${t} contains more than ${qc} wildcard tokens`);return e}function iy(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Vc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function to(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 ny(e,t,r){let i=to(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 X_(e){if(e===void 0)return{...ze,include:[...ze.include],exclude:[...ze.exclude]};let t=yr(e,"native.snapshot");return{include:iy(t.include,"native.snapshot.include",ze.include),exclude:iy(t.exclude,"native.snapshot.exclude",ze.exclude),max_files:to(t.max_files,ze.max_files,"native.snapshot.max_files"),max_total_bytes:to(t.max_total_bytes,ze.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:to(t.max_duration_ms,ze.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:to(t.max_selection_records,ze.max_selection_records,"native.snapshot.max_selection_records")}}function Q_(e){if(e===void 0)return;let t=yr(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=yr(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:Pi(i),toArtifactRoot:Pi(n),stage:a,...o?{cleanup:o}:{}}}function Z_(e){if(e===void 0)return;let t=yr(e,"native.finish");if(t.pull_request===void 0)return{};let r=yr(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(Xr.posix.isAbsolute(i[0])||Xr.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??z_;if(!Number.isSafeInteger(n)||n<1||n>ry)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${ry}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function eA(e,t={}){let r=yr(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??Vp;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=Q_(r.pending_root_move),l=Z_(r.finish);return{artifact_root:Pi(i),language:sy(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:X_(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function tA(e){let t=yr(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:oy(t.artifact_layout),language:sy(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function rA(e){let r=yr(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Mc(i,`hook.allow_paths[${n}]`)))]}}function iA(e){if(e===void 0)return{...ro};let t=yr(e,"memory"),r=t.learning??ro.learning,i=t.retrieval??ro.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 zp(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function nA(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")||Xr.posix.isAbsolute(r)||Xr.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>ey)throw new Error(`${t} exceeds ${ey} 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>ty)throw new Error(`${t} contains more than ${ty} wildcard tokens`);return r}function aA(e){let t=zp(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)=>nA(n,`knowledge.local.include[${a}]`)))],max_file_mb:ny(t.max_file_mb,Fc.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:ny(t.max_total_mb,Fc.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 oA(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 sA(e){let t=zp(e,"knowledge.remote"),r=oA(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 cA(e){if(e===void 0)return{...Wp};let t=zp(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:aA(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:sA(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 lA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function uA(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 Sn(e,t={}){let r=(0,io.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=lA(n.ambient_resume),o=n.hook===void 0?void 0:rA(n.hook),s=iA(n.memory),c=cA(n.knowledge),l=n.native===void 0?void 0:eA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:tA(n.classic),d=uA(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function cy(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function ly(e){let t=e.knowledge??{...Wp};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...ro},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??Fc.max_file_mb,max_total_mb:t.local.max_total_mb??Fc.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:cy(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function it(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function oo(e,t){let r=ly(t),i=Sn((0,io.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...it(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=it(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=it(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...it(a.local),include:[...i.knowledge.local.include],max_file_mb:i.knowledge.local.max_file_mb,max_total_mb:i.knowledge.local.max_total_mb}:delete o.local,i.knowledge.remote){let c={...it(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=it(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures,...i.native.document_writes?{document_writes:i.native.document_writes}:{}};if(i.native.finish?.pull_request){let s=it(a.finish);o.finish={...s,pull_request:{...it(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...it(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=it(a.pending_root_move),c=cy(i.native.pending_root_move),l=it(s.cleanup),u=it(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...it(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition,...i.classic.document_evidence?{document_evidence:i.classic.document_evidence}:{}}),n}function Wc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ro},knowledge:{...Wp},native:{artifact_root:Pi(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Vp,snapshot:{...ze,include:[...ze.include],exclude:[...ze.exclude]}}}}var io,no,Lc,qc,ey,ty,Vp,ro,Fc,Wp,z_,ry,G_,J_,U_,ze,kn,Qr=T(()=>{"use strict";io=fr(Gt(),1),no=Number.MAX_SAFE_INTEGER,Lc=1024,qc=64,ey=1024,ty=64,Vp=5,ro={learning:!0,retrieval:!0},Fc={include:[],max_file_mb:1,max_total_mb:32},Wp={provider:"local"},z_=12e4,ry=6e5,G_=[".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/**"],J_=["**/.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"],U_=[...G_,...J_].sort((e,t)=>e.localeCompare(t,"en")),ze={include:["**/*"],exclude:[...U_],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},kn={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
147
147
|
# ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
|
|
148
148
|
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
149
149
|
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
@@ -171,61 +171,138 @@ ${tc(t)}`).digest("hex")}var fe=A(()=>{"use strict"});import jr from"path";funct
|
|
|
171
171
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
172
172
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
173
173
|
# 可选值:true | false`,"classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
|
|
174
|
-
# 可选值:neutral | strict`}}});import{constants as
|
|
175
|
-
`,r)}var ne=A(()=>{"use strict";df();Dt()});import{existsSync as ew,promises as di}from"fs";import U from"path";import vP from"os";async function mf(e){try{return await di.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wP(e){try{let t=await di.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function sn(e,t){let r=U.relative(e,t);return r===""||!U.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${U.sep}`)}async function on(e){let t=[],r=e;for(;!await mf(r);){let n=U.dirname(r);if(n===r)break;t.push(U.basename(r)),r=n}let i=await di.realpath(r);return U.resolve(i,...t.reverse())}async function vf(e){try{return(await di.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mc(e){let t=U.resolve(e);try{(await di.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=U.resolve(vP.homedir());for(;;){if(!(t===i&&r!==i)){let o=U.join(t,...Ha.split("/")),s=t===r||await wP(o);if(await mf(o)&&s)return t}if(await mf(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return r;t=a}}function vc(e){return li(e)}async function yP(e,t){let r=vc(t),i=U.resolve(e,...r.split("/")),n=await di.realpath(e),a=await on(i);if(!sn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Dr(e,t){let r=vc(t),i=await yP(e,r),n=U.join(i,"comet");if(await vf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([on(i),on(n)]);if(!sn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await vf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([di.realpath(s),on(c)]);if(!sn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...Ha.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function tw(e){if(!gP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function pe(e,t){tw(t);let r=U.join(e.changesRuntimeDir,t);if(!be(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function gf(e,t){tw(t);let r=U.join(e.changesDir,t,"runtime");if(!be(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function ot(e,t){let r=pe(e,t);if(ew(r))return r;let i=gf(e,t);return ew(i)?i:r}function wf(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=U.resolve(e,...t.slice(8).split("/"));if(!be(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function qe(e,t){let r=U.resolve(t);if(be(e.runtimeDir,r))return e.runtimeDir;if(be(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function be(e,t){return sn(U.resolve(e),U.resolve(t))}async function z(e,t){let r=U.resolve(e),i=U.resolve(t);if(!sn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await vf(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([on(r),on(i)]);if(!sn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Ha,gP,te=A(()=>{"use strict";$r();Ha=".comet/config.yaml",gP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import NP from"path";function bP(e="docs",t="en"){return sc(e,t)}async function _e(e){let t=(await dc(e))?.config??null;return t?.native?t:null}async function wc(e){let t=await _e(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function yc(e,t,r={}){let i=await $a(e,{allowPartialProject:!0}),n=Aa(i.document?.value??{},t),a=NP.join(e,...Ha.split("/"));await at(a,_a(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await pf(e,i.identity)}})}async function rw(e){let t=await mc(e.startPath),r=await _e(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Ha} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?vc(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??bP(i??"docs"),a=await Dr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var gc,st=A(()=>{"use strict";$r();rn();hf();ne();te();gc=oc});function bc(){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 fi,Da,Nc,cn=A(()=>{"use strict";fi="comet.native.v4",Da="comet.native.local-execution.v4",Nc=["multi-session","single-session"]});var kf={};du(kf,{NativePortableStateVersionConflictError:()=>Ba,appendNativePortableHistory:()=>ye,compareAndSwapNativePortableState:()=>dn,createNativePortableState:()=>nw,parseNativePortableState:()=>B,readNativePortableState:()=>lt,writeNativePortableState:()=>La});import{promises as kP}from"node:fs";function Ae(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ie(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 ke(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 Nf(e,t){return e===null?null:ke(e,t)}function bf(e,t){let r=ke(e,t);if(!CP.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ln(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ae(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 PP(e,t){return e===null?null:ae(e,t,Number.MIN_SAFE_INTEGER)}function he(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Bt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function xc(e,t){return Bt(e,t,(r,i)=>ke(r,`${t}[${i}]`))}function pi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function un(e,t){let r=ke(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Sc(e,t,r=!1){let i=ke(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ct(e,t){let r=Ae(e,t);return Ie(r,new Set(["text","truncated"]),t),{text:ke(r.text,`${t}.text`,{empty:!0}),truncated:ln(r.truncated,`${t}.truncated`)}}function _P(e,t){let r=`Native spec_changes[${t}]`,i=Ae(e,r);Ie(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ke(i.capability,`${r}.capability`);if(!EP.test(n))throw new Error(`${r}.capability is invalid`);let a=he(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Sc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Sc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:bf(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 AP(e){let t="Native workspace",r=Ae(e,t);Ie(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=he(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Nf(r.change_branch,`${t}.change_branch`),a=Nf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:he(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function IP(e){let t="Native loop",r=Ae(e,t);Ie(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=xc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);pi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:he(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:he(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ae(r.goal_cycle,`${t}.goal_cycle`,1),iteration:ae(r.iteration,`${t}.iteration`),attempt:ae(r.attempt,`${t}.attempt`),retry_epoch:ae(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ae(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ae(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ae(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Nf(r.next_action,`${t}.next_action`)}}function TP(e,t){let r=`Native acceptance[${t}]`,i=Ae(e,r);Ie(i,new Set(["id","source","text","result","reason"]),r);let n=ke(i.id,`${r}.id`);if(!xP.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Sc(i.source,`${r}.source`),text:ke(i.text,`${r}.text`),result:he(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ct(i.reason,`${r}.reason`)}}function jP(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Ae(e,r);return Ie(i,new Set(["name","result","note"]),r),{name:ct(i.name,`${r}.name`),result:he(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ct(i.note,`${r}.note`)}}function $P(e){let t="Native builder_handoff",r=Ae(e,t);Ie(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=xc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);pi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Ae(r.review,`${t}.review`);return n&&Ie(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ke(r.candidate_id,`${t}.candidate_id`),identity_provider:ke(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ke(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ae(r.iteration,`${t}.iteration`,1),summary:ct(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Bt(r.checks,`${t}.checks`,jP),checks_truncated:ln(r.checks_truncated,`${t}.checks_truncated`),known_limits:Bt(r.known_limits,`${t}.known_limits`,(a,o)=>ct(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ln(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:he(n.status,["passed"],`${t}.review.status`),summary:ct(n.summary,`${t}.review.summary`),reviewer_execution_ref:ke(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:un(r.submitted_at,`${t}.submitted_at`)}}function OP(e,t){let r=`Native blockers[${t}]`,i=Ae(e,r);Ie(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=xc(i.acceptance_ids,`${r}.acceptance_ids`);return pi(n,`${r}.acceptance_ids`),{owner:he(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ct(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:he(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function HP(e,t){let r=`Native verification.checks[${t}]`,i=Ae(e,r);return Ie(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ke(i.id,`${r}.id`),name:ct(i.name,`${r}.name`),argv_display:Bt(i.argv_display,`${r}.argv_display`,(n,a)=>ct(n,`${r}.argv_display[${a}]`)),argv_truncated:ln(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Sc(i.cwd_ref,`${r}.cwd_ref`,!0),status:he(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:PP(i.exit_code,`${r}.exit_code`),duration_ms:ae(i.duration_ms,`${r}.duration_ms`)}}function DP(e){let t="Native verification",r=Ae(e,t);Ie(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Bt(r.checks,`${t}.checks`,HP);pi(i.map(a=>a.id),`${t}.checks IDs`);let n=ke(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ke(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ke(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ae(r.iteration,`${t}.iteration`,1),attempt:ae(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":he(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:he(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ct(r.summary,`${t}.summary`),risks:Bt(r.risks,`${t}.risks`,(a,o)=>ct(a,`${t}.risks[${o}]`)),risks_truncated:ln(r.risks_truncated,`${t}.risks_truncated`),completed_at:un(r.completed_at,`${t}.completed_at`)}}function iw(e,t){let r=`Native history[${t}]`,i=Ae(e,r);Ie(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=xc(i.unresolved_ids,`${r}.unresolved_ids`);return pi(n,`${r}.unresolved_ids`),{goal_cycle:ae(i.goal_cycle,`${r}.goal_cycle`,1),iteration:ae(i.iteration,`${r}.iteration`),attempt:ae(i.attempt,`${r}.attempt`),outcome:he(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ct(i.summary,`${r}.summary`),completed_at:un(i.completed_at,`${r}.completed_at`)}}function BP(e){let t="Native history_overflow.outcome_counts",r=Ae(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Ie(r,new Set(i),t),{pass:ae(r.pass,`${t}.pass`),fail:ae(r.fail,`${t}.fail`),blocked:ae(r.blocked,`${t}.blocked`),"execution-error":ae(r["execution-error"],`${t}.execution-error`),recovery:ae(r.recovery,`${t}.recovery`)}}function LP(e){let t="Native history_overflow",r=Ae(e,t);Ie(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=ae(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:un(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:un(r.last_dropped_at,`${t}.last_dropped_at`);if(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=BP(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 qP(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 FP(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 B(e){let t=Ae(e,"Native portable state");if(Ie(t,RP,"Native portable state"),t.schema!==fi)throw new Error(`Native portable state schema must be ${fi}`);let r=ke(t.name,"Native state name");if(!SP.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=Bt(t.spec_changes,"Native spec_changes",_P);pi(i.map(s=>s.capability),"Native spec change capabilities");let n=Bt(t.acceptance,"Native acceptance",TP);pi(n.map(s=>s.id),"Native acceptance IDs");let a=Bt(t.history,"Native history",iw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:fi,name:r,language:he(t.language,["en","zh-CN"],"Native state language"),phase:he(t.phase,["shape","build","verify","archive"],"Native state phase"),status:he(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ae(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:bf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:bf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:he(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:AP(t.workspace),loop:IP(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:$P(t.builder_handoff),blockers:Bt(t.blockers,"Native blockers",OP),verification:t.verification===null?null:DP(t.verification),history:a,history_overflow:LP(t.history_overflow),verification_result:he(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:he(t.verification_report,["verification.md"],"Native verification_report"),archived:ln(t.archived,"Native archived"),created_at:un(t.created_at,"Native created_at")};return qP(o),FP(o),o}function nw(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return B({schema:fi,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:bc(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ye(e,t){let r=B(e),i=iw(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 B({...r,history:n,history_overflow:a})}function VP(e,t){let r=(0,Ec.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 lt(e){let t=await kP.readFile(e,"utf8");return B(VP(t,"Native portable state"))}async function La(e,t,r={}){let i=B(t);await at(e,(0,Ec.stringify)(i),r)}async function MP(e,t){let r=kc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);kc.set(e,a),await r;try{return await t()}finally{i(),kc.get(e)===a&&kc.delete(e)}}async function dn(e){return MP(e.file,async()=>{let t=ae(e.expectedStateVersion,"Native expected state version",1),r=B(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await lt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ba(t,i.state_version);return await La(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await lt(e.file);if(n.state_version!==t)throw new Ba(t,n.state_version)}}),r})}var Ec,SP,EP,xP,CP,RP,Ba,kc,ut=A(()=>{"use strict";Ec=br(rr(),1);ne();cn();SP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xP=/^A[1-9][0-9]*$/u,CP=/^[a-f0-9]{64}$/u,RP=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"]),Ba=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"};kc=new Map});import{promises as WP}from"node:fs";import zP from"node:path";function Rc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Cc(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 ow(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 XP(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 sw(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 dw(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ef&&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),f=e.acceptance_index[l];u&&f&&(f.source!==u.source||f.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=>!cw(e.children,l)),lw(i)?i:null}if(e.schema===hi&&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=>!cw(e.children,a)),lw(i)?i:null}return null}function cw(e,t){return e.some(r=>r.covers.includes(t))}function lw(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function dt(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 QP(e){let t=Rc(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=Rc(n,`Native children acceptance_index.${i}`);if(Cc(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 ZP(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 f=e[l];if(f.source!==u.source||f.text!==u.text){let d=["source","text"].filter(p=>f[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function fw(e,t,r={}){let i=(0,uw.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Rc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==hi&&a!==Br)throw Cc(n,aw,"Native children contract"),new Error(`Native children schema must be ${hi} or ${Br}`);let o=a===hi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Cc(n,o==="indexed-v2"?GP:aw,"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((d,p)=>{let m=Rc(d,`Native child ${p}`);if(Cc(m,o==="indexed-v2"?YP:o==="summary-v2"?KP:UP,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!JP.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:ow(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?ow(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let p=d.depends_on.filter(m=>!u.has(m));if(p.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${p.join(", ")}`)}XP(c);let f=r.policy==="advisory";if(a===Ef){if(o==="indexed-v2"){let d=QP(n.acceptance_index);f||ZP(d,t,r);let p=Object.keys(d);return f||sw(c,p,p),{schema:Br,acceptance_index:d,children:c}}return{schema:Br,children:c}}return t&&!f&&sw(c,t),{schema:hi,children:c}}async function Fe(e){let t=zP.join(e.changeDir,Sf);try{await WP.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Q({root:e.changeDir,ref:Sf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=fw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?dw(a,e.acceptanceIds,e.validation??{}):null}}var uw,Sf,hi,Br,Ef,JP,aw,GP,UP,KP,YP,Pc=A(()=>{"use strict";uw=br(rr(),1);nt();Sf="children.yaml",hi="comet.native.children.v1",Br="comet.native.children.v2",Ef=Br,JP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aw=new Set(["schema","children"]),GP=new Set(["schema","acceptance_index","children"]),UP=new Set(["name","depends_on","covers"]),KP=new Set(["name","summary","depends_on"]),YP=new Set(["name","depends_on","covers"])});function ee(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 qa({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var qa,_c=A(()=>{"use strict";qa=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 xf(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Cf(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){xf(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Ne,executionRef:xf(t.executionRef,"Native execution ref"),[pw]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:xf(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[hw]:!0})}})}function Ac(e){return typeof e=="object"&&e!==null&&e[hw]===!0}function mw(e){return typeof e=="object"&&e!==null&&e[pw]===!0}var pw,hw,Ne,mi=A(()=>{"use strict";pw=Symbol("comet.native.trusted-execution-identity"),hw=Symbol("comet.native.trusted-verifier-envelope"),Ne="skill-coordinated"});function Ic(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fa(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function vi(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Tc(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,i)=>{let n=Ic(r,`Native Verifier acceptance ${i}`);ee(n,["id","result","reason"],`Native Verifier acceptance ${i}`,`${t}/${i}`);let a=vi(n.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(n.result)))throw new Error(`Native Verifier acceptance ${a} result is invalid`);return{id:a,result:n.result,reason:vi(n.reason,`Native Verifier acceptance ${a} reason`)}})}function e_(e,t){let r=Ic(e,"Native Verifier final result");if(ee(r,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result",t),!["pass","fail","blocked"].includes(String(r.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(r.risks)||!r.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Fa(r.iteration,"Native Verifier iteration"),attempt:Fa(r.attempt,"Native Verifier attempt"),verdict:r.verdict,acceptance:Tc(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:vi(r.summary,"Native Verifier summary")}}function t_(e,t,r){let i=Ic(e,`Native Verifier check request ${t}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`,`${r}/${t}`),!Array.isArray(i.argv)||!i.argv.every(a=>typeof a=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let n=Fa(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(n<1)throw new Error("Native Verifier check timeout must be positive");return{id:vi(i.id,`Native Verifier check request ${t} ID`),name:vi(i.name,`Native Verifier check request ${t} name`),executable:vi(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:vi(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:n,repeatable:i.repeatable}}function Va(e,t=""){let r=Ic(e,"Native Verifier response");if(r.kind==="final-result")return ee(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:e_(r.result,`${t}/result`)};if(r.kind==="request-checks"){if(ee(r,["kind","iteration","attempt","checks"],"Native Verifier response",t),!Array.isArray(r.checks)||r.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Fa(r.iteration,"Native Verifier iteration"),attempt:Fa(r.attempt,"Native Verifier attempt"),checks:r.checks.map((i,n)=>t_(i,n,`${t}/checks`))}}throw new Error("Native Verifier response kind is invalid")}function vw(e){if(!Ac(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=Va(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=Rf(i.result,r);return{...i,result:{...i.result,acceptance:o}}}function Rf(e,t){Tc(e.acceptance);let r=[...t.acceptanceIds],i=new Set(t.knownAcceptanceIds??r),n=new Set(t.previouslyPassedAcceptanceIds??[]),a=r.filter(h=>!i.has(h)),o=[...n].filter(h=>!i.has(h));if(a.length>0||o.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:h})=>h),l=c.filter((h,g)=>c.indexOf(h)!==g),u=c.filter(h=>!i.has(h)),f=r.filter(h=>!c.includes(h)),d=e.acceptance.filter(({id:h,result:g})=>s.has(h)||!i.has(h)?!1:!n.has(h)||g!=="passed").map(({id:h,result:g})=>`${h}=${g}`);if(l.length>0||u.length>0||f.length>0||d.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${f.join(", ")||"none"}; out-of-scope: ${d.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let p=e.acceptance.filter(({id:h})=>s.has(h));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let m=p.map(({result:h})=>h);if(e.verdict==="pass"&&m.some(h=>h!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!m.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!m.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return p}var Ma=A(()=>{"use strict";_c();mi()});function ft(e,t){if(!r_.test(e))throw new Error(`${t} must be a Git commit`)}function Ve(e){return structuredClone(e)}function Ue(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function i_(e,t){if(!Pf(t.dependsOn,e.children)){let r=t.dependsOn.filter(i=>e.children.find(({name:n})=>n===i)?.status!=="integrated");throw new Error(`Native Supervisor child ${t.name} dependency ${r[0]??"?"} is not integrated`)}}function Pf(e,t){let r=new Map(t.map(({name:i,status:n})=>[i,n]));return e.every(i=>r.get(i)==="integrated")}function gw(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Ja(e){ft(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:Wa(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:za,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 Wa(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 _f(e){let t=Ve(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=Wa(e.contract,n.name),s=T("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.candidateCommit?(n.status="needs-reverify",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):Pf(n.dependsOn,t.children)?(n.status="ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):(n.status="pending",n.blocker=null)),n.acceptanceScope=o,n.contractHash=s,n.builderFailureCount??=0}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Wa(e.contract,n.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0});return t.stateVersion+=1,t}function Lr(e,t,r){let i={child:e.child,runId:e.runId},n=(e.checkExecution?.checkStates??[]).filter(({status:o})=>o==="interrupted").map(({id:o})=>o),a=e.role==="builder"?[{kind:"supervisor-builder-result",...i,candidateCommit:"<candidate-commit>"},{kind:"supervisor-builder-failure",...i,reason:"<failure-reason>"}]:[{kind:"supervisor-checks",...i,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],materials:[],...n.length>0?{retry_check_ids:n}:{}},{kind:"supervisor-verifier-result",...i,verdict:"blocked",evidence:{summary:"<verification-summary>",checks:[],acceptance:(e.acceptance??[]).map(({id:o})=>({id:o,result:"blocked",reason:"<evidence>"})),receiptRef:e.checkExecution?.receiptRef??null}}];return{...e,controlProjectRoot:r,returnAction:{cwd:r,commandArgs:["comet","native","next",t,"--runner-input","<temporary-json-file>","--json"],inputOptions:a.map(o=>({name:o.kind,exclusiveGroup:"runner-input",template:o}))}}}function Ga(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Ve(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);i_(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,Ue(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function ww(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function Af(e,t){let r=ww(e,t),i=Ve(e);return Ue(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function jc(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Ve(e),i=r.children.find(({name:a})=>a===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);let n=i.task.role;return n==="builder"?(i.builderFailureCount=(i.builderFailureCount??0)+1,i.status=i.builderFailureCount>=cr?"blocked":"ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=n==="builder"&&(i.builderFailureCount??0)>=cr?`Builder failed ${i.builderFailureCount} times; explicit Builder retry is required. Last failure: ${t.reason}`:t.reason,Ue(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Ua(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,Ue(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function If(e,t){ft(t.candidateCommit,"Native Supervisor candidate commit");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.builderFailureCount=0,i.task=null,i.blocker=null,Ue(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Tf(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return Rf({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(t.verdict==="fail"?(i.status="ready",i.candidateCommit=null,i.verifiedCommit=null,i.verification=null,i.checks=[]):i.status="needs-reverify",i.blocker=t.evidence.summary),Ue(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function jf(e,t){if(!Number.isSafeInteger(t.expectedStateVersion)||t.expectedStateVersion<1)throw new Error("Native Supervisor Builder retry state version is invalid");if(e.stateVersion!==t.expectedStateVersion)throw new Error("Native Supervisor Builder retry input is stale");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.status!=="blocked"||i.task!==null||(i.builderFailureCount??0)<cr)throw new Error(`Native Supervisor child ${t.child} is not waiting for an explicit Builder retry`);if(!Pf(i.dependsOn,r.children))throw new Error(`Native Supervisor child ${t.child} dependencies are not integrated`);return i.status="ready",i.candidateCommit=null,i.blocker=null,i.builderFailureCount=0,Ue(r,{kind:"task-cancelled",child:i.name,runId:null,summary:"Explicit Builder retry authorized after the failure budget was exhausted"}),r.stateVersion+=1,r}function $c(e,t){ft(t.integrationCommit,"Native Supervisor integration commit");let r=Ve(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,Ue(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}function Oc(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 r_,za,cr,gi=A(()=>{"use strict";fe();Ma();r_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;za="comet.native.supervisor.v2",cr=3});import Ka from"node:path";import{promises as Nw}from"node:fs";function $f(e,t){return Ka.join(pe(e,t),"supervisor")}function wi(e,t){return Ka.join($f(e,t),"state.json")}function bw(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!==za)throw new Error(`Native Supervisor state schema must be ${za}`);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(ft(t.integration.targetCommit,"Native Supervisor target commit"),ft(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");ft(n.candidateCommit,"Native Supervisor integration candidate commit"),ft(n.integrationCommit,"Native Supervisor integration check commit"),yw(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&&ft(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(ft(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&&yw(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 O(e,t,r={}){try{let i=await Nw.readFile(wi(e,t),"utf8"),n=JSON.parse(i);if(bw(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(()=>(ut(),kf)),c=await s(Ka.join(o.changesDir,t,"comet-state.yaml")),l=await Fe({changeDir:Ka.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:dt(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:f})=>f===u.name)&&(u.acceptanceScope=Wa(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(()=>(ut(),kf)),s=await o(Ka.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 Hc(e,t){let r=await n_(e,t);if(r.length>0)throw new Error(`Native Supervisor Git binding cannot change while active child tasks exist: ${r.join(", ")}`)}async function n_(e,t){return(await O(e,t,{diagnostics:!0}))?.children.filter(({task:i})=>i!==null).map(({name:i})=>i)??[]}async function q(e,t){bw(t),await Nw.mkdir(e.changesRuntimeDir,{recursive:!0}),await we(wi(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function yw(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=A(()=>{"use strict";ne();fe();Pc();te();gi()});import{spawn as Of}from"node:child_process";import{existsSync as kw}from"node:fs";import yi from"node:path";function Hf(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function l_(e){let t=(Hf(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function u_(e,t,r){let n=yi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Hf(t,"PATH")??"").split(yi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=yi.win32.extname(e)?[e]:l_(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?yi.join(s,c):yi.resolve(r,c)))}function fn(e,t,r){return u_(e,t,r).find(i=>kw(i))??e}function d_(e){let t=Hf(e,"SystemRoot");if(t){let r=yi.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(kw(r))return r}return"powershell.exe"}function Ya(e){if(e.some(t=>s_.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function f_(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(c_,"utf16le").toString("base64");return Of(d_(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Df(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Of(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=fn(e,i,r.cwd),a=yi.win32.extname(n).toLowerCase();return o_.has(a)&&Ya(t),a_.has(a)?f_(n,t,{cwd:r.cwd,env:i}):Of(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var a_,o_,s_,c_,Dc=A(()=>{"use strict";a_=new Set([".bat",".cmd",".ps1"]),o_=new Set([".bat",".cmd"]),s_=/[&|<>()^%"!\r\n]/u,c_=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFileSync as p_}from"node:child_process";import Sw from"node:path";function v_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function pn(e,t,r={}){let i=r.timeoutMs??h_,n=r.maxBufferBytes??m_;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=Sw.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?fn(e,o,a):e,c=Sw.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Ya(t);try{return p_(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(u){let f=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Bf(e,t,f,{cause:u,timedOut:v_(u)})}}var h_,m_,Bf,Bc=A(()=>{"use strict";Dc();h_=6e4,m_=8*1024*1024,Bf=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{promises as Ew}from"node:fs";import xw from"node:path";function y_(e){let t=qf.get(e);if(!t)return;let r=t.value===null?w_:g_;if(Date.now()-t.at>r){qf.delete(e);return}return t.value}async function Ke(e){if(e===process.pid&&Lf!==null)return Lf;let t=y_(e);if(t!==void 0)return t;let r=await N_(e);return e===process.pid&&r!==null&&(Lf=r),e!==process.pid&&qf.set(e,{value:r,at:Date.now()}),r}async function N_(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Ew.readFile(`/proc/${e}/stat`,"utf8"),Ew.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await k_(e);if(process.platform==="darwin"){let t=pn("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return t?`darwin:${t}`:null}}catch{}return null}function b_(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function k_(e){try{let n=pn(xw.win32.join(process.env.SystemRoot??"C:\\Windows","System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:5e3,maxBufferBytes:4096}),a=/^CreationDate=(\S+)/mu.exec(n);if(a)return`win32-wmic:${a[1]}`}catch{}let t=process.env.SystemRoot??"C:\\Windows",r=xw.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=pn(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return b_(i)}function Lc(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function hn(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Ke(e);return r===t?"alive":r===null||Lc(r)!==Lc(t)&&Cw.has(Lc(r))&&Cw.has(Lc(t))?"unknown":"dead"}async function mn(e,t){return await hn(e,t)!=="dead"}var Lf,g_,w_,qf,Cw,Xa=A(()=>{"use strict";Bc();Lf=null,g_=6e4,w_=1e4,qf=new Map;Cw=new Set(["win32-wmic","win32-ps"])});import{spawn as S_}from"node:child_process";import Ff from"node:path";async function Qa(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&Ff.win32.isAbsolute(r)?Ff.win32.resolve(r):"C:\\Windows",n=Ff.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(f,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(f))};try{c=S_(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",f=>u(f===0)),l=setTimeout(()=>u(!1,!0),E_)}catch{u(!1)}});for(let o=0;o<x_;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var E_,x_,Vf=A(()=>{"use strict";E_=1e3,x_=2});function Me(e){return e.replace(C_,"$1 [REDACTED]").replace(R_,"[REDACTED PRIVATE KEY]").replace(P_,"$1[REDACTED]@").replace(__,"[REDACTED TOKEN]").replace(A_,'$1"[REDACTED]"').replace(I_,"$1$2$1$3$4[REDACTED]$4").replace(T_,"$1$2[REDACTED]")}var C_,R_,P_,__,A_,I_,T_,qr=A(()=>{"use strict";C_=/\b(Bearer|Basic)\s+[^\s"']+/giu,R_=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,P_=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,__=/\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,A_=/("(?:[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,I_=/(["'])((?:[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,T_=/\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 j_,constants as $_,createWriteStream as O_,existsSync as Mf,promises as H_,statSync as D_}from"node:fs";import me from"node:path";function Pw(e,t){let r=me.relative(e,t);return r===""||!me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${me.sep}`)}function _w(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Za(e,t){if(t.length===0||t.includes("\\")||me.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||me.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=me.resolve(e),i=me.resolve(r,...t.split("/"));if(!Pw(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=D_(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}function vn(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function Rw(e,t){return me.isAbsolute(e)||/[\\/]/u.test(e)?[me.resolve(t,e)]:(process.env.PATH??"").split(me.delimiter).map(r=>r.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean).map(r=>me.join(r,e))}function B_(e,t){if(process.platform==="win32"){let i=fn(e,process.env,t),n=me.win32.isAbsolute(i)?i:Rw(e,t).find(a=>Mf(a));if(!n||!Mf(n))throw new Error(`executable is not available: ${e}`);return[".bat",".cmd"].includes(me.win32.extname(n).toLowerCase()),void 0}let r=Rw(e,t).find(i=>Mf(i));if(!r)throw new Error(`executable is not available: ${e}`);try{j_(r,$_.X_OK)}catch(i){throw new Error(`executable is not executable: ${e}`,{cause:i})}}function Ye(e,t){let r=new Set;t.forEach((i,n)=>{if(r.has(i.id))throw new Error(`Native check plan duplicate ID ${i.id} at /checks/${n}/id`);r.add(i.id);let a;try{if(a=to(e,i),process.platform==="win32"){let o=fn(i.executable,process.env,a),s=me.win32.extname(o).toLowerCase();(s===".bat"||s===".cmd")&&Ya(i.argv)}B_(i.executable,a)}catch(o){throw new Error(`Native check ${i.id} is invalid at /checks/${n}: ${o.message}`,{cause:o})}})}function eo(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Me(r);return L_.test(r)&&(t=!0),i})}function to(e,t){if(_w(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return Za(e,t.cwdRef)}async function Ni(e){let{plan:t}=e;_w(e.operationId,"Native check operation ID");let r=to(e.projectRoot,t),i=me.join(e.runtimeDir,"logs","checks"),n=me.join(i,`${e.operationId}-${t.id}.log`);if(!Pw(me.resolve(e.runtimeDir),me.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await H_.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=O_(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Df(t.executable,t.argv,{cwd:r,env:process.env})}catch(g){o.destroy(),c(g);return}let u=!1,f=null,d=null,p=Promise.resolve(),m=!1,h=setTimeout(()=>{u=!0,Qa(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(h.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",g=>{f=g,o.write(`
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
174
|
+
# 可选值:neutral | strict`}}});import{constants as zc,promises as _i}from"fs";function Gp(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function uy(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function so(e){return{dev:e.dev,ino:e.ino,birthtime:Gp(e)}}function Gc(e,t){let r=so(e),i=so(t);return Pt(r,i)?te(r,i):te(r,i)&&Gp(e)===Gp(t)&&uy(e)===uy(t)&&e.size===t.size}async function En(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 _i.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new It("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new It("too-large",`${i} exceeds ${t} bytes`);let o=await _i.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:so(a)});let s=process.platform==="win32"?zc.O_RDONLY:zc.O_RDONLY|zc.O_NOFOLLOW|zc.O_NONBLOCK,c;try{c=await _i.open(e,s)}catch(l){throw l.code==="ELOOP"?new It("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),_i.lstat(e,{bigint:n}),_i.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Gc(a,l)||!Gc(a,u))throw new It("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:so(l)}),await r.hooks?.afterOpen?.();let p=[],h=0,f=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-h,{bytesRead:N}=await c.read(f,0,Math.min(f.length,w),null);if(N===0)break;if(h+=N,h>t)throw new It("too-large",`${i} exceeds ${t} bytes`);p.push(Buffer.from(f.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[m,v,g]=await Promise.all([c.stat({bigint:n}),_i.lstat(e,{bigint:n}),_i.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Gc(a,m)||!Gc(a,v))throw new It("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:so(m)}),{bytes:Buffer.concat(p,h),stat:m,realPath:g}}finally{await c.close()}}var It,co=T(()=>{"use strict";eo();It=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Jc}from"fs";import Zr from"path";function dA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Jp(e,t){let r=Zr.relative(e,t);return r===""||!Zr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Zr.sep}`)}async function dy(e,t){let r=Zr.resolve(e),i=await Jc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Jc.realpath(r)}async function py(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Zr.join(n,r[a]);let o;try{o=await Jc.lstat(n)}catch(u){if(dA(u))return{exists:!1,kind:"missing"};throw u}let s=Zr.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 Jc.realpath(n);if(!Jp(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 xn(e,t,r){let i=Mc(t,r.label),n=Zr.resolve(e),a=await dy(n,r.label),o=i.split("/"),s=Zr.resolve(n,...o);if(!Jp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await py(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function nt(e,t,r,i){let n=await xn(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 dy(n.projectRoot,i.label);return En(n.target,r,{...i,verify:async(o,s)=>{if(!Jp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await py(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var br=T(()=>{"use strict";co();Qr()});import{createHash as pA}from"crypto";function Up(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function hA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Uc(e,t={}){return(await uo(e,t)).document}async function hy(e){try{return(await nt(e,lo,no,{label:lo})).bytes}catch(t){if(hA(t))return null;throw t}}function fy(e){return e?{exists:!0,sha256:pA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Kc(e){return fy(await hy(e))}async function uo(e,t={}){let r=await hy(e);return{document:r?Sn(r.toString("utf8"),t):null,identity:fy(r)}}async function Kp(e){return(await Uc(e))?.config??null}var lo,Rn=T(()=>{"use strict";Qr();br();lo=".comet/config.yaml"});import{promises as Xp}from"node:fs";async function Qp(e,t){let r;for(let i=0;i<=Yp.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Yp.length||!fA.has(a??""))throw n;await new Promise(o=>setTimeout(o,Yp[i]))}throw r}async function Zp(e,t){await Qp(()=>Xp.rename(e,t),`rename ${t}`)}async function eh(e){await Qp(()=>Xp.unlink(e),`unlink ${e}`)}async function th(e,t){await Qp(()=>Xp.link(e,t),`link ${t}`)}var fA,Yp,rh=T(()=>{"use strict";fA=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Yp=[50,100,200]});var Cn=T(()=>{"use strict";rh();eo()});var Qq,ih=T(()=>{"use strict";Cn();Rn();br();Qq=16*1024});async function nh(e,t){if(!t)return;let r=await Kc(e);if(!Up(r,t))throw new Error("Project config changed before commit; rerun the operation")}var ah=T(()=>{"use strict";Cn();Qr();Rn();br();ih()});import{randomUUID as wA}from"crypto";import{promises as je}from"fs";import Tt from"path";function Yc(e,t){let r=Tt.relative(e,t);return r===""||!Tt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Tt.sep}`)}function yA(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xc(e,t){return te({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function bA(e,t){return Xc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function my(e){let t=await je.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 je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Pn(e){for(let t of e){let r=await je.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!yA(t,r)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function NA(e,t,r){let[i,n]=await Promise.all([je.lstat(e),je.realpath(e),r?Pn(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Xc(i,t)||r&&!Yc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function kA(e,t){let r=Tt.resolve(e),i=Tt.resolve(t);if(!Yc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await my(r)],a=Tt.relative(r,i).split(Tt.sep).filter(Boolean),o=r;for(let s of a){await Pn(n),o=Tt.join(o,s);try{await je.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await my(o);if(!Yc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Pn(n),n}async function SA(e){let t;try{t=await je.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 EA(e,t,r={}){let i=Tt.dirname(e),n=r.containedRoot?await kA(r.containedRoot,i):null;n||await je.mkdir(i,{recursive:!0});let a=Tt.join(i,`.${Tt.basename(e)}.${wA()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await je.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([je.lstat(a),je.realpath(a)]);if(await Pn(n),!l.isFile()||l.isSymbolicLink()||!Xc(s,l)||!Yc(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(),!Xc(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 NA(a,c,n),await r.beforeCommit?.(),n){await Pn(n);let l=await je.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!bA(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await th(a,e),await eh(a)):await Zp(a,e),await SA(i)}catch(l){if(await o?.close(),!n)await je.rm(a,{force:!0});else try{await Pn(n),await je.rm(a,{force:!0})}catch{}throw l}}async function mt(e,t,r={}){await EA(e,t,r)}async function fe(e,t,r={}){await mt(e,JSON.stringify(t,null,2)+`
|
|
175
|
+
`,r)}var ne=T(()=>{"use strict";rh();Jt()});import{existsSync as vy,promises as Ai}from"fs";import K from"path";import xA from"os";async function oh(e){try{return await Ai.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function CA(e){try{let t=await Ai.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function An(e,t){let r=K.relative(e,t);return r===""||!K.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${K.sep}`)}async function _n(e){let t=[],r=e;for(;!await oh(r);){let n=K.dirname(r);if(n===r)break;t.push(K.basename(r)),r=n}let i=await Ai.realpath(r);return K.resolve(i,...t.reverse())}async function sh(e){try{return(await Ai.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Qc(e){let t=K.resolve(e);try{(await Ai.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=K.resolve(xA.homedir());for(;;){if(!(t===i&&r!==i)){let o=K.join(t,...ho.split("/")),s=t===r||await CA(o);if(await oh(o)&&s)return t}if(await oh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return r;t=a}}function Zc(e){return Pi(e)}async function PA(e,t){let r=Zc(t),i=K.resolve(e,...r.split("/")),n=await Ai.realpath(e),a=await _n(i);if(!An(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function ei(e,t){let r=Zc(t),i=await PA(e,r),n=K.join(i,"comet");if(await sh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_n(i),_n(n)]);if(!An(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await sh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ai.realpath(s),_n(c)]);if(!An(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...ho.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function gy(e){if(!RA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function me(e,t){gy(t);let r=K.join(e.changesRuntimeDir,t);if(!Ee(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function ch(e,t){gy(t);let r=K.join(e.changesDir,t,"runtime");if(!Ee(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function vt(e,t){let r=me(e,t);if(vy(r))return r;let i=ch(e,t);return vy(i)?i:r}function lh(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=K.resolve(e,...t.slice(8).split("/"));if(!Ee(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ge(e,t){let r=K.resolve(t);if(Ee(e.runtimeDir,r))return e.runtimeDir;if(Ee(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function Ee(e,t){return An(K.resolve(e),K.resolve(t))}async function G(e,t){let r=K.resolve(e),i=K.resolve(t);if(!An(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await sh(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_n(r),_n(i)]);if(!An(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var ho,RA,ie=T(()=>{"use strict";Qr();ho=".comet/config.yaml",RA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import _A from"path";function AA(e="docs",t="en"){return Wc(e,t)}async function Oe(e){let t=(await Uc(e))?.config??null;return t?.native?t:null}async function tl(e){let t=await Oe(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function rl(e,t,r={}){let i=await uo(e,{allowPartialProject:!0}),n=oo(i.document?.value??{},t),a=_A.join(e,...ho.split("/"));await mt(a,ao(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await nh(e,i.identity)}})}async function wy(e){let t=await Qc(e.startPath),r=await Oe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${ho} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?Zc(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??AA(i??"docs"),a=await ei(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var el,gt=T(()=>{"use strict";Qr();Rn();ah();ne();ie();el=Vc});function ee(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 fo({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var fo,mo=T(()=>{"use strict";fo=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 uh(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 Tn(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}]`;ee(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:uh(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>uh(o,`${n}.evidence`)),note:uh(i.note,`${n}.note`)}})}function $n(e,t){if(!t)throw new In(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 In(o,s)}var In,vo=T(()=>{"use strict";mo();In=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 nl(){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 Ii,go,il,jn=T(()=>{"use strict";Ii="comet.native.v4",go="comet.native.local-execution.v4",il=["multi-session","single-session"]});var fh={};Qu(fh,{NativePortableStateVersionConflictError:()=>wo,appendNativePortableHistory:()=>ke,compareAndSwapNativePortableState:()=>Dn,createNativePortableState:()=>by,parseNativePortableState:()=>B,readNativePortableState:()=>yt,writeNativePortableState:()=>yo});import{promises as IA}from"node:fs";function He(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function De(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 xe(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 ph(e,t){return e===null?null:xe(e,t)}function hh(e,t){let r=xe(e,t);if(!OA.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function On(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function se(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function DA(e,t){return e===null?null:se(e,t,Number.MIN_SAFE_INTEGER)}function ye(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ut(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function cl(e,t){return Ut(e,t,(r,i)=>xe(r,`${t}[${i}]`))}function Ti(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Hn(e,t){let r=xe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ol(e,t,r=!1){let i=xe(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 wt(e,t){let r=He(e,t);return De(r,new Set(["text","truncated"]),t),{text:xe(r.text,`${t}.text`,{empty:!0}),truncated:On(r.truncated,`${t}.truncated`)}}function BA(e,t){let r=`Native spec_changes[${t}]`,i=He(e,r);De(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=xe(i.capability,`${r}.capability`);if(!$A.test(n))throw new Error(`${r}.capability is invalid`);let a=ye(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ol(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:ol(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:hh(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 LA(e){let t="Native workspace",r=He(e,t);De(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ye(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=ph(r.change_branch,`${t}.change_branch`),a=ph(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ye(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 qA(e){let t="Native loop",r=He(e,t);De(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=cl(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ti(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ye(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ye(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:se(r.goal_cycle,`${t}.goal_cycle`,1),iteration:se(r.iteration,`${t}.iteration`),attempt:se(r.attempt,`${t}.attempt`),retry_epoch:se(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:se(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:se(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:se(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:ph(r.next_action,`${t}.next_action`)}}function FA(e,t){let r=`Native acceptance[${t}]`,i=He(e,r);De(i,new Set(["id","source","text","result","reason"]),r);let n=xe(i.id,`${r}.id`);if(!jA.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ol(i.source,`${r}.source`),text:xe(i.text,`${r}.text`),result:ye(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:wt(i.reason,`${r}.reason`)}}function MA(e,t){let r=`Native builder_handoff.checks[${t}]`,i=He(e,r);return De(i,new Set(["name","result","note"]),r),{name:wt(i.name,`${r}.name`),result:ye(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:wt(i.note,`${r}.note`)}}function VA(e){let t="Native builder_handoff",r=He(e,t);De(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=cl(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ti(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:He(r.review,`${t}.review`);return n&&De(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:xe(r.candidate_id,`${t}.candidate_id`),identity_provider:xe(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:xe(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),summary:wt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:Tn(r.acceptance_review)},checks:Ut(r.checks,`${t}.checks`,MA),checks_truncated:On(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ut(r.known_limits,`${t}.known_limits`,(a,o)=>wt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:On(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ye(n.status,["passed"],`${t}.review.status`),summary:wt(n.summary,`${t}.review.summary`),reviewer_execution_ref:xe(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Hn(r.submitted_at,`${t}.submitted_at`)}}function WA(e,t){let r=`Native blockers[${t}]`,i=He(e,r);De(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=cl(i.acceptance_ids,`${r}.acceptance_ids`);return Ti(n,`${r}.acceptance_ids`),{owner:ye(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:wt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ye(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function zA(e,t){let r=`Native verification.checks[${t}]`,i=He(e,r);return De(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:xe(i.id,`${r}.id`),name:wt(i.name,`${r}.name`),argv_display:Ut(i.argv_display,`${r}.argv_display`,(n,a)=>wt(n,`${r}.argv_display[${a}]`)),argv_truncated:On(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ol(i.cwd_ref,`${r}.cwd_ref`,!0),status:ye(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:DA(i.exit_code,`${r}.exit_code`),duration_ms:se(i.duration_ms,`${r}.duration_ms`)}}function GA(e){let t="Native verification",r=He(e,t);De(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ut(r.checks,`${t}.checks`,zA);Ti(i.map(a=>a.id),`${t}.checks IDs`);let n=xe(r.identity_provider,`${t}.identity_provider`);return{candidate_id:xe(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:xe(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),attempt:se(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ye(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ye(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:wt(r.summary,`${t}.summary`),risks:Ut(r.risks,`${t}.risks`,(a,o)=>wt(a,`${t}.risks[${o}]`)),risks_truncated:On(r.risks_truncated,`${t}.risks_truncated`),completed_at:Hn(r.completed_at,`${t}.completed_at`)}}function yy(e,t){let r=`Native history[${t}]`,i=He(e,r);De(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=cl(i.unresolved_ids,`${r}.unresolved_ids`);return Ti(n,`${r}.unresolved_ids`),{goal_cycle:se(i.goal_cycle,`${r}.goal_cycle`,1),iteration:se(i.iteration,`${r}.iteration`),attempt:se(i.attempt,`${r}.attempt`),outcome:ye(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:wt(i.summary,`${r}.summary`),completed_at:Hn(i.completed_at,`${r}.completed_at`)}}function JA(e){let t="Native history_overflow.outcome_counts",r=He(e,t),i=["pass","fail","blocked","execution-error","recovery"];return De(r,new Set(i),t),{pass:se(r.pass,`${t}.pass`),fail:se(r.fail,`${t}.fail`),blocked:se(r.blocked,`${t}.blocked`),"execution-error":se(r["execution-error"],`${t}.execution-error`),recovery:se(r.recovery,`${t}.recovery`)}}function UA(e){let t="Native history_overflow",r=He(e,t);De(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=se(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Hn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Hn(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=JA(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 KA(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&&$n(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 YA(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 B(e){let t=He(e,"Native portable state");if(De(t,HA,"Native portable state"),t.schema!==Ii)throw new Error(`Native portable state schema must be ${Ii}`);let r=xe(t.name,"Native state name");if(!TA.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=Ut(t.spec_changes,"Native spec_changes",BA);Ti(i.map(s=>s.capability),"Native spec change capabilities");let n=Ut(t.acceptance,"Native acceptance",FA);Ti(n.map(s=>s.id),"Native acceptance IDs");let a=Ut(t.history,"Native history",yy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ii,name:r,language:ye(t.language,["en","zh-CN"],"Native state language"),phase:ye(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ye(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:se(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1 or 2")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:hh(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:hh(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ye(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:LA(t.workspace),loop:qA(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:VA(t.builder_handoff),blockers:Ut(t.blockers,"Native blockers",WA),verification:t.verification===null?null:GA(t.verification),history:a,history_overflow:UA(t.history_overflow),verification_result:ye(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ye(t.verification_report,["verification.md"],"Native verification_report"),archived:On(t.archived,"Native archived"),created_at:Hn(t.created_at,"Native created_at")};return KA(o),YA(o),o}function by(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return B({schema:Ii,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:nl(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ke(e,t){let r=B(e),i=yy(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 B({...r,history:n,history_overflow:a})}function XA(e,t){let r=(0,sl.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 yt(e){let t=await IA.readFile(e,"utf8");return B(XA(t,"Native portable state"))}async function yo(e,t,r={}){let i=B(t);await mt(e,(0,sl.stringify)(i),r)}async function QA(e,t){let r=al.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);al.set(e,a),await r;try{return await t()}finally{i(),al.get(e)===a&&al.delete(e)}}async function Dn(e){return QA(e.file,async()=>{let t=se(e.expectedStateVersion,"Native expected state version",1),r=B(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await yt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new wo(t,i.state_version);return await yo(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await yt(e.file);if(n.state_version!==t)throw new wo(t,n.state_version)}}),r})}var sl,TA,$A,jA,OA,HA,wo,al,at=T(()=>{"use strict";vo();sl=fr(Gt(),1);ne();jn();TA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jA=/^A[1-9][0-9]*$/u,OA=/^[a-f0-9]{64}$/u,HA=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"]),wo=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"};al=new Map});import{promises as ZA}from"node:fs";import eI from"node:path";function ul(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function ll(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 ky(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 oI(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 Sy(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 Cy(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===vh&&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=>!Ey(e.children,l)),xy(i)?i:null}if(e.schema===$i&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!Ey(e.children,a)),xy(i)?i:null}return null}function Ey(e,t){return e.some(r=>r.covers.includes(t))}function xy(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function bt(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 sI(e){let t=ul(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=ul(n,`Native children acceptance_index.${i}`);if(ll(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 cI(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(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${p.join(", ")} exactly from the current acceptance catalog`)}}}function Py(e,t,r={}){let i=(0,Ry.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ul(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==$i&&a!==ti)throw ll(n,Ny,"Native children contract"),new Error(`Native children schema must be ${$i} or ${ti}`);let o=a===$i?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(ll(n,o==="indexed-v2"?rI:Ny,"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,h)=>{let f=ul(p,`Native child ${h}`);if(ll(f,o==="indexed-v2"?aI:o==="summary-v2"?nI:iI,`Native ${s} child fields (child ${h})`),typeof f.name!="string"||!tI.test(f.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof f.summary!="string"||f.summary.trim().length===0)throw new Error(`Native child ${f.name} summary must be a non-empty string`);if(f.summary.length>2e3)throw new Error(`Native child ${f.name} summary exceeds 2000 characters`)}return{name:f.name,summary:m?f.summary:null,depends_on:ky(f.depends_on,`Native child ${f.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?ky(f.covers,`Native child ${f.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 h=p.depends_on.filter(f=>!u.has(f));if(h.length>0)throw new Error(`Native child ${p.name} depends on unknown child: ${h.join(", ")}`)}oI(c);let d=r.policy==="advisory";if(a===vh){if(o==="indexed-v2"){let p=sI(n.acceptance_index);d||cI(p,t,r);let h=Object.keys(p);return d||Sy(c,h,h),{schema:ti,acceptance_index:p,children:c}}return{schema:ti,children:c}}return t&&!d&&Sy(c,t),{schema:$i,children:c}}async function Je(e){let t=eI.join(e.changeDir,mh);try{await ZA.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Z({root:e.changeDir,ref:mh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Py(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Cy(a,e.acceptanceIds,e.validation??{}):null}}var Ry,mh,$i,ti,vh,tI,Ny,rI,iI,nI,aI,dl=T(()=>{"use strict";Ry=fr(Gt(),1);rt();mh="children.yaml",$i="comet.native.children.v1",ti="comet.native.children.v2",vh=ti,tI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ny=new Set(["schema","children"]),rI=new Set(["schema","acceptance_index","children"]),iI=new Set(["name","depends_on","covers"]),nI=new Set(["name","summary","depends_on"]),aI=new Set(["name","depends_on","covers"])});function gh(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function wh(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){gh(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Se,executionRef:gh(t.executionRef,"Native execution ref"),[_y]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:gh(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Ay]:!0})}})}function pl(e){return typeof e=="object"&&e!==null&&e[Ay]===!0}function Iy(e){return typeof e=="object"&&e!==null&&e[_y]===!0}var _y,Ay,Se,ji=T(()=>{"use strict";_y=Symbol("comet.native.trusted-execution-identity"),Ay=Symbol("comet.native.trusted-verifier-envelope"),Se="skill-coordinated"});function hl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bo(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Oi(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function fl(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,i)=>{let n=hl(r,`Native Verifier acceptance ${i}`);ee(n,["id","result","reason"],`Native Verifier acceptance ${i}`,`${t}/${i}`);let a=Oi(n.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(n.result)))throw new Error(`Native Verifier acceptance ${a} result is invalid`);return{id:a,result:n.result,reason:Oi(n.reason,`Native Verifier acceptance ${a} reason`)}})}function lI(e,t){let r=hl(e,"Native Verifier final result");if(ee(r,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result",t),!["pass","fail","blocked"].includes(String(r.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(r.risks)||!r.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:bo(r.iteration,"Native Verifier iteration"),attempt:bo(r.attempt,"Native Verifier attempt"),verdict:r.verdict,acceptance:fl(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:Oi(r.summary,"Native Verifier summary")}}function uI(e,t,r){let i=hl(e,`Native Verifier check request ${t}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`,`${r}/${t}`),!Array.isArray(i.argv)||!i.argv.every(a=>typeof a=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let n=bo(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(n<1)throw new Error("Native Verifier check timeout must be positive");return{id:Oi(i.id,`Native Verifier check request ${t} ID`),name:Oi(i.name,`Native Verifier check request ${t} name`),executable:Oi(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:Oi(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:n,repeatable:i.repeatable}}function No(e,t=""){let r=hl(e,"Native Verifier response");if(r.kind==="final-result")return ee(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:lI(r.result,`${t}/result`)};if(r.kind==="request-checks"){if(ee(r,["kind","iteration","attempt","checks"],"Native Verifier response",t),!Array.isArray(r.checks)||r.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:bo(r.iteration,"Native Verifier iteration"),attempt:bo(r.attempt,"Native Verifier attempt"),checks:r.checks.map((i,n)=>uI(i,n,`${t}/checks`))}}throw new Error("Native Verifier response kind is invalid")}function Ty(e){if(!pl(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=No(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=yh(i.result,r);return{...i,result:{...i.result,acceptance:o}}}function yh(e,t){fl(e.acceptance);let r=[...t.acceptanceIds],i=new Set(t.knownAcceptanceIds??r),n=new Set(t.previouslyPassedAcceptanceIds??[]),a=r.filter(m=>!i.has(m)),o=[...n].filter(m=>!i.has(m));if(a.length>0||o.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:m})=>m),l=c.filter((m,v)=>c.indexOf(m)!==v),u=c.filter(m=>!i.has(m)),d=r.filter(m=>!c.includes(m)),p=e.acceptance.filter(({id:m,result:v})=>s.has(m)||!i.has(m)?!1:!n.has(m)||v!=="passed").map(({id:m,result:v})=>`${m}=${v}`);if(l.length>0||u.length>0||d.length>0||p.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${d.join(", ")||"none"}; out-of-scope: ${p.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let h=e.acceptance.filter(({id:m})=>s.has(m));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let f=h.map(({result:m})=>m);if(e.verdict==="pass"&&f.some(m=>m!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!f.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!f.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return h}var ko=T(()=>{"use strict";mo();ji()});function Nt(e,t){if(!dI.test(e))throw new Error(`${t} must be a Git commit`)}function Ue(e){return structuredClone(e)}function ot(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function pI(e,t){if(!bh(t.dependsOn,e.children)){let r=t.dependsOn.filter(i=>e.children.find(({name:n})=>n===i)?.status!=="integrated");throw new Error(`Native Supervisor child ${t.name} dependency ${r[0]??"?"} is not integrated`)}}function bh(e,t){let r=new Map(t.map(({name:i,status:n})=>[i,n]));return e.every(i=>r.get(i)==="integrated")}function $y(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function xo(e){Nt(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:So(e.contract,i.name),contractHash:$("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:Eo,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 So(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 Nh(e){let t=Ue(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=So(e.contract,n.name),s=$("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.candidateCommit?(n.status="needs-reverify",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):bh(n.dependsOn,t.children)?(n.status="ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):(n.status="pending",n.blocker=null)),n.acceptanceScope=o,n.contractHash=s,n.builderFailureCount??=0}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:So(e.contract,n.name),contractHash:$("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0});return t.stateVersion+=1,t}function ri(e,t,r){let i={child:e.child,runId:e.runId},n=(e.checkExecution?.checkStates??[]).filter(({status:o})=>o==="interrupted").map(({id:o})=>o),a=e.role==="builder"?[{kind:"supervisor-builder-result",...i,candidateCommit:"<candidate-commit>"},{kind:"supervisor-builder-failure",...i,reason:"<failure-reason>"}]:[{kind:"supervisor-checks",...i,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],materials:[],...n.length>0?{retry_check_ids:n}:{}},{kind:"supervisor-verifier-result",...i,verdict:"blocked",evidence:{summary:"<verification-summary>",checks:[],acceptance:(e.acceptance??[]).map(({id:o})=>({id:o,result:"blocked",reason:"<evidence>"})),receiptRef:e.checkExecution?.receiptRef??null}}];return{...e,controlProjectRoot:r,returnAction:{cwd:r,commandArgs:["comet","native","next",t,"--runner-input","<temporary-json-file>","--json"],inputOptions:a.map(o=>({name:o.kind,exclusiveGroup:"runner-input",template:o}))}}}function Ro(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Ue(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);pI(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,ot(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function jy(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function kh(e,t){let r=jy(e,t),i=Ue(e);return ot(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function ml(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Ue(e),i=r.children.find(({name:a})=>a===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);let n=i.task.role;return n==="builder"?(i.builderFailureCount=(i.builderFailureCount??0)+1,i.status=i.builderFailureCount>=Nr?"blocked":"ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=n==="builder"&&(i.builderFailureCount??0)>=Nr?`Builder failed ${i.builderFailureCount} times; explicit Builder retry is required. Last failure: ${t.reason}`:t.reason,ot(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Co(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,ot(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Sh(e,t){Nt(t.candidateCommit,"Native Supervisor candidate commit");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.builderFailureCount=0,i.task=null,i.blocker=null,ot(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Eh(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return yh({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(t.verdict==="fail"?(i.status="ready",i.candidateCommit=null,i.verifiedCommit=null,i.verification=null,i.checks=[]):i.status="needs-reverify",i.blocker=t.evidence.summary),ot(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function xh(e,t){if(!Number.isSafeInteger(t.expectedStateVersion)||t.expectedStateVersion<1)throw new Error("Native Supervisor Builder retry state version is invalid");if(e.stateVersion!==t.expectedStateVersion)throw new Error("Native Supervisor Builder retry input is stale");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.status!=="blocked"||i.task!==null||(i.builderFailureCount??0)<Nr)throw new Error(`Native Supervisor child ${t.child} is not waiting for an explicit Builder retry`);if(!bh(i.dependsOn,r.children))throw new Error(`Native Supervisor child ${t.child} dependencies are not integrated`);return i.status="ready",i.candidateCommit=null,i.blocker=null,i.builderFailureCount=0,ot(r,{kind:"task-cancelled",child:i.name,runId:null,summary:"Explicit Builder retry authorized after the failure budget was exhausted"}),r.stateVersion+=1,r}function vl(e,t){Nt(t.integrationCommit,"Native Supervisor integration commit");let r=Ue(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,ot(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}function gl(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 dI,Eo,Nr,Hi=T(()=>{"use strict";pe();ko();dI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Eo="comet.native.supervisor.v2",Nr=3});import Po from"node:path";import{promises as Hy}from"node:fs";function Rh(e,t){return Po.join(me(e,t),"supervisor")}function Di(e,t){return Po.join(Rh(e,t),"state.json")}function Dy(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!==Eo)throw new Error(`Native Supervisor state schema must be ${Eo}`);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(Nt(t.integration.targetCommit,"Native Supervisor target commit"),Nt(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");Nt(n.candidateCommit,"Native Supervisor integration candidate commit"),Nt(n.integrationCommit,"Native Supervisor integration check commit"),Oy(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&&Nt(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(Nt(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&&Oy(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 D(e,t,r={}){try{let i=await Hy.readFile(Di(e,t),"utf8"),n=JSON.parse(i);if(Dy(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(()=>(at(),fh)),c=await s(Po.join(o.changesDir,t,"comet-state.yaml")),l=await Je({changeDir:Po.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:bt(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=So(l.contract,u.name),u.contractHash=$("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(()=>(at(),fh)),s=await o(Po.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 wl(e,t){let r=await hI(e,t);if(r.length>0)throw new Error(`Native Supervisor Git binding cannot change while active child tasks exist: ${r.join(", ")}`)}async function hI(e,t){return(await D(e,t,{diagnostics:!0}))?.children.filter(({task:i})=>i!==null).map(({name:i})=>i)??[]}async function F(e,t){Dy(t),await Hy.mkdir(e.changesRuntimeDir,{recursive:!0}),await fe(Di(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Oy(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=T(()=>{"use strict";ne();pe();dl();ie();Hi()});import{createHash as Ph,randomUUID as fI}from"node:crypto";import{promises as st}from"node:fs";import mI from"node:os";import Ke from"node:path";async function Ch(e,t){let r=await st.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await st.readFile(e),n=await st.lstat(e,{bigint:!0});if(r.ino!==n.ino||r.ctimeNs!==n.ctimeNs||r.size!==n.size)throw new Error("Process probe cache changed");return i}async function qy(e){try{let t=JSON.parse((await Ch(Ke.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=Ke.join(e,t.file),i=await Ch(r,65536);return Ph("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function wI(e,t){let r,i=fI(),n=Ke.join(e,`probe-${i}.cs`),a=Ke.join(e,`probe-${i}.exe`),o=Ke.join(e,`probe-${i}.json`);try{if(await st.mkdir(e,{recursive:!0,mode:448}),(await st.lstat(e)).isSymbolicLink())return null;r=await st.open(Ke.join(e,"prepare.lock"),"wx",384);let s=await qy(e);if(s)return s;await st.writeFile(n,Ly,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=Ke.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await st.access(d),c=d;break}catch{}}if(!c)return null;await Gr(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=Ph("sha256").update(await Ch(a,65536)).digest("hex");return await st.writeFile(o,JSON.stringify({file:Ke.basename(a),hash:l}),{flag:"wx",mode:384}),await st.rename(o,Ke.join(e,"probe.json")),a}catch{return null}finally{await st.unlink(n).catch(()=>{}),await st.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await st.unlink(Ke.join(e,"prepare.lock")).catch(()=>{}))}}async function By(e,t,r){try{let i=await Gr(Ke.join(t,"System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),n=/^CreationDate=(\S+)/mu.exec(i);if(n)return`win32-wmic:${n[1]}`}catch{}if(r.aborted)return null;try{let n=(await Gr(Ke.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function yI(e,t){let r=yl.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:wI(e,t),retryAfter:1/0};return yl.set(e,i),i.promise.then(n=>{yl.get(e)===i&&(n?yl.delete(e):i.retryAfter=performance.now()+gI)}),i.promise}async function Fy(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=Ke.join(t.cacheRoot??Ke.join(mI.tmpdir(),"comet-process-identity"),vI),n=async l=>{if(!l)return null;try{let d=(await Gr(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await qy(i);if(a){let l=await n(a);return l||By(e,r,new AbortController().signal)}let o=yI(i,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(n).then(c),By(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Ly,vI,gI,yl,My=T(()=>{"use strict";yn();Ly=`using System;
|
|
176
|
+
using System.Runtime.InteropServices;
|
|
177
|
+
class CometProcessIdentity {
|
|
178
|
+
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
|
179
|
+
[DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
|
|
180
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
|
181
|
+
static int Main(string[] args) {
|
|
182
|
+
int pid; if(args.Length != 1 || !int.TryParse(args[0], out pid) || pid <= 0) return 1;
|
|
183
|
+
IntPtr handle=OpenProcess(0x1000, false, pid); if(handle == IntPtr.Zero) return 1;
|
|
184
|
+
try { long creation, exit, kernel, user; if(!GetProcessTimes(handle,out creation,out exit,out kernel,out user)) return 1;
|
|
185
|
+
Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
|
|
186
|
+
} finally { CloseHandle(handle); }
|
|
187
|
+
}
|
|
188
|
+
}`,vI=Ph("sha256").update(Ly).digest("hex"),gI=1e4,yl=new Map});import{promises as Vy}from"node:fs";function NI(e){let t=Ah.get(e);if(t){if(Date.now()-t.at>bI){Ah.delete(e);return}return t.value}}async function ct(e){if(e===process.pid&&_h!==null)return _h;let t=NI(e);if(t!==void 0)return t;let r=bl.get(e);r||(r=kI(e),bl.set(e,r));let i=await r;return bl.get(e)===r&&bl.delete(e),e===process.pid&&i!==null&&(_h=i),i===null&&Ah.set(e,{value:null,at:Date.now()}),i}async function kI(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Vy.readFile(`/proc/${e}/stat`,"utf8"),Vy.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await Fy(e);if(process.platform==="darwin"){let t=(await Gr("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return t?`darwin:${t}`:null}}catch{}return null}function Nl(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function Bn(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await ct(e);return r===t?"alive":r===null||Nl(r)!==Nl(t)&&Wy.has(Nl(r))&&Wy.has(Nl(t))?"unknown":"dead"}async function Ln(e,t){return await Bn(e,t)!=="dead"}var _h,bI,Ah,bl,Wy,_o=T(()=>{"use strict";yn();My();_h=null,bI=1e4,Ah=new Map,bl=new Map;Wy=new Set(["win32-wmic","win32-ps"])});import{spawn as SI}from"node:child_process";import Ih from"node:path";async function Ao(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&Ih.win32.isAbsolute(r)?Ih.win32.resolve(r):"C:\\Windows",n=Ih.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,p=!1)=>{s||(s=!0,l&&clearTimeout(l),p&&c?.kill("SIGKILL"),o(d))};try{c=SI(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),EI)}catch{u(!1)}});for(let o=0;o<xI;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var EI,xI,Th=T(()=>{"use strict";EI=1e3,xI=2});function Ye(e){return e.replace(RI,"$1 [REDACTED]").replace(CI,"[REDACTED PRIVATE KEY]").replace(PI,"$1[REDACTED]@").replace(_I,"[REDACTED TOKEN]").replace(AI,'$1"[REDACTED]"').replace(II,"$1$2$1$3$4[REDACTED]$4").replace(TI,"$1$2[REDACTED]")}var RI,CI,PI,_I,AI,II,TI,ii=T(()=>{"use strict";RI=/\b(Bearer|Basic)\s+[^\s"']+/giu,CI=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,PI=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,_I=/\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,II=/(["'])((?:[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,TI=/\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 $I,constants as jI,createWriteStream as OI,existsSync as $h,promises as HI,statSync as DI}from"node:fs";import be from"node:path";function Gy(e,t){let r=be.relative(e,t);return r===""||!be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${be.sep}`)}function Jy(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Io(e,t){if(t.length===0||t.includes("\\")||be.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||be.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=be.resolve(e),i=be.resolve(r,...t.split("/"));if(!Gy(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=DI(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}function qn(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function zy(e,t){return be.isAbsolute(e)||/[\\/]/u.test(e)?[be.resolve(t,e)]:(process.env.PATH??"").split(be.delimiter).map(r=>r.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean).map(r=>be.join(r,e))}function BI(e,t){if(process.platform==="win32"){let i=xi(e,process.env,t),n=be.win32.isAbsolute(i)?i:zy(e,t).find(a=>$h(a));if(!n||!$h(n))throw new Error(`executable is not available: ${e}`);return[".bat",".cmd"].includes(be.win32.extname(n).toLowerCase()),void 0}let r=zy(e,t).find(i=>$h(i));if(!r)throw new Error(`executable is not available: ${e}`);try{$I(r,jI.X_OK)}catch(i){throw new Error(`executable is not executable: ${e}`,{cause:i})}}function lt(e,t){let r=new Set;t.forEach((i,n)=>{if(r.has(i.id))throw new Error(`Native check plan duplicate ID ${i.id} at /checks/${n}/id`);r.add(i.id);let a;try{if(a=$o(e,i),process.platform==="win32"){let o=xi(i.executable,process.env,a),s=be.win32.extname(o).toLowerCase();(s===".bat"||s===".cmd")&&Ka(i.argv)}BI(i.executable,a)}catch(o){throw new Error(`Native check ${i.id} is invalid at /checks/${n}: ${o.message}`,{cause:o})}})}function To(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Ye(r);return LI.test(r)&&(t=!0),i})}function $o(e,t){if(Jy(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return Io(e,t.cwdRef)}async function Bi(e){let{plan:t}=e;Jy(e.operationId,"Native check operation ID");let r=$o(e.projectRoot,t),i=be.join(e.runtimeDir,"logs","checks"),n=be.join(i,`${e.operationId}-${t.id}.log`);if(!Gy(be.resolve(e.runtimeDir),be.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await HI.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=OI(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Dp(t.executable,t.argv,{cwd:r,env:process.env})}catch(v){o.destroy(),c(v);return}let u=!1,d=null,p=null,h=Promise.resolve(),f=!1,m=setTimeout(()=>{u=!0,Ao(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(m.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",v=>{d=v,o.write(`
|
|
189
|
+
[comet] failed to start check: ${Ye(v.message)}
|
|
190
|
+
`)}),l.once("close",(v,g)=>{f=!0,clearTimeout(m);let w=(e.now??(()=>new Date))();h.then(()=>{if(p!==null){o.destroy(),c(p);return}o.end(()=>{let N=u||d!==null||g!==null;s({id:t.id,name:t.name,argvDisplay:To(t.argv),cwdRef:t.cwdRef,status:N?"interrupted":v===0?"passed":"failed",exitCode:v,signal:g,timedOut:u,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:be.relative(e.runtimeDir,n).split(be.sep).join("/")})})})}),o.once("error",v=>{clearTimeout(m),p??=v,f?h.then(()=>c(p)):Ao(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let v=l.pid;h=Promise.resolve().then(()=>e.onSpawn({pid:v})).catch(async g=>{p=g,l.exitCode===null&&l.signalCode===null&&await Ao(l).catch(()=>l.kill("SIGKILL"))})}})}var LI,Fn=T(()=>{"use strict";Ya();Th();ii();LI=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});import{AsyncLocalStorage as qI}from"async_hooks";import{randomUUID as Yy}from"crypto";import{promises as kt}from"fs";import Xy from"os";import ce from"path";function VI(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function WI(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Qy(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Sl(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Pt(r,i)?te(r,i):te(r,i)&&e.size===t.size}function jo(e,t){return Sl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function zI(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&jo(e.identity,t.identity)}async function St(e){let t,r;try{let i=await En(e,Uy,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof It?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Uy} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:WI(JSON.parse(t.toString("utf8")),e),identity:Qy(r)}}async function GI(e){return(await St(e))?.owner??null}async function Oh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Xy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await Bn(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function JI(e,t){try{await kt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await kt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function El(e,t){let r=await St(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!jo(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await kt.mkdir(t,{recursive:!0});let i=ce.join(t,`${ce.basename(e.file)}.${e.owner.id}.${Yy()}.removed`);try{await kt.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await St(i);if(!n||n.owner.id!==e.owner.id||!Sl(n.identity,e.identity))throw await JI(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await kt.rm(i,{force:!0}),"removed"}async function Zy(e){let t=await ct(process.pid);return{id:Yy(),pid:process.pid,hostname:Xy.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function eb(e,t){let r;try{r=await kt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await GI(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
191
|
+
`,"utf8"),await r.sync(),i=Qy(await r.stat({bigint:!0}))}finally{await r.close()}let n=await St(e);if(!i||!n||n.owner.id!==t.id||!Sl(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function UI(e,t){let r=await G(e.runtimeDir,e.locksDir);await kt.mkdir(r,{recursive:!0});let i=await G(e.runtimeDir,ce.join(r,jh));await kt.mkdir(i,{recursive:!0});let n=await Zy(t),a=ce.join(i,`.${n.id}.tmp`),o=ce.join(i,`${n.id}.claim`);try{let s=await eb(a,n);await kt.rename(a,o);let c=await St(o);if(!c||!Sl(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await kt.rm(a,{force:!0})}}async function KI(e){let t=ce.dirname(e.file),r=!1,i=ce.basename(e.file);for(let n of await kt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ce.join(t,n.name);if(ce.resolve(a)!==ce.resolve(e.file))try{let o=await St(a),s=await Oh(o);if(s.status==="missing")continue;let c=await St(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!jo(c.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await El(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function tb(e){let t=await St(e.file);if(t){if(t.owner.id!==e.owner.id||!jo(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await El(t,ce.dirname(e.file))}}async function YI(e,t){let r=Date.now()+FI;for(;;){let i=await UI(e,t);if(!await KI(i))return i;if(await tb(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function XI(e){let t=kl.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return kl.set(e,n),await t,()=>{r(),kl.get(e)===n&&kl.delete(e)}}async function xl(e,t,r){let i=ce.resolve(e.locksDir),n=Ky.getStore();if(n?.has(i))return r();let a=await XI(i);try{let o=await YI(e,t),s=new Map(n??[]);return s.set(i,o),await Ky.run(s,async()=>{try{return await r()}finally{await tb(o)}})}finally{a()}}async function rb(e,t,r){let i=[...new Map(e.map(a=>[ce.resolve(a.locksDir),a])).values()].sort((a,o)=>ce.resolve(a.locksDir).localeCompare(ce.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?xl(o,t,()=>n(a+1)):r()};return n(0)}async function Rl(e,t,r){return xl(e,`acquire ${t}`,async()=>{let i=await G(e.runtimeDir,e.locksDir);await kt.mkdir(i,{recursive:!0});let n=await G(e.runtimeDir,ce.join(i,VI(t))),a=await Zy(r),o=await eb(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Cl(e){await St(e.file)&&await xl({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ce.basename(e.file)}`,async()=>{let t=await St(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!jo(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ce.join(e.locksDir,jh);await El(t,r)})}function QI(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function ib(e){return Oh(await St(e))}async function nb(e,t,r,i={}){return xl(e,`take over ${ce.basename(t)}`,async()=>{let n=await G(e.runtimeDir,e.locksDir),a=await G(e.runtimeDir,t);if(ce.resolve(ce.dirname(a))!==ce.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await St(a),s=await Oh(o);if(s.status==="missing")return{status:"missing"};if(r&&!zI(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&QI(o?.owner??null)>=MI;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=ce.join(n,jh);return await El(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Uy,jh,FI,MI,Ky,kl,Oo=T(()=>{"use strict";co();_o();ie();Jt();Uy=16*1024,jh=".coordinator",FI=5e3,MI=900*1e3,Ky=new qI,kl=new Map});import{createHash as ZI}from"node:crypto";function Fi(e){return e.replaceAll(`\r
|
|
179
192
|
`,`
|
|
180
193
|
`).replaceAll("\r",`
|
|
181
|
-
`)}function
|
|
182
|
-
`),i=
|
|
194
|
+
`)}function Mn(e){return ZI("sha256").update(Fi(e)).digest("hex")}function qh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z(`${t} must be an object`);return e}function ub(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new z(`${r} has unknown field(s): ${i.join(", ")}`)}function Fh(e,t){if(typeof e!="string"||e.trim().length===0)throw new z(`${t} must be a non-empty string`);return e.trim()}function ob(e,t){if(e!==void 0){if(typeof e!="string")throw new z(`${t} must be text`);return Fi(e).replace(/^\n+|\n+$/gu,"")}}function Pl(e,t){let r=Fh(e,t).toLowerCase();if(!tT.test(r))throw new z(`${t} must be a SHA-256 hash`);return r}function sb(e,t,r){let i=qh(e,t),n=Object.entries(i);if(n.length>ab)throw new z(`${t} must contain at most ${ab} entries`);let a={};for(let[o,s]of n){if(Bh(o,`${t} ID`)!==o)throw new z(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=Pl(s,`${t}.${o}`)}return a}function Bh(e,t){let r=Fh(e,t);if(!lb.test(r))throw new z(`${t} is not a valid stable requirement ID`);return r}function rT(e,t){let r=Fh(e,t);if(!eT.test(r))throw new z(`${t} is not a valid capability ID`);return r}function iT(e,t){let r=`Native delta operations[${t}]`,i=qh(e,r);ub(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Bh(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new z(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Bh(i.to_id,`${r}.to_id`),c=ob(i.title,`${r}.title`),l=ob(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:Pl(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new z(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new z(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new z(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new z(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function nT(e){let t=qh(e,"Native delta");if(ub(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Hh)throw new z(`Native delta schema must be ${Hh}`);let r=rT(t.capability,"Native delta capability"),i=Pl(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new z("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:Pl(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=sb(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:sb(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new z("Native delta operations must be an array");let s=t.operations.map(iT),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let p of d){if(c.has(p))throw new z(`Native delta operations contain duplicate or overlapping requirement ID ${p} at ${l}`);c.add(p)}}if(o!==void 0){if(a===void 0)throw new z("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new z(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new z(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:Hh,capability:r,base_hash:i,base_version:Number(t.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function aT(e){let t=(0,Lh.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new z(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Ho(e){return nT(typeof e=="string"?aT(e):e)}function oT(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function sT(e){let t=[],r=null;for(let[i,n]of e.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(n);if(!o)continue;let s=o[3];if(!lb.test(s))throw new z(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function qi(e){let t=Fi(e),r=t.split(`
|
|
195
|
+
`),i=sT(r),n=[],a=new Set;for(let l of i){if(a.has(l.id))throw new z(`Native total Spec contains duplicate requirement ID ${l.id}`);a.add(l.id);let u=r.length;for(let d=l.line+1;d<r.length;d+=1){if(i.some(h=>h.line===d)){u=d;break}let p=oT(r[d]);if(p!==null&&p<=l.level){u=d;break}}n.push({start:l.line,end:u,marker:l})}let o=new Map;for(let l of n){let u=`${r.slice(l.start,l.end).join(`
|
|
183
196
|
`)}${l.end<r.length?`
|
|
184
|
-
`:""}`,
|
|
185
|
-
`).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:
|
|
197
|
+
`:""}`,d=r.slice(l.start+1,l.end).join(`
|
|
198
|
+
`).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:d,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of n)s.push(r.slice(c,l.start).join(`
|
|
186
199
|
`)),c=l.end;return s.push(r.slice(c).join(`
|
|
187
200
|
`)),{text:t,lines:r,requirements:o,legacyText:s.join(`
|
|
188
|
-
`)}}function
|
|
201
|
+
`)}}function Mh(e){return Mn(e)}function Sr(e){return Mn(e)}function db(e){let t=qi(e).legacyText;return Mn(t.split(`
|
|
189
202
|
`).filter(r=>r.trim().length>0).join(`
|
|
190
|
-
`).trim())}function
|
|
203
|
+
`).trim())}function pb(e,t){let r=qi(e),i=[];for(let n of t.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new z(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
|
|
191
204
|
|
|
192
205
|
`)}
|
|
193
|
-
`}function
|
|
206
|
+
`}function _l(e,t,r,i){let n=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,a=Fi(i).replace(/\n+$/u,"");return[n,"",...a.split(`
|
|
194
207
|
`),"",""].join(`
|
|
195
|
-
`)}function
|
|
208
|
+
`)}function Dh(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function Al(e,t){if(e.operation==="rename"){if(!t)throw new z(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function cT(e,t,r){let i=qi(e),n=[...i.lines],a=i.requirements.get(t.id);if(!a)throw new z(`Requirement target disappeared: ${t.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
|
|
196
209
|
`)),n.join(`
|
|
197
|
-
`)}function
|
|
210
|
+
`)}function lT(e,t){let r=Fi(e),i=r.length===0||r.endsWith(`
|
|
198
211
|
|
|
199
212
|
`)?"":`
|
|
200
213
|
`,n=`${r}${i}`;return`${n.endsWith(`
|
|
201
214
|
`)||n.length===0?n:`${n}
|
|
202
|
-
`}${t}`}function
|
|
203
|
-
`)}else t=
|
|
215
|
+
`}${t}`}function hb(e,t){if(e.operation==="add"||e.operation==="modify"){let a=t.requirements.get(e.id);if(!a)return!1;let o=Al(e,e.operation==="modify"?a:void 0);return a.raw===_l(o.level,o.id,o.title,o.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),i=t.requirements.get(e.id);if(!r||i)return!1;let n=Al(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===_l(n.level,n.id,n.title,n.body)}function uT(e,t){let r=t.requirements.get(e.id);if(e.operation==="add"){if(r)throw new z(`Add target already exists: ${e.id}`);return}if(!r)throw new z(`Native delta target does not exist: ${e.id}`);if(e.expected_hash!==Mh(r.raw))throw new z(`Native delta ${e.operation} expected_hash does not match ${e.id}`);if(e.operation==="rename"&&t.requirements.has(e.to_id))throw new z(`Rename destination already exists: ${e.to_id}`)}function dT(e,t){if(e.base_requirements===void 0)return;let r=e.base_requirements,i=t.requirements;if(Object.keys(r).length!==i.size)throw new z("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==Mh(a.raw))throw new z(`Native delta base_requirements does not match requirement ${n}`)}function pT(e,t){let r=db(t.text);if(r!==Mn("")&&e.legacy_hash!==r)throw new z("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function hT(e){let t=Fi(e.baselineMarkdown),r=[],i=[];for(let a of e.delta.operations){let o=qi(t),s=o.requirements.get(a.id);if(e.allowAlreadyApplied&&hb(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:Dh(a)});continue}if(a.operation==="add"){if(s)throw new Li([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let c=Al(a,void 0);t=lT(t,_l(c.level,c.id,c.title,c.body))}else{if(!s)throw new Li([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==Mh(s.raw))throw new Li([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let c=Al(a,s);if(a.operation==="rename"&&qi(t).requirements.has(a.to_id))throw new Li([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let l=[...qi(t).lines];l.splice(s.startLine,s.endLine-s.startLine),t=l.join(`
|
|
216
|
+
`)}else t=cT(t,s,_l(c.level,c.id,c.title,c.body))}r.push(...Dh(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:Dh(a)})}let n=Fi(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:Mn(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function fb(e){let t=qi(e.baselineMarkdown);if(Mn(t.text)!==e.delta.base_hash)throw new Li([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);pT(e.delta,t),dT(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&hb(r,t)||uT(r,t);return hT({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}var Lh,Hh,cb,eT,lb,tT,ab,z,Li,Vh=T(()=>{"use strict";Lh=fr(Gt(),1),Hh="comet.native.delta.v1",cb="delta.yaml",eT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lb=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,tT=/^[a-f0-9]{64}$/iu,ab=512,z=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},Li=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var Kt,Yt,Xt,Do=T(()=>{"use strict";Kt="comet.native.v3",Yt="comet.native.v2",Xt="comet.native.v1"});import fT from"node:path";function qo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wb(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 Fo(e){if(!gb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function yb(e){if(!gb.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function bb(e,t){if(e.length===0||fT.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kT(e,t){let r=qo(e,`spec_changes[${t}]`);if(wb(r,gT,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(yb(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"&&bb(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"||!zh.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"||!zh.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 ST(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 Gh(e,t){if(wb(e,t,xr),typeof e.name!="string")throw new Error("Native change name is required");if(Fo(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"||!wT.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&&!yT.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(kT),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"||!bT.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"&&bb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!ST(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 Vn(e){let t=qo(e,xr);if(t.schema!==Xt)throw new Error(`Expected ${Xt}`);return{schema:Xt,...Gh(t,mT)}}function Lo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Wh(e,t,r){if(e===null)return null;let i=typeof e=="string"?NT.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 ET(e){if(e==null)return null;if(typeof e!="string"||!zh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function xT(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 Wn(e){let t=qo(e,xr);if(t.schema!==Yt)throw new Error(`Expected ${Yt}`);if(Lo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Yt} minimum_runtime_version must be 2`);return{schema:Yt,minimum_runtime_version:2,revision:Lo(t.revision,"Native v2 revision"),...Gh(t,vb)}}function Mi(e){let t=qo(e,xr);if(t.schema!==Kt){if(t.schema===Xt||t.schema===Yt){let o=t.schema===Xt?Vn(t):Wn(t);throw new Bo(o.name,o.schema)}throw new Qt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Lo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Qt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Lo(t.revision,"Native revision"),n=Gh(t,vT),a=ET(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Kt,minimum_runtime_version:3,revision:i,verification_protocol:xT(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Wh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Wh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Wh(t.partial_allowance,"Native partial_allowance","allowances")}}function Jh(e){let t=qo(e,xr);if(t.schema===Xt){let n=Vn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Kt}`}}if(t.schema===Yt){let n=Wn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Kt}`}}if(t.schema!==Kt){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 Qt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Lo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Qt(t.schema,r).message};let i=Mi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var mb,mT,vb,vT,gT,wT,yT,bT,xr,zh,gb,NT,Bo,Qt,Il=T(()=>{"use strict";Do();mb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],mT=new Set(mb),vb=new Set([...mb,"minimum_runtime_version","revision"]),vT=new Set([...vb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),gT=new Set(["capability","operation","source","base_hash"]),wT=new Set(["shape","build","verify","archive"]),yT=new Set(["implicit","confirmed"]),bT=new Set(["pending","pass","fail"]),xr="comet-state.yaml",zh=/^[a-f0-9]{64}$/u,gb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NT=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Bo=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"},Qt=class extends Error{constructor(r,i){super(r!==Kt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});function RT(e,t){return Uh[e][t]}function Kh(e,t){return kb[e][t]??Sb[e][t]}function Tl(e){return Eb.get(e.trim().toLocaleLowerCase("en-US"))??null}function $l(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${RT(e,i)}
|
|
204
217
|
`).join(`
|
|
205
|
-
`)}function
|
|
218
|
+
`)}function Xe(e,t,r){return e==="zh-CN"?r:t}var Uh,kb,Sb,Eb,Nb,Vi=T(()=>{"use strict";Uh={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:"验证预期"}},kb={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:"结论"}},Sb={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:"结论"}},Eb=new Map,Nb=new Map;for(let e of Object.keys(Uh)){for(let[t,r]of Object.entries(Uh[e]))Eb.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(kb[e]))Nb.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Sb[e]))Nb.set(r.toLocaleLowerCase("en-US"),t)}});function Cb(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 xb(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 Rb(e){return e.includes("-->")||e.includes("--!>")}function*jl(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
206
219
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
207
|
-
`,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=
|
|
208
|
-
`),[],i)),"Brief",i)}function
|
|
209
|
-
`),o.context,i)),o=null}};for(let{line:c,body:l}of Zc(e)){let u=l?ly(c):null,f=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let d=lo(f[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:d,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),dy(n,"Specification",i)}var RA,wL,el,tl=A(()=>{"use strict";xi();fe();RA="comet.native.acceptance.v1",wL=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),el=Object.freeze({maxCriteria:1024})});import fy from"node:path";function py(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||fy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||fy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function AA(e,t){return e.localeCompare(t,"en")}function rl(e){let t=py(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>AA(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=op(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=py(a.source,`Native spec source for ${a.capability}`);i.push(...sp(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=lo(a.text);let o=a.text;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function hy(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!_A.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function my(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var _A,il=A(()=>{"use strict";tl();_A=/^A[1-9]\d*$/u});function IA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function J(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(IA(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Fr=A(()=>{"use strict"});import TA from"node:path";function BA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function LA(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function qA(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function FA(e){return e.schema===Ft?yn(e):e.schema===qt?Nn(e):Ei(e)}function VA(e){return TA.posix.normalize(e.replaceAll("\\","/"))}function MA(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:VA(t.source)})}function WA(e){return e==="shape"?"shape":"build"}function zA(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function JA(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function vy(e){let t=FA(e.state);hy(e.acceptance);let r=WA(t.phase),i=r==="shape"?0:1,n=LA(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return B({schema:fi,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:MA(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:zA(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:J(JA(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:bc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function cp(e){let t=BA(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!jA.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==nl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!OA.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!$A.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!DA.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!HA.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:nl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:qA(t.createdAt,"Native portable migration transaction createdAt")}}function gy(e){switch(cp(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var nl,jA,$A,OA,HA,DA,lp=A(()=>{"use strict";Yc();il();ut();Fr();cn();no();nl="comet.native.portable-migration.v1",jA=new Set(["schema","id","change","fromSchema","status","createdAt"]),$A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OA=/^[a-z0-9][a-z0-9-]{7,127}$/u,HA=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),DA=new Set([Ft,qt,Lt])});import dp from"node:path";function ky(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Sy(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 up(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function yy(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function eI(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=ky(e,r);if(Sy(i,ZA,r),typeof i.capability!="string"||!by.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let o=up(i.base_hash,`${r}.base_hash`),s=yy(i.delta_content,`${r}.delta_content`),c=yy(i.source_content,`${r}.source_content`),l=up(i.expected_target_hash,`${r}.expected_target_hash`),u=up(i.result_hash,`${r}.result_hash`),f=a!==void 0;if(f&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(f&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!f&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(f){let d=io(s);if(d.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(d.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(ur(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(ur(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(d=>d==="."||d===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||ur(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function tI(e){let t=ky(e,"Native portable Archive transaction");if(Sy(t,QA,"Native portable Archive transaction"),t.schema!==wy)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!KA.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!by.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!YA.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!XA.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(eI);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:wy,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function al(e){let t=GA.exec(e);if(t)return{kind:"archive",change:t[1]};let r=UA.exec(e);return r?{kind:"migration",change:r[1]}:null}function ol(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=al(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return dp.join(e.transactionsDir,r)}async function fp(e,t){let r=al(t);if(!r)return null;let i=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=dp.join(e.transactionsDir,t);if(r.kind==="archive"){let s=tI(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=cp(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function sl(e,t){let r=ol(e,t);try{return await fp(e,dp.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Ey(e){return e.kind==="archive"||e.journal.status!=="committed"}var wy,Ny,GA,UA,KA,YA,XA,QA,ZA,by,cl=A(()=>{"use strict";nt();Zf();lp();wy="comet.native.archive-transaction.v4",Ny="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",GA=new RegExp(`^portable-archive-(${Ny})\\.json$`,"u"),UA=new RegExp(`^portable-migration-(${Ny})\\.json$`,"u"),KA=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YA=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XA=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),QA=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ZA=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),by=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as rI}from"node:crypto";import{constants as ll,promises as Et}from"node:fs";import xt from"node:path";function dl(e,t){let r=xt.relative(e,t);return r===""||!xt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xt.sep}`)}function iI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function nI(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function aI(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ul(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 pp(e,t){let r=await Et.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Et.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function oI(e,t,r){let i=xt.resolve(e),n=xt.resolve(t);if(!dl(i,n))throw new Error(`${r} is outside its managed root`);let a=[await pp(i,r)],o=i;for(let s of xt.relative(i,n).split(xt.sep).filter(Boolean)){await Ci(a,r),o=xt.join(o,s);let c=await pp(o,r);if(!dl(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ci(a,r),a}async function Ci(e,t){for(let r of e){let i=await Et.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!nI(r,i)||await Et.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function sI(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 uo(e){let t=e.maxBytes===null?null:iI(e.maxBytes),r=xt.resolve(e.file),i=await oI(e.root,xt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>pp(xt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ci(i,e.label);let a=await Et.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=aI(a),s=await Et.realpath(r);if(!dl(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>dl(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ll.O_RDONLY:ll.O_RDONLY|ll.O_NOFOLLOW|ll.O_NONBLOCK,l=await Et.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([Et.lstat(r),Et.realpath(r)]);if(await Ci(i,e.label),await Ci(n,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!ul(o,u)||!ul(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await sI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),Et.lstat(r),Et.realpath(r)]);if(await Ci(i,e.label),await Ci(n,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!ul(o,m)||!ul(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:rI("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Mt=A(()=>{"use strict";ne();Dt()});import pr from"path";import{TextDecoder as lI}from"util";function pl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hl(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 Py(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function hp(e,t){if(typeof e!="string"||e.length===0||pr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function fl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function xy(e,t){if(hp(e,t),e.includes("\\")||e!==pr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function mI(e,t){let r=pl(e,`transaction operations[${t}]`);if(hl(r,dI,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);hp(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&hp(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function _y(e){let t=pl(e,"Native Archive transaction journal");if(hl(t,fI,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Ry.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Py(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(fl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=pl(s,`Archive transaction operations[${c}]`);if(hl(l,pI,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);xy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&xy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&fl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(fl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);fl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function vI(e){let t=pl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return _y(t);if(hl(t,uI,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Ry.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Py(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(mI),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function gI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pr.join(e.transactionsDir,t)}function Ay(e,t){let r=gI(e,t);return{directory:r,journal:pr.join(r,"transaction.json"),events:pr.join(r,"events.jsonl"),staged:pr.join(r,"staged"),backups:pr.join(r,"backups")}}async function vp(e,t){let r=Ay(e,t);return await Promise.all(Object.values(r).map(i=>z(e.runtimeDir,i))),r}async function gp(e,t,r={}){let i=await vp(e,t),n=await uo({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(hI.decode(n.bytes)),o=vI(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var uI,dI,fI,pI,Ry,hI,ml=A(()=>{"use strict";ne();te();Mt();uI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),dI=new Set(["id","type","source","target","staged","backup"]),fI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),pI=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Ry=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),hI=new lI("utf-8",{fatal:!0})});import{promises as wI}from"fs";import yI from"path";async function NI(e,t,r){let i;try{i=await wI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await gp(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(al(n.name))try{let a=await fp(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ey(a))return!0}catch{return!0}return!1}async function bI(e,t){let r=Date.now()+5e3,i=yI.join(e.locksDir,"root-move.lock");for(;;)try{return await zc(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Lw(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await qw(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function _(e,t,r,i){let n=await bI(e,t);try{if(await wc(e.projectRoot),await NI(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Jc(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
|
|
210
|
-
`)}}}var
|
|
211
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function bp(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 XI(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function My(e){let t=gc(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?XI(n):void 0;if(a&&!a())return!1;let o=bp(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=bp(r,c,a),o===null||o.size===0)return!1}return bp(r,o,a)?.has(r.length)??!1}}function QI(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>gc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>gc(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=YI(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(My),excludeMatchers:r.map(My),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 ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function En(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Gt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Jy(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=Vy.posix.normalize(e);if(r!==e||Vy.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function ZI(e,t){let r=ht(e,`Native snapshot entry ${t}`);mt(r,VI,`Native snapshot entry ${t}`);let i=Jy(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!El.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:Gt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!UI.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function eT(e,t){let r=ht(e,`Native snapshot omission ${t}`);if(mt(r,MI,`Native snapshot omission ${t}`),!JI.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!GI.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Jy(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Gt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function tT(e){let t=ht(e,"Native snapshot omission overflow");if(mt(t,WI,"Native snapshot omission overflow"),typeof t.hash!="string"||!El.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:En(t.count,"Native snapshot omission overflow count")}}function Sn(e,t){let r=ht(e,t);if(mt(r,LI,t),typeof r.hash!="string"||!El.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=Gt(r.recordCount,`${t} recordCount`),n=Gt(r.storedRecordCount,`${t} storedRecordCount`),a=Gt(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 Wy(e){let t=ht(e,"Native Git selection evidence");if(mt(t,BI,"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=Sn(t.stageBefore,"Native Git selection stageBefore"),i=Sn(t.combined,"Native Git selection combined"),n=Sn(t.stageAfter,"Native Git selection stageAfter"),a=Sn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Sn(t.finalCombined,"Native Git selection finalCombined"),s=Sn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(f=>f.overflow),l=!Sl(r,n)||!Sl(n,a)||!Sl(i,o)||!Sl(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 zy(e,t){let r=ht(e,t);if(mt(r,FI,t),typeof r.hash!="string"||!El.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=Gt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Gt(r.recordCount,`${t} recordCount`),a=Gt(r.storedRecordCount,`${t} storedRecordCount`),o=Gt(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 rT(e){let t=ht(e,"Native physical selection evidence");if(mt(t,qI,"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=zy(t.before,"Native physical selection before"),i=zy(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!KI(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 kp(e){let t=ht(e,"Native content snapshot manifest");if(mt(t,jI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!zI.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let N=ht(t.capture,"Native content snapshot capture");if(mt(N,HI,"Native content snapshot capture"),N.provider!=="git"&&N.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=N.gitSelection===void 0?void 0:Wy(N.gitSelection),k=N.physicalSelection===void 0?void 0:rT(N.physicalSelection),E=null;if(N.projection!==void 0){let C=ht(N.projection,"Native content snapshot projection");if(mt(C,DI,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...C.selection===void 0?{}:{selection:Wy(C.selection)}}}if(N.provider==="git"){if(k||E)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");r=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}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=ht(t.limits,"Native content snapshot limits");mt(i,$I,"Native content snapshot limits");let n={maxFiles:En(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:En(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:En(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:En(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:En(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let N=ht(t.policy,"Native snapshot policy");if(mt(N,OI,"Native snapshot policy"),N.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(N.include)||!Array.isArray(N.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=QI({include:N.include,exclude:N.exclude,hash:N.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(ZI),s=t.omitted.map(eT),c=Gt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:tT(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(N=>N.size>n.maxFileBytes)||o.reduce((N,x)=>N+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(N=>N.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>TI||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 f=s.filter(N=>N.reason==="git-enumeration-limit"),d=s.filter(N=>N.reason==="git-selection-changed");for(let N of[...f,...d])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.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!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let g=s.filter(N=>N.reason==="physical-enumeration-limit"),v=s.filter(N=>N.reason==="physical-selection-changed");for(let N of[...g,...v])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||v.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,y=w?.status==="overflow"||w?.status==="overflow-and-changed",b=w?.status==="changed"||w?.status==="overflow-and-changed";if(y!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(v.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}:{}}}var Lq,TI,jI,$I,OI,HI,DI,BI,LI,qI,FI,VI,MI,WI,zI,JI,GI,El,UI,qq,Fq,Vq,Mq,Wq,po=A(()=>{"use strict";ne();st();Jt();Dt();te();Mt();Sa();Lq={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},TI=1e3,jI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$I=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),OI=new Set(["schema","include","exclude","hash"]),HI=new Set(["provider","gitSelection","physicalSelection","projection"]),DI=new Set(["provider","selection"]),BI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),LI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),qI=new Set(["schema","status","before","after"]),FI=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),VI=new Set(["path","hash","size","type","gitObjectId"]),MI=new Set(["path","size","type","reason"]),WI=new Set(["ref","hash","count"]),zI=new Set(["change-created","legacy-migration","explicit"]),JI=new Set(["file","directory","other"]),GI=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"]),El=/^[a-f0-9]{64}$/u,UI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,qq=64*1024,Fq=64*1024,Vq={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Mq={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};Wq=(1n<<256n)-1n});import{createHash as eN}from"node:crypto";import Gy from"path";function Re(e,t){return e<t?-1:e>t?1:0}function Ep(e){if(!Cp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cT(e,t){return e===t?0:e===null?-1:t===null?1:Re(e,t)}function Wr(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=Gy.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Gy.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function iN(e,t){return e==="."?e:Wr(e,t)}function xn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lT(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:Wr(e.path,`${t} path`),hash:e.hash,size:xn(e.size,`${t} size`),type:"file"}}function uT(e,t){return{path:iN(e.path,`${t} path`),size:e.size===null?null:xn(e.size,`${t} size`),type:e.type,reason:e.reason}}function dT(e,t){return Re(e.path,t.path)||Re(e.hash,t.hash)||e.size-t.size}function fT(e,t){return Re(e.path,t.path)||Re(e.reason,t.reason)||Re(e.type,t.type)||(e.size??-1)-(t.size??-1)}function vo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
212
|
-
`,"utf8")}function
|
|
213
|
-
${
|
|
214
|
-
`),e.omissionOverflow&&
|
|
215
|
-
`);let r=0;nN(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Mr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)go(o,n.path)&&(a+=1,Mr(t,"change-attribution",o));Mr(t,"change-end",{attributionCount:a}),a===0&&Mr(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&&Mr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function ST(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=NT(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),k=new Set(o.changePaths),E=r.externalDrift.paths.filter(C=>!k.has(C)||n.some(H=>go(H,C)));if(E.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${E.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=T(ho,e),c=T(ho,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,k]of[["baseline",e],["current",t]])for(let E of k.omitted){if(l.length>=sT)break;l.push(hr({kind:"snapshot-omission",source:x,path:E.path,evidence:{reason:E.reason,size:E.size,type:E.type}},`${x} snapshot omitted ${E.path}: ${E.reason}`))}let f=e.omitted.length+t.omitted.length,d=[...Ky("baseline",e),...Ky("current",t),...o.totalChanges===0&&a===null?[hr({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 x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(k=>x.has(k)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(k=>!x.has(k))}},m=x=>{let k=o.candidates.slice(0,x.detailedChangeCount),E=k.filter(Ce=>Ce.attributedTo.length===0&&!u.has(Ce.path)),C=o.totalChanges-k.length,H=o.totalUnattributed-E.length,P=f-x.detailedOmissionCount,W=H+P,ue=[...E.map(Ce=>hr({kind:"unattributed-change",source:"implementation-scope",path:Ce.path,evidence:{after:Ce.after,before:Ce.before,changeKind:Ce.kind}},`Changed path is not covered by a declared artifact: ${Ce.path}`)),...l.slice(0,x.detailedOmissionCount),...d,...W>0?[sN(x.overflowHash,{changes:C,unattributed:H,unresolved:W})]:[]],$t=gT(ue),ri=x.includeGitAdvisory?p():void 0;return{schema:Sp,contractHash:i,baselineProjectionRef:Ep(s),baselineProjectionHash:s,currentProjectionRef:Ep(c),currentProjectionHash:c,complete:$t.length===0,declaredArtifacts:n,changes:k,unattributed:E,unresolvedScopes:$t,noCodeReason:a,...ri?{gitAdvisory:ri}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,g=l.length,v=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let x=m({detailedChangeCount:h,detailedOmissionCount:g,includeGitAdvisory:v,overflowHash:w});if(vo({...x,scopeHash:w})<=Pi)break;if(v){v=!1;continue}if(g>0){g-=Math.max(1,Math.ceil(g/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 b=o.totalChanges>h||f>g?kT({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:g}):w,S=m({detailedChangeCount:h,detailedOmissionCount:g,includeGitAdvisory:v,overflowHash:b}),N={...S,scopeHash:T(rN,S)};if(vo(N)>Pi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return N}function Ut(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kt(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 Ri(e,t){if(typeof e!="string"||!Cp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xy(e,t,r){let i=Ep(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function xl(e,t){let r=Ut(e,"Native snapshot projection");if(Kt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==tN)throw new Error("Native snapshot projection schema is invalid");let i=kp({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=hT(i);if(T(ho,r)!==T(ho,n))throw new Error("Native snapshot projection is not canonical");let a=T(ho,n);if(t!==void 0&&Ri(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Rp(e,t){let r=Ut(e,`Declared artifact ${t}`);if(Kt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Wr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Qy(e,t){if(e===null)return null;let r=Ut(e,t);return Kt(r,["hash","size"],[],t),{hash:Ri(r.hash,`${t} hash`),size:xn(r.size,`${t} size`)}}function Zy(e,t){let r=Ut(e,`Implementation change ${t}`);if(Kt(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(Rp),n=Cl(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Qy(r.before,`Implementation change ${t} before`),o=Qy(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:Wr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function xT(e,t){let r=Ut(e,`Unresolved scope ${t}`);Kt(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"?iN(r.path,`Unresolved scope ${t} path`):Wr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function mo(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)=>Wr(n,`${t} ${a}`)),i=[...new Set(r)].sort(Re);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function cN(e){let t=Ut(e,"Native implementation external drift");if(Kt(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=mo(t.paths,"Native external drift paths");return oN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Rl(e){let t=Ut(e,"Native implementation scope"),r=[...ET].filter(E=>E!=="gitAdvisory"&&E!=="externalDrift");if(Kt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Sp)throw new Error("Native implementation scope schema is invalid");let i=Ri(t.contractHash,"Implementation scope contractHash"),n=Ri(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Xy(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ri(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Xy(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(Rp);if(JSON.stringify(c)!==JSON.stringify(Cl(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Zy),u=[...l].sort((E,C)=>Re(E.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(E=>E.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(E=>`${E.kind}:${E.path}`));if(l.some(E=>E.attributedTo.some(C=>!f.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(E=>JSON.stringify(E.attributedTo)!==JSON.stringify(c.filter(C=>go(C,E.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(Zy),p=t.externalDrift===void 0?void 0:cN(t.externalDrift),m=new Set(p?.paths??[]),h=l.filter(E=>E.attributedTo.length===0&&!m.has(E.path));if(JSON.stringify(d)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let g=t.unresolvedScopes.map(xT),v=g.filter(E=>E.kind==="scope-detail-overflow");if(v.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=v[0]===void 0?null:bT(v[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,b=[...h.map(E=>hr({kind:"unattributed-change",source:"implementation-scope",path:E.path,evidence:{after:E.after,before:E.before,changeKind:E.kind}},`Changed path is not covered by a declared artifact: ${E.path}`)),...l.length+(w?.changes??0)===0&&y===null?[hr({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")]:[]],S=g.filter(E=>E.kind==="unattributed-change"||E.kind==="missing-no-code-reason");if(JSON.stringify(g)!==JSON.stringify([...g].sort(xp))||new Set(g.map(E=>E.id)).size!==g.length||JSON.stringify(S)!==JSON.stringify(b.sort(xp))||t.complete!==(g.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 N;if(t.gitAdvisory!==void 0){let E=Ut(t.gitAdvisory,"Implementation scope Git advisory");if(Kt(E,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),E.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=mo(E.changedPaths,"Git changed paths"),H=mo(E.pathsPresentInSnapshotChanges,"Git present paths"),P=mo(E.pathsAbsentFromSnapshotChanges,"Git absent paths"),W=[...H,...P].sort(Re);if(JSON.stringify(W)!==JSON.stringify(C)||P.some(ue=>l.some($t=>$t.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:H,pathsAbsentFromSnapshotChanges:P}}let x={schema:Sp,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:g,noCodeReason:y,...N?{gitAdvisory:N}:{},...p?{externalDrift:p}:{}},k=Ri(t.scopeHash,"Implementation scope scopeHash");if(T(rN,x)!==k)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:k}}function CT(e){let t=Ut(e,"Native implementation scope authority");if(Kt(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(Rp);if(JSON.stringify(r)!==JSON.stringify(Cl(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=mo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:cN(t.externalDrift),a=yT({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 wo(e){let t=Ut(e,"Native implementation scope bundle");Kt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=CT(t.authority),i=xl(t.baseline),n=xl(t.current),a=Rl(t.scope),o=ST(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function lN(e){let t=Rl(e.scope);return wo({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 Sp,tN,ho,rN,iT,nT,aT,Cp,Pi,oT,sT,ET,Cn=A(()=>{"use strict";fe();po();Sp="comet.native.implementation-scope.v2",tN="comet.native.content-snapshot-projection.v1",ho="comet.native.content-snapshot-projection.v1",rN="comet.native.implementation-scope.v2",iT="comet.native.unresolved-scope-id.v1",nT="comet.native.scope-detail-overflow.v1",aT="comet.native.snapshot-projection-overflow.v2",Cp=/^[a-f0-9]{64}$/u,Pi=1024*1024,oT=128,sT=128;ET=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import uN from"node:path";function mr(e,t){if(!fN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function pN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function hN(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 Pp(e,t,r=2e3){let i=Me(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function yo(e,t){let r=uN.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})||uN.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 AT(e,t,r){let i=yo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Xi(i),a=i.toLowerCase(),o=r?yo(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 _p(e){let t=yo(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 Rn(e,t){return e<t?-1:e>t?1:0}function Pl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _l(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 dN(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 IT(e){let t=Pl(e,"Native acceptance trace");if(_l(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=yo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Pl(o,`Native acceptance trace entry ${s}`);if(_l(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(f=>typeof f!="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(f=>_p(f)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Rn))||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:yo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Pp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Rn(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=mr(t.traceHash,"Native acceptance trace hash");if(T(RT,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function vN(e){let t=Pl(e,"Native partial allowance");if(_l(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(Rn))||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:hN(t.change),scopeHash:mr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Pp(t.reason,"Partial allowance reason"),confirmedSummary:Pp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:pN(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=mr(t.allowanceHash,"Native partial allowance hash");if(T(PT,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Ap(e){let t=Pl(e,"Native verification evidence");if(_l(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=mr(t.implementationScopeHash,"Native verification implementation scope hash"),i=IT(t.acceptanceTrace),n=mr(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:mr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>_p(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Rn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(d=>d.evidenceRefs))].sort(Rn);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(d=>_p(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Rn)))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:hN(t.change),sourceRevision:pN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:mr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:dN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:AT(t.reportRef,"Native verification report ref"),reportHash:mr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:dN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:mN(t.createdAt,"Native verification timestamp")},f=mr(t.envelopeHash,"Native verification envelope hash");if(T(_T,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}var fN,RT,PT,_T,Al=A(()=>{"use strict";fe();qr();Sa();Cn();fN=/^[a-f0-9]{64}$/u,RT="comet.native.acceptance-trace.v2",PT="comet.native.partial-allowance.v1",_T="comet.native.verification-evidence.v2"});var Il,TT,jT,$T,nF,OT,aF,Ip=A(()=>{"use strict";fe();Il="scoped-text-safety",TT=1,jT=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),$T="comet.native.checker-policy.v1",nF=T($T,{policy:Il,version:TT,limits:jT,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),OT=["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"],aF=new Set(OT)});function Pn(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 vr(e,t){if(typeof e!="string"||!DT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Rt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Me(e).trim();if(!r||r.length>FT||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Tp(e,t){let r=Rt(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 No(e,t,r=Rt,i=!1,n=VT){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 WT(e,t){if(typeof e!="string"||!BT.test(e))throw new Error(`${t} is invalid`);return e}function zT(e){let t=Pn(e,"Native verification receipt bindings");if(zr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!LT.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:vr(t.contractHash,"Native verification receipt contract hash"),scopeHash:vr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:vr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:vr(t.artifactHash,"Native verification receipt artifact hash")}}function JT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=qT.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function GT(e,t,r,i){let n=Pn(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=Tp(n.startedAt,"Native automated-check start time"),o=Tp(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=Pn(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=Pn(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:Rt(n.executable,"Native automated-check executable"),args:No(n.args,"Native automated-check arguments",Rt,!0),cwd:Rt(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:Rt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:vr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:vr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:vr(n.outputHash,"Native automated-check output hash"),outputSummary:Rt(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=JT(n.checkReceiptRef);if(vr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:No(n.subjects,"Native static inspection subjects",Rt,i==="required-check"),rule:Rt(n.rule,"Native static inspection rule"),resultSummary:Rt(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:No(n.steps,"Native manual evidence steps"),observations:No(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function UT(e){let t=Pn(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=Rt(t.actor,"Native verification receipt actor"),o=No(t.acceptanceIds,"Native receipt acceptance IDs",WT,i==="required-check",MT).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:jp,kind:r,role:i,status:n,bindings:zT(t.bindings),acceptanceIds:o,actor:a,issuedAt:Tp(t.issuedAt,"Native verification receipt issue time"),evidence:GT(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Il||s.actor!==`native-runtime:${Il}`))throw new Error("Native required check policy identity is invalid");return s}function $p(e){let t=Pn(e,"Native verification receipt");if(zr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==jp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=UT(i),a=vr(t.receiptHash,"Native verification receipt hash");if(T(HT,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var jp,HT,DT,BT,LT,qT,FT,VT,MT,Tl=A(()=>{"use strict";fe();Ip();qr();jp="comet.native.verification-receipt.v3",HT=jp,DT=/^[a-f0-9]{64}$/u,BT=/^acceptance-[a-f0-9]{64}$/u,LT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,FT=4096,VT=256,MT=1024});var RN={};du(RN,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>Yt,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>KT,listNativeVerificationReceiptRefs:()=>xN,nativeEvidenceRef:()=>Jr,nativeReportEvidenceRef:()=>ZT,readArchivedNativeVerificationAcceptanceCounts:()=>oj,readNativeImplementationScope:()=>Eo,readNativeImplementationScopeBundle:()=>$l,readNativePartialAllowance:()=>Lp,readNativeVerificationEvidence:()=>qp,readNativeVerificationReceipt:()=>Ol,readNativeVerificationReportSnapshot:()=>So,removeNativeVerificationReportSnapshot:()=>kN,writeNativeImplementationScope:()=>nj,writeNativePartialAllowance:()=>aj,writeNativeVerificationEvidence:()=>CN,writeNativeVerificationReceipt:()=>EN,writeNativeVerificationReportSnapshot:()=>ko});import{createHash as NN}from"node:crypto";import{promises as Te}from"node:fs";import Pt from"node:path";function Op(e,t){let r=Pt.relative(e,t);return r===""||!Pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pt.sep}`)}function YT(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function bo(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wt(r,i)?Z(r,i):Z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function gN(e){let t=await Te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function XT(e,t){let r=Pt.resolve(e),i=Pt.resolve(t);if(!Op(r,i))throw new Error("Native evidence path is outside its change");let n=[await gN(r)],a=r;for(let o of Pt.relative(r,i).split(Pt.sep).filter(Boolean)){a=Pt.join(a,o);let s=await gN(a);if(!Op(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function wN(e){for(let t of e){let r=await Te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!YT(t,r)||await Te.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function QT(e,t,r={}){let i=await XT(t,Pt.dirname(e));await r.afterParentChainCaptured?.();let n=await Te.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Te.realpath(e);if(!Op(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Te.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Te.lstat(e),Te.realpath(e)]);if(await wN(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!bo(s,n)||!bo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`);await r.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let g=Yt+1-f,v=await o.read(d,0,Math.min(d.length,g),null);if(v.bytesRead===0)break;if(f+=v.bytesRead,f>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`);u.push(Buffer.from(d.subarray(0,v.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Te.lstat(e),Te.realpath(e)]);if(await wN(i),!m.isFile()||m.isSymbolicLink()||h!==a||!bo(s,p)||!bo(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function Jr(e,t){if(!bN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function ZT(e){return Jr("reports",e)}async function ko(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Yt||NN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ai({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function kN(e){let t=Hp(e.paths,e.name,"reports",e.hash),r=qe(e.paths,t);await z(r,t);let i=await Te.lstat(t);if(await So(e.paths,e.name,e.hash),await z(r,t),!bo(i,await Te.lstat(t)))throw new Error("Native report evidence changed before rollback");await Te.unlink(t)}async function So(e,t,r,i,n){if(!bN.test(r))throw new Error("Native report evidence hash is invalid");let a=await Xt({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"||NN("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 _i(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 Hp(e,t,r,i,n){let a=Jr(r,i);return n?Pt.join(n,...a.split("/")):wf(ot(e,t),a)}async function Xt(e){let t=Hp(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??qe(e.paths,t);return await z(r,t),QT(t,r,e.hooks)}async function Ai(e){jl(e.value);let t=Hp(e.paths,e.name,e.kind,e.hash),r=qe(e.paths,t);await z(r,t);try{let n=await Xt(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Jr(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await we(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Xt(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Jr(e.kind,e.hash)}function jl(e){if(ej(e)>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`)}function ej(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
216
|
-
`,"utf8")}function yN(e,t){return xl(e,t)}function tj(e,t){let r=Rl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function SN(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 Dp(e,t,r){let i=Ap(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function rj(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function ij(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,u=typeof s=="number"?s:Number.NaN,f=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(f)||l<0||u<0||f<0||u+f>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:f}}async function Bp(e,t,r,i=!1,n){let a=await Eo(e,t,r.implementationScopeRef,void 0,n);if(i&&await So(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 Lp(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 nj(e){let t=wo(e.bundle),{baseline:r,current:i,scope:n}=t;return jl(r),jl(i),jl(n),await Ai({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await Ai({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),Ai({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function $l(e,t,r,i,n){let a=_i(r,"scopes"),o=tj(await Xt({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=_i(o.baselineProjectionRef,"snapshots"),c=_i(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Xt({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(f=>yN(f,s)),Xt({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(f=>yN(f,c))]);return lN({baseline:l,current:u,scope:o})}async function Eo(e,t,r,i,n){return(await $l(e,t,r,i,n)).scope}async function aj(e){let t=SN(e.allowance,e.name,e.allowance.allowanceHash),r=await Eo(e.paths,e.name,Jr("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return Ai({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function Lp(e,t,r,i,n){let a=_i(r,"allowances");return SN(await Xt({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function EN(e){let t=$p(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return Ai({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function Ol(e,t,r,i,n){let a=_i(r,"receipts"),o=$p(await Xt({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 xN(e,t){let r=Pt.join(ot(e,t),"evidence","receipts");await z(qe(e,r),r);let i;try{i=await Te.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>Jr("receipts",n))}async function CN(e){let t=Dp(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await Bp(e.paths,e.name,t,!0),Ai({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function qp(e,t,r,i,n){let a=_i(r,"verifications"),o=Dp(await Xt({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Bp(e,t,o,!1,n),o}async function oj(e,t,r,i){let n=_i(r,"verifications"),a=await Xt({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=ij(a,t,n);if(o)return o;let s=Dp(a,t,n);return await Bp(e,t,s,!1,i),rj(s.acceptanceTrace)}var bN,Yt,KT,Gr=A(()=>{"use strict";ne();te();Dt();Cn();Al();Tl();bN=/^[a-f0-9]{64}$/u,Yt=Pi,KT=3*Yt});var _N={};du(_N,{executeNativeSupervisorChecks:()=>Mp,readNativeSupervisorCheckEvidence:()=>_n});import{createHash as sj,randomUUID as cj}from"node:crypto";import{promises as PN}from"node:fs";import Vp from"node:path";function Co(e){return sj("sha256").update(e).digest("hex")}function Fp(e,t){if(I(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||I(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!zt(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function xo(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function lj(e,t){return Promise.all(t.map(async r=>{let i=gl(r),n=await z(e,Vp.resolve(e,...i.logRef.split(/[\\/]/u))),a=await PN.readFile(n,"utf8"),o=Me(a);return{...i,logContent:o.slice(0,128*1024),logDigest:Co(o)}}))}function uj(e,t){return typeof e.logContent=="string"&&typeof e.logDigest=="string"&&e.logDigest.length>0&&t.status===e.status&&t.id===e.id&&t.name===e.name&&JSON.stringify(t.argvDisplay)===JSON.stringify(e.argvDisplay)&&t.cwdRef===e.cwdRef&&t.exitCode===e.exitCode&&t.signal===e.signal&&t.timedOut===e.timedOut&&t.durationMs===e.durationMs&&t.startedAt===e.startedAt&&t.completedAt===e.completedAt&&t.repeatable===e.repeatable&&t.logRef===e.logRef}async function dj(e){try{let t=pe(e.paths,e.parent);return(await Promise.all(e.checks.map(async i=>{if(typeof i.logContent!="string"||typeof i.logDigest!="string")return!1;let n=await z(t,Vp.resolve(t,...i.logRef.split(/[\\/]/u))),a=Me(await PN.readFile(n,"utf8"));return Co(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function fj(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function pj(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}async function Mp(e){if(e.plans.length===0||new Set(e.plans.map(({id:l})=>l)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:l})=>!l))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:l,content:u})=>!l.trim()||Buffer.byteLength(u)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=fj(e.retryCheckIds),r=await _(e.paths,"reserve Supervisor checks",async()=>{let l=await O(e.paths,e.parent),u=xo(l,e.child,e.runId);Fp(e.parent,u),Ye(u.projectRoot,e.plans);let f=yl(),d=await wl({kind:"child",parent:e.parent,child:e.child,runId:e.runId,projectRoot:u.projectRoot,candidateCommit:u.baseCommit,contractHash:u.contractHash??null,plans:e.plans,materials:e.materials}),p=T("comet.native.supervisor-check-plan.v2",{machineId:f,inputFingerprint:d}),m=u.checkExecution;if(m?.status==="running"){let w=await mn(m.ownerPid,m.ownerIdentity),y=Date.parse(m.expiresAt??"")||Date.parse(m.startedAt)+3e4;if(w){if(!(Date.now()<y))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(m.key!==p)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let b=m.activeProcess;if(b===void 0||b?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${Vp.join(pe(e.paths,e.parent),"logs","checks")} for operation ${m.operationId}; stop any remaining check process in ${u.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${u.runId}, and dispatch a new Verifier for the preserved candidate.`);if(b&&await mn(b.pid,b.identity)){if(!(Date.now()<y))throw new Error(`Native Supervisor check ${b.checkId} is still running as PID ${b.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(u),execute:!1}}if(m.checkStates?.length&&m.checkStates.every(({status:N})=>N==="passed"||N==="failed")&&m.receiptRef){m.status="completed";try{return await _n({...e,task:u,receiptRef:m.receiptRef}),l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!1,key:m.key}}catch{m.status="interrupted"}}m.status="interrupted";for(let N of m.checkStates??[])(N.status==="planned"||N.status==="running")&&(N.status="interrupted")}let h=m?.key===p&&m.machineId===f&&m.inputFingerprint===d;if(t){if(!h||m?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");pj(m.checkStates,e.plans,t)}else if(m?.status==="interrupted"&&h)return{task:structuredClone(u),execute:!1,key:p};if(m?.status==="completed"&&h&&m.receiptRef)try{return await _n({...e,task:u,receiptRef:m.receiptRef}),{task:structuredClone(u),execute:!1,key:p}}catch{}let g=t&&m?.checkStates?m.checkStates.map(w=>t.has(w.id)?{...w,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...w}):e.plans.map(bn),v=e.plans.map(w=>g.find(y=>y.id===w.id)??bn(w));return u.checkExecution={operationId:cj(),key:p,status:"running",ownerPid:process.pid,ownerIdentity:await Ke(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,y)=>w+y.timeoutMs,0)+3e4).toISOString(),machineId:f,inputFingerprint:d,checkStates:v},u.checksReason="running",l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!0,key:p,plansToExecute:e.plans.filter(w=>!t||t.has(w.id))}}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.status==="completed"&&i.checkExecution.receiptRef&&await _n({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":i.checkExecution.status==="interrupted"?"interrupted":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=pe(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await _(e.paths,"register Supervisor check process",async()=>{let u=await O(e.paths,e.parent),f=xo(u,e.child,e.runId);if(f.checkExecution?.operationId!==n||f.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let d=f.checkExecution.checkStates?.find(({id:p})=>p===l.checkId);if(!d||d.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);d.status="running",d.executionCount+=1,d.startedAt=new Date().toISOString(),d.completedAt=null,d.logRef=null}f.checkExecution.activeProcess=l,u.stateVersion+=1,await q(e.paths,u)})},c=async l=>_(e.paths,"record Supervisor check result",async()=>{let u=await O(e.paths,e.parent),f=xo(u,e.child,e.runId);if(f.checkExecution?.operationId!==n||f.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let d=f.checkExecution.checkStates?.find(({id:p})=>p===l.id);if(!d)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(d,vl(d,l)),f.checkExecution.activeProcess=null,u.stateVersion+=1,await q(e.paths,u)});try{for(let g of o){await s({status:"starting",checkId:g.id});let v=await Ni({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:g,onSpawn:async({pid:w})=>{await s({status:"running",checkId:g.id,pid:w,identity:await Ke(w)??void 0})}});if(await c(v),v.status==="interrupted")throw new Error(`Native Supervisor check ${v.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await O(e.paths,e.parent),u=xo(l,e.child,e.runId);Fp(e.parent,u);let f=u.checkExecution?.checkStates;if(!f||f.some(({status:g})=>!["passed","failed"].includes(g)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let d=await lj(a,f),p={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:r.key,machineId:u.checkExecution.machineId,inputFingerprint:u.checkExecution.inputFingerprint,checks:d,materials:e.materials.map(({name:g,content:v})=>{let w=Me(v);return{name:g,content:w,hash:Co(w)}})},m=JSON.stringify(p),h=await ko({paths:e.paths,name:e.parent,hash:Co(m),text:m});return await _(e.paths,"complete Supervisor checks",async()=>{let g=await O(e.paths,e.parent),v=xo(g,e.child,e.runId);if(v.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Fp(e.parent,v),v.checkExecution.status="completed",v.checkExecution.receiptRef=h,v.checkExecution.activeProcess=null,v.checksReason="completed",g.stateVersion+=1,await q(e.paths,g)}),{status:"completed",operationId:n,receiptRef:h}}catch(l){throw await _(e.paths,"interrupt Supervisor checks",async()=>{let u=await O(e.paths,e.parent),f=u?.children.find(({name:d})=>d===e.child)?.task;if(f?.runId===e.runId&&f.checkExecution?.operationId===n){f.checkExecution.status="interrupted",f.checkExecution.activeProcess=null;for(let d of f.checkExecution.checkStates??[])(d.status==="planned"||d.status==="running")&&(d.status="interrupted");f.checksReason="not-run",u.stateVersion+=1,await q(e.paths,u)}}),l}}async function _n(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await So(e.paths,e.parent,t[1])),i=e.task,n=i.checkExecution?.checkStates,a=n!==void 0&&Array.isArray(r.checks)&&r.checks.length===n.length&&r.checks.every((s,c)=>uj(s,n[c])),o=Array.isArray(r.checks)&&await dj({paths:e.paths,parent:e.parent,checks:r.checks});if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||r.machineId!==i.checkExecution.machineId||r.inputFingerprint!==i.checkExecution.inputFingerprint||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!a||!o||!Array.isArray(r.materials)||r.materials.some(({content:s,hash:c})=>Co(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Wp=A(()=>{"use strict";kn();rt();Xa();fe();gn();yp();Gr();le();te();qr();lr()});var $N=br(rr(),1);import{promises as Nj}from"node:fs";import _t from"node:path";import{execFileSync as wR}from"child_process";import yR from"fs";import Xs from"path";function ir(e,t){return wR("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Ki(e,t){return Ig(e)===Ig(t)}function Ig(e){let t=Xs.resolve(e);try{let r=yR.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ie(e){try{let t=Xs.resolve(ir(e,["rev-parse","--show-toplevel"])),i=ir(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Xs.resolve(i.slice(9)):t,a=null;try{a=ir(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Ki(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Qs(e){try{ir(e,["rev-parse","--is-inside-work-tree"]);let t=ir(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:Xs.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 nr(e){return Qs(e).map(t=>t.root)}function Tg(e){try{return ir(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function Yi(e,t){try{return ir(e,["check-ref-format","--branch",t]),ir(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function ar(e,t){try{let r=ir(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}rt();nt();fe();st();te();ut();Pc();Pc();gi();lr();import{randomUUID as mj}from"node:crypto";import Hl from"node:path";rt();Xa();ne();fe();gn();le();te();yp();gi();lr();kn();rt();import{promises as fo}from"node:fs";import ze from"node:path";st();kn();ro();te();var Vr=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Fy(e,t){let r=ze.relative(e,t);return r===""||!ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ze.sep}`)}function Ly(e){return JSON.stringify(e.native)}async function kl(e,t){let r=await _e(e);if(r&&t){if(Ly(r)!==Ly(t))throw new Error(`Native worktree configuration differs from the source project: ${ze.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await yc(e,t),await By(e),!0):!1}async function RI(e,t){if(!Fy(e,t))return!1;let i=`/${ze.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=ze.resolve(e,n),o=ze.join(a,"info","exclude"),s="";try{s=await fo.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await fo.mkdir(ze.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
220
|
+
`,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=xb(l,t);else if(r)Rb(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=xb(l,null);if(d!==null)t=d;else{let p=l.trimStart();if(p.startsWith("<!--")&&!Rb(p))r=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(p);h&&n.has(h[1].toLowerCase())&&!p.startsWith("</")&&!p.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(p)&&(i=h[1])}}}if(c===-1)break;o=c+1}}function Mo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Pb(e,t,r,i=[],n="content-hash"){let a=Mo(r),o=t.replaceAll("\\","/").trim(),s=i.map(Mo);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-${$(CT,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function _b(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 PT(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of jl(e)){n=s+1;let c=o?Cb(a):null;c?.level===1&&(Tl(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 Xh(e,t="brief.md",r=Ol.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=PT(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of jl(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(p===null)continue;let h=p[1].length;a=a===null?h:Math.min(a,h)}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 jl(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(),_b(o.map(l=>Pb("brief-example",t,l.join(`
|
|
221
|
+
`),[],i)),"Brief",i)}function Qh(e,t="spec.md",r=Ol.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({...Pb("spec-scenario",t,[s.title,...s.body].join(`
|
|
222
|
+
`),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of jl(e)){let d=u?Cb(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 h=Mo(p[1]);if(h.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:h,body:[],context:o.map(f=>f.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(),_b(a,"Specification",i)}var CT,Yh,Ol,Vo=T(()=>{"use strict";Vi();pe();CT="comet.native.acceptance.v1",Yh=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ol=Object.freeze({maxCriteria:1024})});import Ab from"node:path";function Ib(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Ab.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Ab.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function AT(e,t){return e.localeCompare(t,"en")}function Hl(e){let t=Ib(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((o,s)=>AT(o.capability,s.capability));if(new Set(r.map(o=>o.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Xh(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:o,text:s})=>({source:o,text:s})),n=i.length;for(let o of r){let s=Ib(o.source,`Native spec source for ${o.capability}`);for(let c of Qh(o.markdown,s,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(c.briefAcceptanceRef!==void 0){let l=Number(c.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(l)||l<0||l>=n)throw new Error(`Native Spec references unknown brief acceptance ${c.briefAcceptanceRef}: ${s}`);continue}i.push({source:s,text:c.text})}}let a=new Set;for(let o of i){o.text=Mo(o.text);let s=o.text;if(a.has(s))throw new Error(`Native acceptance contains a duplicate criterion: ${o.text}`);a.add(s)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((o,s)=>({id:`A${s+1}`,source:o.source,text:o.text}))}function Tb(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!_T.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function $b(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var _T,Dl=T(()=>{"use strict";Vo();_T=/^A[1-9]\d*$/u});function IT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function J(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(IT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var ni=T(()=>{"use strict"});import TT from"node:path";function BT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function LT(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function qT(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function FT(e){return e.schema===Xt?Vn(e):e.schema===Yt?Wn(e):Mi(e)}function MT(e){return TT.posix.normalize(e.replaceAll("\\","/"))}function VT(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:MT(t.source)})}function WT(e){return e==="shape"?"shape":"build"}function zT(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function GT(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function jb(e){let t=FT(e.state);Tb(e.acceptance);let r=WT(t.phase),i=r==="shape"?0:1,n=LT(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return B({schema:Ii,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:VT(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:zT(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:J(GT(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:nl(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Zh(e){let t=BT(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!$T.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Bl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!OT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!jT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!DT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!HT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Bl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:qT(t.createdAt,"Native portable migration transaction createdAt")}}function Ob(e){switch(Zh(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Bl,$T,jT,OT,HT,DT,ef=T(()=>{"use strict";Il();Dl();at();ni();jn();Do();Bl="comet.native.portable-migration.v1",$T=new Set(["schema","id","change","fromSchema","status","createdAt"]),jT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OT=/^[a-z0-9][a-z0-9-]{7,127}$/u,HT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),DT=new Set([Xt,Yt,Kt])});import rf from"node:path";function qb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fb(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 tf(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function Db(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function e$(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=qb(e,r);if(Fb(i,ZT,r),typeof i.capability!="string"||!Lb.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(p=>p==="."||p==="..")))throw new Error(`${r}.delta_source is invalid`);let o=tf(i.base_hash,`${r}.base_hash`),s=Db(i.delta_content,`${r}.delta_content`),c=Db(i.source_content,`${r}.source_content`),l=tf(i.expected_target_hash,`${r}.expected_target_hash`),u=tf(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let p=Ho(s);if(p.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(p.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(Sr(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Sr(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(p=>p==="."||p===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||Sr(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function t$(e){let t=qb(e,"Native portable Archive transaction");if(Fb(t,QT,"Native portable Archive transaction"),t.schema!==Hb)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!KT.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Lb.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!YT.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!XT.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(e$);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Hb,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Ll(e){let t=JT.exec(e);if(t)return{kind:"archive",change:t[1]};let r=UT.exec(e);return r?{kind:"migration",change:r[1]}:null}function ql(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Ll(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return rf.join(e.transactionsDir,r)}async function nf(e,t){let r=Ll(t);if(!r)return null;let i=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=rf.join(e.transactionsDir,t);if(r.kind==="archive"){let s=t$(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Zh(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Fl(e,t){let r=ql(e,t);try{return await nf(e,rf.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Mb(e){return e.kind==="archive"||e.journal.status!=="committed"}var Hb,Bb,JT,UT,KT,YT,XT,QT,ZT,Lb,Ml=T(()=>{"use strict";rt();Vh();ef();Hb="comet.native.archive-transaction.v4",Bb="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",JT=new RegExp(`^portable-archive-(${Bb})\\.json$`,"u"),UT=new RegExp(`^portable-migration-(${Bb})\\.json$`,"u"),KT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YT=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XT=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),QT=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ZT=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Lb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as r$}from"node:crypto";import{constants as Vl,promises as $t}from"node:fs";import jt from"node:path";function zl(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}function i$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function n$(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function a$(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wl(e,t){return te({...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 af(e,t){let r=await $t.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await $t.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function o$(e,t,r){let i=jt.resolve(e),n=jt.resolve(t);if(!zl(i,n))throw new Error(`${r} is outside its managed root`);let a=[await af(i,r)],o=i;for(let s of jt.relative(i,n).split(jt.sep).filter(Boolean)){await Wi(a,r),o=jt.join(o,s);let c=await af(o,r);if(!zl(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Wi(a,r),a}async function Wi(e,t){for(let r of e){let i=await $t.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!n$(r,i)||await $t.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function s$(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 Wo(e){let t=e.maxBytes===null?null:i$(e.maxBytes),r=jt.resolve(e.file),i=await o$(e.root,jt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>af(jt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Wi(i,e.label);let a=await $t.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=a$(a),s=await $t.realpath(r);if(!zl(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>zl(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Vl.O_RDONLY:Vl.O_RDONLY|Vl.O_NOFOLLOW|Vl.O_NONBLOCK,l=await $t.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([$t.lstat(r),$t.realpath(r)]);if(await Wi(i,e.label),await Wi(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!Wl(o,u)||!Wl(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await s$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[f,m,v]=await Promise.all([l.stat(),$t.lstat(r),$t.realpath(r)]);if(await Wi(i,e.label),await Wi(n,e.label),!m.isFile()||m.isSymbolicLink()||v!==s||!Wl(o,f)||!Wl(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:r$("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}var Zt=T(()=>{"use strict";ne();Jt()});import Rr from"path";import{TextDecoder as l$}from"util";function Jl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ul(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 Gb(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function of(e,t){if(typeof e!="string"||e.length===0||Rr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Gl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Vb(e,t){if(of(e,t),e.includes("\\")||e!==Rr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function m$(e,t){let r=Jl(e,`transaction operations[${t}]`);if(Ul(r,d$,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);of(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&of(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Jb(e){let t=Jl(e,"Native Archive transaction journal");if(Ul(t,p$,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!zb.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Gb(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Gl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Jl(s,`Archive transaction operations[${c}]`);if(Ul(l,h$,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Vb(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Vb(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Gl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Gl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Gl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function v$(e){let t=Jl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Jb(t);if(Ul(t,u$,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!zb.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Rr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Rr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Gb(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(m$),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function g$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Rr.join(e.transactionsDir,t)}function Ub(e,t){let r=g$(e,t);return{directory:r,journal:Rr.join(r,"transaction.json"),events:Rr.join(r,"events.jsonl"),staged:Rr.join(r,"staged"),backups:Rr.join(r,"backups")}}async function cf(e,t){let r=Ub(e,t);return await Promise.all(Object.values(r).map(i=>G(e.runtimeDir,i))),r}async function lf(e,t,r={}){let i=await cf(e,t),n=await Wo({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(f$.decode(n.bytes)),o=v$(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var u$,d$,p$,h$,zb,f$,Kl=T(()=>{"use strict";ne();ie();Zt();u$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),d$=new Set(["id","type","source","target","staged","backup"]),p$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),h$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),zb=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),f$=new l$("utf-8",{fatal:!0})});import{promises as w$}from"fs";import y$ from"path";async function b$(e,t,r){let i;try{i=await w$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await lf(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Ll(n.name))try{let a=await nf(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Mb(a))return!0}catch{return!0}return!1}async function N$(e,t){let r=Date.now()+5e3,i=y$.join(e.locksDir,"root-move.lock");for(;;)try{return await Rl(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await ib(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await nb(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function A(e,t,r,i){let n=await N$(e,t);try{if(await tl(e.projectRoot),await b$(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Cl(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
|
|
223
|
+
`)}}}var ve=T(()=>{"use strict";gt();Oo();Ml();Kl()});import{createHash as k$}from"node:crypto";import{promises as uf}from"node:fs";import Kb from"node:os";import Ot from"node:path";function zn(e){return{id:e.id,name:e.name,status:"planned",repeatable:e.repeatable,executionCount:0,argvDisplay:To(e.argv),cwdRef:e.cwdRef,exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}}function Yl(e,t){return{...e,name:t.name,status:t.status,argvDisplay:[...t.argvDisplay],cwdRef:t.cwdRef,exitCode:t.exitCode,signal:t.signal,timedOut:t.timedOut,durationMs:t.durationMs,startedAt:t.startedAt,completedAt:t.completedAt,logRef:t.logRef}}function Xl(e){if(e.status!=="passed"&&e.status!=="failed"&&e.status!=="interrupted"||e.startedAt===null||e.completedAt===null||e.logRef===null)throw new Error(`Native Supervisor check ${e.id} has incomplete Runtime evidence`);return{id:e.id,name:e.name,argvDisplay:[...e.argvDisplay],cwdRef:e.cwdRef,status:e.status,exitCode:e.exitCode,signal:e.signal,timedOut:e.timedOut,durationMs:e.durationMs,startedAt:e.startedAt,completedAt:e.completedAt,repeatable:e.repeatable,logRef:e.logRef}}function S$(e,t){let r=Ot.relative(Ot.resolve(e),Ot.resolve(t));return r===""||!Ot.isAbsolute(r)&&!r.startsWith(`..${Ot.sep}`)}function er(e,t){try{return I(e,t)}catch(r){return`unavailable:${r instanceof Error?r.message:String(r)}`}}async function Yb(e){let t=er(e,["ls-files","--others","--exclude-standard","-z"]);return t===null||t.startsWith("unavailable:")?[{error:t}]:Promise.all(t.split("\0").filter(Boolean).sort().map(async r=>{let i=r.replaceAll("\\","/"),n=Ot.resolve(e,...i.split("/"));if(!S$(e,n))return{path:i,error:"escaped"};try{let a=await uf.lstat(n);if(a.isSymbolicLink())return{path:i,kind:"symlink",target:await uf.readlink(n)};if(!a.isFile())return{path:i,kind:"other",size:a.size};let o=await uf.readFile(n);return{path:i,kind:"file",size:a.size,digest:k$("sha256").update(o).digest("hex")}}catch(a){return{path:i,error:a instanceof Error?a.message:String(a)}}}))}async function E$(e){let t=er(e,["ls-files","--stage","-z"]);if(t===null||t.startsWith("unavailable:"))return[{error:t}];let r=t.split("\0").map(i=>/^160000\s+[^\s]+\s+\d+\t(.+)$/u.exec(i)?.[1]).filter(i=>i!==void 0).sort();return Promise.all(r.map(async i=>({path:i.replaceAll("\\","/"),head:er(Ot.resolve(e,i),["rev-parse","HEAD"]),status:er(Ot.resolve(e,i),["status","--porcelain=v1","-z","--untracked-files=all"]),diff:er(Ot.resolve(e,i),["diff","--binary","HEAD","--submodule=diff"]),untracked:await Yb(Ot.resolve(e,i))})))}async function Ql(e){let t=Object.entries(process.env).map(([r,i])=>[r,i??null]).sort(([r],[i])=>r.localeCompare(i));return $("comet.native.supervisor-check-input.v2",{kind:e.kind,parent:e.parent,child:e.child,runId:e.runId,projectRoot:Ot.resolve(e.projectRoot),candidateCommit:e.candidateCommit,integrationCommit:e.integrationCommit??null,contractHash:e.contractHash??null,plans:e.plans,materials:e.materials,machineId:Kb.hostname(),runtime:{execPath:process.execPath,version:process.version,platform:process.platform,arch:process.arch,environment:t},git:{head:er(e.projectRoot,["rev-parse","HEAD"]),branch:er(e.projectRoot,["branch","--show-current"]),status:er(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none"]),diff:er(e.projectRoot,["diff","--binary","HEAD","--submodule=diff"]),stagedDiff:er(e.projectRoot,["diff","--cached","--binary","--submodule=diff"]),submodules:await E$(e.projectRoot),untracked:await Yb(e.projectRoot)}})}function Zl(){return Kb.hostname()}var df=T(()=>{"use strict";We();Fn();pe()});import{createHash as x$}from"node:crypto";import{lstatSync as R$,readFileSync as Xb,promises as Qb}from"node:fs";import eu from"node:path";function tN(e){try{if(I(e,["ls-files","--",tu]))return!1;let t=eu.join(e,tu),r=R$(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(Xb(Zb(e),"utf8")).hash===eN(Xb(t))}catch{return!1}}async function rN(e){let t=eu.join(e,tu),r;try{r=await Qb.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=Zb(e);await Qb.mkdir(eu.dirname(i),{recursive:!0}),await fe(i,{hash:eN(r)},{containedRoot:e})}function tr(e,t=[]){return Qa(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===tu&&tN(e))}var tu,Zb,eN,Gn=T(()=>{"use strict";We();ne();tu=".comet/config.yaml",Zb=e=>eu.join(e,".comet","runtime","native","workspace-config.json"),eN=e=>x$("sha256").update(e).digest("hex")});import{createHash as A$}from"crypto";function ut(e){return A$("sha256").update(e).digest("hex")}var rr=T(()=>{"use strict"});import oN from"path";function iu(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function K$(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 Y$(e,t){return ut(`comet.native.snapshot-policy.v1
|
|
224
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function hf(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 X$(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function sN(e){let t=el(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?X$(n):void 0;if(a&&!a())return!1;let o=hf(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=hf(r,c,a),o===null||o.size===0)return!1}return hf(r,o,a)?.has(r.length)??!1}}function Q$(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>el(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>el(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=Y$(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(sN),excludeMatchers:r.map(sN),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 Et(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Un(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ir(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function uN(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=oN.posix.normalize(e);if(r!==e||oN.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Z$(e,t){let r=Et(e,`Native snapshot entry ${t}`);xt(r,M$,`Native snapshot entry ${t}`);let i=uN(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!nu.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:ir(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!U$.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function ej(e,t){let r=Et(e,`Native snapshot omission ${t}`);if(xt(r,V$,`Native snapshot omission ${t}`),!G$.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!J$.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:uN(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:ir(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function tj(e){let t=Et(e,"Native snapshot omission overflow");if(xt(t,W$,"Native snapshot omission overflow"),typeof t.hash!="string"||!nu.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:Un(t.count,"Native snapshot omission overflow count")}}function Jn(e,t){let r=Et(e,t);if(xt(r,L$,t),typeof r.hash!="string"||!nu.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=ir(r.recordCount,`${t} recordCount`),n=ir(r.storedRecordCount,`${t} storedRecordCount`),a=ir(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 cN(e){let t=Et(e,"Native Git selection evidence");if(xt(t,B$,"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=Jn(t.stageBefore,"Native Git selection stageBefore"),i=Jn(t.combined,"Native Git selection combined"),n=Jn(t.stageAfter,"Native Git selection stageAfter"),a=Jn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Jn(t.finalCombined,"Native Git selection finalCombined"),s=Jn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!iu(r,n)||!iu(n,a)||!iu(i,o)||!iu(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 lN(e,t){let r=Et(e,t);if(xt(r,F$,t),typeof r.hash!="string"||!nu.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=ir(r.visitedNodeCount,`${t} visitedNodeCount`),n=ir(r.recordCount,`${t} recordCount`),a=ir(r.storedRecordCount,`${t} storedRecordCount`),o=ir(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 rj(e){let t=Et(e,"Native physical selection evidence");if(xt(t,q$,"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=lN(t.before,"Native physical selection before"),i=lN(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!K$(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 ff(e){let t=Et(e,"Native content snapshot manifest");if(xt(t,$$,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!z$.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let b=Et(t.capture,"Native content snapshot capture");if(xt(b,H$,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:cN(b.gitSelection),k=b.physicalSelection===void 0?void 0:rj(b.physicalSelection),S=null;if(b.projection!==void 0){let C=Et(b.projection,"Native content snapshot projection");if(xt(C,D$,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");S={provider:"git",...C.selection===void 0?{}:{selection:cN(C.selection)}}}if(b.provider==="git"){if(k||S)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&S)throw new Error("Native physical-tree capture cannot combine selection and projection");r=S?{provider:"physical-tree",projection:S}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}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");xt(i,j$,"Native content snapshot limits");let n={maxFiles:Un(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Un(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Un(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Un(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Un(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Et(t.policy,"Native snapshot policy");if(xt(b,O$,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Q$({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(Z$),s=t.omitted.map(ej),c=ir(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:tj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>T$||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(b=>b.reason==="git-enumeration-limit"),p=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...p])if(b.path!=="."||b.size!==null||b.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 h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,f=h?.status==="overflow"||h?.status==="overflow-and-changed",m=h?.status==="changed"||h?.status==="overflow-and-changed";if(f!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(b=>b.reason==="physical-enumeration-limit"),g=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...v,...g])if(b.path!=="."||b.size!==null||b.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 w=r?.physicalSelection,N=w?.status==="overflow"||w?.status==="overflow-and-changed",y=w?.status==="changed"||w?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(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}:{}}}var oV,T$,$$,j$,O$,H$,D$,B$,L$,q$,F$,M$,V$,W$,z$,G$,J$,nu,U$,sV,cV,lV,uV,dV,Go=T(()=>{"use strict";wn();ne();gt();rr();Jt();ie();Zt();Za();oV={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},T$=1e3,$$=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),j$=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),O$=new Set(["schema","include","exclude","hash"]),H$=new Set(["provider","gitSelection","physicalSelection","projection"]),D$=new Set(["provider","selection"]),B$=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),L$=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),q$=new Set(["schema","status","before","after"]),F$=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),M$=new Set(["path","hash","size","type","gitObjectId"]),V$=new Set(["path","size","type","reason"]),W$=new Set(["ref","hash","count"]),z$=new Set(["change-created","legacy-migration","explicit"]),G$=new Set(["file","directory","other"]),J$=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),nu=/^[a-f0-9]{64}$/u,U$=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,sV=64*1024,cV=64*1024,lV={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},uV={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};dV=(1n<<256n)-1n});import{createHash as wN}from"node:crypto";import dN from"path";function Te(e,t){return e<t?-1:e>t?1:0}function vf(e){if(!wf.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cj(e,t){return e===t?0:e===null?-1:t===null?1:Te(e,t)}function si(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=dN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||dN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function NN(e,t){return e==="."?e:si(e,t)}function Kn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lj(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:si(e.path,`${t} path`),hash:e.hash,size:Kn(e.size,`${t} size`),type:"file"}}function uj(e,t){return{path:NN(e.path,`${t} path`),size:e.size===null?null:Kn(e.size,`${t} size`),type:e.type,reason:e.reason}}function dj(e,t){return Te(e.path,t.path)||Te(e.hash,t.hash)||e.size-t.size}function pj(e,t){return Te(e.path,t.path)||Te(e.reason,t.reason)||Te(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ko(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
225
|
+
`,"utf8")}function oi(e,t,r){let i=`${t}
|
|
226
|
+
${Bc(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function hj(e){if(Ko(e)<=Gi)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=wN("sha256");a.update(`${aj}
|
|
227
|
+
`),e.omissionOverflow&&oi(a,"existing-overflow",e.omissionOverflow);let o=(p,h)=>{h||(i+=1),n+=1,oi(a,"omission",p)},s=p=>{i+=1,n+=1,oi(a,"entry",p)},c=()=>{for(let p=r.length-1;p>=0;p-=1){let h=r[p];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return r.splice(p,1),h}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(;Ko(u)>Gi;){if(r.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(r.length/4));for(let f=0;f<h;f+=1){let m=c();if(m===null)break;o(m,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let f of t.splice(-h))s(f)}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 fj(e){let t=ff(e),r=t.entries.map((n,a)=>lj(n,`Snapshot entry ${a}`));if(r.sort(dj),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)=>uj(n,`Snapshot omission ${a}`));return i.sort(pj),hj({schema:yN,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 ou(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:si(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)=>Te(r.path,i.path)||Te(r.kind,i.kind))}function Yo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function pN(e){return e?{hash:e.hash,size:e.size}:null}function kN(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:Te(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:pN(c),after:pN(l)})}}function mj(e,t){return{...e,attributedTo:t.filter(r=>Yo(r,e.path))}}function Cr(e,t){return{id:`scope:${$(ij,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function vj(e,t){let r=t.omitted.map(i=>Cr({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(Cr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(Cr({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 hN(e,t){return vj(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function gf(e,t){return Te(e.kind,t.kind)||Te(e.source,t.source)||cj(e.path,t.path)||Te(e.id,t.id)}function gj(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(gf)}function SN(e){return[...new Set(e.map((t,r)=>si(t,`Git path ${r}`)))].sort(Te)}function fN(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 wj(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 EN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=SN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:fN(e.baseCommit,"Native external drift base commit"),targetBranch:wj(e.targetBranch,"Native external drift target branch"),targetCommit:fN(e.targetCommit,"Native external drift target commit"),paths:t}}function yj(e){if(typeof e.contractHash!="string"||!wf.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ou(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:SN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:EN(e.externalDrift)}}}function bj(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 kN(e,t,h=>{let f=r.some(m=>Yo(m,h.path));if(d+=1,c.push(h.path),!f&&!n?.has(h.path)&&(p+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<oj){let m=mj(h,r),v=Ko(m);l+v<=Gi?(a.push(m),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:p}}function xN(e,t){return Cr({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 Nj(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:Kn(Number(t[1]),"Scope overflow change count"),unresolved:Kn(Number(t[2]),"Scope overflow unresolved count"),unattributed:Kn(Number(t[3]),"Scope overflow unattributed count")},i=zi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(xN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function kj(e){let t=wN("sha256");t.update(`${nj}
|
|
228
|
+
`);let r=0;kN(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){oi(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Yo(o,n.path)&&(a+=1,oi(t,"change-attribution",o));oi(t,"change-end",{attributionCount:a}),a===0&&oi(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&&oi(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function Sj(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=bj(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),k=new Set(o.changePaths),S=r.externalDrift.paths.filter(C=>!k.has(C)||n.some(P=>Yo(P,C)));if(S.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${S.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=$(Jo,e),c=$(Jo,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,k]of[["baseline",e],["current",t]])for(let S of k.omitted){if(l.length>=sj)break;l.push(Cr({kind:"snapshot-omission",source:x,path:S.path,evidence:{reason:S.reason,size:S.size,type:S.type}},`${x} snapshot omitted ${S.path}: ${S.reason}`))}let d=e.omitted.length+t.omitted.length,p=[...hN("baseline",e),...hN("current",t),...o.totalChanges===0&&a===null?[Cr({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")]:[]],h=()=>{if(r.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(k=>x.has(k)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(k=>!x.has(k))}},f=x=>{let k=o.candidates.slice(0,x.detailedChangeCount),S=k.filter(tt=>tt.attributedTo.length===0&&!u.has(tt.path)),C=o.totalChanges-k.length,P=o.totalUnattributed-S.length,_=d-x.detailedOmissionCount,j=P+_,ue=[...S.map(tt=>Cr({kind:"unattributed-change",source:"implementation-scope",path:tt.path,evidence:{after:tt.after,before:tt.before,changeKind:tt.kind}},`Changed path is not covered by a declared artifact: ${tt.path}`)),...l.slice(0,x.detailedOmissionCount),...p,...j>0?[xN(x.overflowHash,{changes:C,unattributed:P,unresolved:j})]:[]],de=gj(ue),Or=x.includeGitAdvisory?h():void 0;return{schema:mf,contractHash:i,baselineProjectionRef:vf(s),baselineProjectionHash:s,currentProjectionRef:vf(c),currentProjectionHash:c,complete:de.length===0,declaredArtifacts:n,changes:k,unattributed:S,unresolvedScopes:de,noCodeReason:a,...Or?{gitAdvisory:Or}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},m=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let x=f({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:w});if(Ko({...x,scopeHash:w})<=Gi)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let y=o.totalChanges>m||d>v?kj({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:v}):w,E=f({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:y}),b={...E,scopeHash:$(bN,E)};if(Ko(b)>Gi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function nr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ar(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 zi(e,t){if(typeof e!="string"||!wf.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mN(e,t,r){let i=vf(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function au(e,t){let r=nr(e,"Native snapshot projection");if(ar(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==yN)throw new Error("Native snapshot projection schema is invalid");let i=ff({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=fj(i);if($(Jo,r)!==$(Jo,n))throw new Error("Native snapshot projection is not canonical");let a=$(Jo,n);if(t!==void 0&&zi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function yf(e,t){let r=nr(e,`Declared artifact ${t}`);if(ar(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:si(r.path,`Declared artifact ${t} path`),kind:r.kind}}function vN(e,t){if(e===null)return null;let r=nr(e,t);return ar(r,["hash","size"],[],t),{hash:zi(r.hash,`${t} hash`),size:Kn(r.size,`${t} size`)}}function gN(e,t){let r=nr(e,`Implementation change ${t}`);if(ar(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(yf),n=ou(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=vN(r.before,`Implementation change ${t} before`),o=vN(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:si(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function xj(e,t){let r=nr(e,`Unresolved scope ${t}`);ar(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"?NN(r.path,`Unresolved scope ${t} path`):si(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Uo(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)=>si(n,`${t} ${a}`)),i=[...new Set(r)].sort(Te);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function RN(e){let t=nr(e,"Native implementation external drift");if(ar(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=Uo(t.paths,"Native external drift paths");return EN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function su(e){let t=nr(e,"Native implementation scope"),r=[...Ej].filter(S=>S!=="gitAdvisory"&&S!=="externalDrift");if(ar(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==mf)throw new Error("Native implementation scope schema is invalid");let i=zi(t.contractHash,"Implementation scope contractHash"),n=zi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=mN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=zi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=mN(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(yf);if(JSON.stringify(c)!==JSON.stringify(ou(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(gN),u=[...l].sort((S,C)=>Te(S.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(S=>S.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(S=>`${S.kind}:${S.path}`));if(l.some(S=>S.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(S=>JSON.stringify(S.attributedTo)!==JSON.stringify(c.filter(C=>Yo(C,S.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(gN),h=t.externalDrift===void 0?void 0:RN(t.externalDrift),f=new Set(h?.paths??[]),m=l.filter(S=>S.attributedTo.length===0&&!f.has(S.path));if(JSON.stringify(p)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(xj),g=v.filter(S=>S.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=g[0]===void 0?null:Nj(g[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,y=[...m.map(S=>Cr({kind:"unattributed-change",source:"implementation-scope",path:S.path,evidence:{after:S.after,before:S.before,changeKind:S.kind}},`Changed path is not covered by a declared artifact: ${S.path}`)),...l.length+(w?.changes??0)===0&&N===null?[Cr({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")]:[]],E=v.filter(S=>S.kind==="unattributed-change"||S.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(gf))||new Set(v.map(S=>S.id)).size!==v.length||JSON.stringify(E)!==JSON.stringify(y.sort(gf))||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 b;if(t.gitAdvisory!==void 0){let S=nr(t.gitAdvisory,"Implementation scope Git advisory");if(ar(S,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),S.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Uo(S.changedPaths,"Git changed paths"),P=Uo(S.pathsPresentInSnapshotChanges,"Git present paths"),_=Uo(S.pathsAbsentFromSnapshotChanges,"Git absent paths"),j=[...P,..._].sort(Te);if(JSON.stringify(j)!==JSON.stringify(C)||_.some(ue=>l.some(de=>de.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:P,pathsAbsentFromSnapshotChanges:_}}let x={schema:mf,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:p,unresolvedScopes:v,noCodeReason:N,...b?{gitAdvisory:b}:{},...h?{externalDrift:h}:{}},k=zi(t.scopeHash,"Implementation scope scopeHash");if($(bN,x)!==k)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:k}}function Rj(e){let t=nr(e,"Native implementation scope authority");if(ar(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(yf);if(JSON.stringify(r)!==JSON.stringify(ou(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=Uo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:RN(t.externalDrift),a=yj({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 Xo(e){let t=nr(e,"Native implementation scope bundle");ar(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=Rj(t.authority),i=au(t.baseline),n=au(t.current),a=su(t.scope),o=Sj(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 CN(e){let t=su(e.scope);return Xo({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 mf,yN,Jo,bN,ij,nj,aj,wf,Gi,oj,sj,Ej,Yn=T(()=>{"use strict";pe();Go();mf="comet.native.implementation-scope.v2",yN="comet.native.content-snapshot-projection.v1",Jo="comet.native.content-snapshot-projection.v1",bN="comet.native.implementation-scope.v2",ij="comet.native.unresolved-scope-id.v1",nj="comet.native.scope-detail-overflow.v1",aj="comet.native.snapshot-projection-overflow.v2",wf=/^[a-f0-9]{64}$/u,Gi=1024*1024,oj=128,sj=128;Ej=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import PN from"node:path";function Pr(e,t){if(!AN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function IN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function TN(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 bf(e,t,r=2e3){let i=Ye(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Qo(e,t){let r=PN.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})||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 relative ref`);return e}function Aj(e,t,r){let i=Qo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Nn(i),a=i.toLowerCase(),o=r?Qo(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 Nf(e){let t=Qo(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 Xn(e,t){return e<t?-1:e>t?1:0}function cu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function lu(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 $N(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 _N(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 Ij(e){let t=cu(e,"Native acceptance trace");if(lu(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"||!AN.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=Qo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=cu(o,`Native acceptance trace entry ${s}`);if(lu(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=>Nf(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Xn))||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:Qo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:bf(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Xn(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=Pr(t.traceHash,"Native acceptance trace hash");if($(Cj,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function jN(e){let t=cu(e,"Native partial allowance");if(lu(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(Xn))||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:TN(t.change),scopeHash:Pr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:bf(t.reason,"Partial allowance reason"),confirmedSummary:bf(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:IN(t.sourceRevision),confirmedAt:$N(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=Pr(t.allowanceHash,"Native partial allowance hash");if($(Pj,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function kf(e){let t=cu(e,"Native verification evidence");if(lu(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=Pr(t.implementationScopeHash,"Native verification implementation scope hash"),i=Ij(t.acceptanceTrace),n=Pr(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:Pr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>Nf(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Xn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(Xn);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=>Nf(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Xn)))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:TN(t.change),sourceRevision:IN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Pr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:_N(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:Aj(t.reportRef,"Native verification report ref"),reportHash:Pr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:_N(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:$N(t.createdAt,"Native verification timestamp")},d=Pr(t.envelopeHash,"Native verification envelope hash");if($(_j,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var AN,Cj,Pj,_j,uu=T(()=>{"use strict";pe();ii();Za();Yn();AN=/^[a-f0-9]{64}$/u,Cj="comet.native.acceptance-trace.v2",Pj="comet.native.partial-allowance.v1",_j="comet.native.verification-evidence.v2"});var du,Tj,$j,jj,xV,Oj,RV,Sf=T(()=>{"use strict";pe();du="scoped-text-safety",Tj=1,$j=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),jj="comet.native.checker-policy.v1",xV=$(jj,{policy:du,version:Tj,limits:$j,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Oj=["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"],RV=new Set(Oj)});function Qn(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 ci(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 _r(e,t){if(typeof e!="string"||!Dj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ht(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Ye(e).trim();if(!r||r.length>Fj||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Ef(e,t){let r=Ht(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 Zo(e,t,r=Ht,i=!1,n=Mj){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 Wj(e,t){if(typeof e!="string"||!Bj.test(e))throw new Error(`${t} is invalid`);return e}function zj(e){let t=Qn(e,"Native verification receipt bindings");if(ci(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Lj.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:_r(t.contractHash,"Native verification receipt contract hash"),scopeHash:_r(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:_r(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:_r(t.artifactHash,"Native verification receipt artifact hash")}}function Gj(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=qj.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function Jj(e,t,r,i){let n=Qn(t,`Native ${e} evidence`);if(e==="automated-check"){if(ci(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=Ef(n.startedAt,"Native automated-check start time"),o=Ef(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=Qn(n.worktree,"Native automated-check worktree");if(ci(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=Qn(n.afterFence,"Native automated-check after fence");if(ci(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:Ht(n.executable,"Native automated-check executable"),args:Zo(n.args,"Native automated-check arguments",Ht,!0),cwd:Ht(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:Ht(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:_r(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:_r(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:_r(n.outputHash,"Native automated-check output hash"),outputSummary:Ht(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){ci(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=Gj(n.checkReceiptRef);if(_r(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Zo(n.subjects,"Native static inspection subjects",Ht,i==="required-check"),rule:Ht(n.rule,"Native static inspection rule"),resultSummary:Ht(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ci(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Zo(n.steps,"Native manual evidence steps"),observations:Zo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function Uj(e){let t=Qn(e,"Native verification receipt");if(ci(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=Ht(t.actor,"Native verification receipt actor"),o=Zo(t.acceptanceIds,"Native receipt acceptance IDs",Wj,i==="required-check",Vj).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:xf,kind:r,role:i,status:n,bindings:zj(t.bindings),acceptanceIds:o,actor:a,issuedAt:Ef(t.issuedAt,"Native verification receipt issue time"),evidence:Jj(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==du||s.actor!==`native-runtime:${du}`))throw new Error("Native required check policy identity is invalid");return s}function Rf(e){let t=Qn(e,"Native verification receipt");if(ci(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==xf)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=Uj(i),a=_r(t.receiptHash,"Native verification receipt hash");if($(Hj,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var xf,Hj,Dj,Bj,Lj,qj,Fj,Mj,Vj,pu=T(()=>{"use strict";pe();Sf();ii();xf="comet.native.verification-receipt.v3",Hj=xf,Dj=/^[a-f0-9]{64}$/u,Bj=/^acceptance-[a-f0-9]{64}$/u,Lj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Fj=4096,Mj=256,Vj=1024});var zN={};Qu(zN,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>or,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>Kj,listNativeVerificationReceiptRefs:()=>VN,nativeEvidenceRef:()=>li,nativeReportEvidenceRef:()=>Zj,readArchivedNativeVerificationAcceptanceCounts:()=>o0,readNativeImplementationScope:()=>is,readNativeImplementationScopeBundle:()=>fu,readNativePartialAllowance:()=>If,readNativeVerificationEvidence:()=>Tf,readNativeVerificationReceipt:()=>mu,readNativeVerificationReportSnapshot:()=>rs,removeNativeVerificationReportSnapshot:()=>qN,writeNativeImplementationScope:()=>n0,writeNativePartialAllowance:()=>a0,writeNativeVerificationEvidence:()=>WN,writeNativeVerificationReceipt:()=>MN,writeNativeVerificationReportSnapshot:()=>ts});import{createHash as BN}from"node:crypto";import{promises as Be}from"node:fs";import Dt from"node:path";function Cf(e,t){let r=Dt.relative(e,t);return r===""||!Dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dt.sep}`)}function Yj(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function es(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Pt(r,i)?te(r,i):te(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ON(e){let t=await Be.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Be.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Xj(e,t){let r=Dt.resolve(e),i=Dt.resolve(t);if(!Cf(r,i))throw new Error("Native evidence path is outside its change");let n=[await ON(r)],a=r;for(let o of Dt.relative(r,i).split(Dt.sep).filter(Boolean)){a=Dt.join(a,o);let s=await ON(a);if(!Cf(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function HN(e){for(let t of e){let r=await Be.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Yj(t,r)||await Be.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function Qj(e,t,r={}){let i=await Xj(t,Dt.dirname(e));await r.afterParentChainCaptured?.();let n=await Be.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Be.realpath(e);if(!Cf(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Be.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Be.lstat(e),Be.realpath(e)]);if(await HN(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!es(s,n)||!es(s,c))throw new Error("Native evidence document changed while opening");if(s.size>or)throw new Error(`Native evidence document exceeds ${or} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=or+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>or)throw new Error(`Native evidence document exceeds ${or} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[h,f,m]=await Promise.all([o.stat(),Be.lstat(e),Be.realpath(e)]);if(await HN(i),!f.isFile()||f.isSymbolicLink()||m!==a||!es(s,h)||!es(s,f))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function li(e,t){if(!LN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function Zj(e){return li("reports",e)}async function ts(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>or||BN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ui({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function qN(e){let t=Pf(e.paths,e.name,"reports",e.hash),r=Ge(e.paths,t);await G(r,t);let i=await Be.lstat(t);if(await rs(e.paths,e.name,e.hash),await G(r,t),!es(i,await Be.lstat(t)))throw new Error("Native report evidence changed before rollback");await Be.unlink(t)}async function rs(e,t,r,i,n){if(!LN.test(r))throw new Error("Native report evidence hash is invalid");let a=await sr({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"||BN("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 Ji(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 Pf(e,t,r,i,n){let a=li(r,i);return n?Dt.join(n,...a.split("/")):lh(vt(e,t),a)}async function sr(e){let t=Pf(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ge(e.paths,t);return await G(r,t),Qj(t,r,e.hooks)}async function Ui(e){hu(e.value);let t=Pf(e.paths,e.name,e.kind,e.hash),r=Ge(e.paths,t);await G(r,t);try{let n=await sr(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return li(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await fe(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await sr(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return li(e.kind,e.hash)}function hu(e){if(e0(e)>or)throw new Error(`Native evidence document exceeds ${or} bytes`)}function e0(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
229
|
+
`,"utf8")}function DN(e,t){return au(e,t)}function t0(e,t){let r=su(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function FN(e,t,r){let i=jN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function _f(e,t,r){let i=kf(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function r0(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function i0(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,u=typeof s=="number"?s:Number.NaN,d=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(d)||l<0||u<0||d<0||u+d>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:d}}async function Af(e,t,r,i=!1,n){let a=await is(e,t,r.implementationScopeRef,void 0,n);if(i&&await rs(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 If(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 n0(e){let t=Xo(e.bundle),{baseline:r,current:i,scope:n}=t;return hu(r),hu(i),hu(n),await Ui({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await Ui({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),Ui({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function fu(e,t,r,i,n){let a=Ji(r,"scopes"),o=t0(await sr({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Ji(o.baselineProjectionRef,"snapshots"),c=Ji(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([sr({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>DN(d,s)),sr({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>DN(d,c))]);return CN({baseline:l,current:u,scope:o})}async function is(e,t,r,i,n){return(await fu(e,t,r,i,n)).scope}async function a0(e){let t=FN(e.allowance,e.name,e.allowance.allowanceHash),r=await is(e.paths,e.name,li("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return Ui({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function If(e,t,r,i,n){let a=Ji(r,"allowances");return FN(await sr({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function MN(e){let t=Rf(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return Ui({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function mu(e,t,r,i,n){let a=Ji(r,"receipts"),o=Rf(await sr({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function VN(e,t){let r=Dt.join(vt(e,t),"evidence","receipts");await G(Ge(e,r),r);let i;try{i=await Be.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>li("receipts",n))}async function WN(e){let t=_f(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await Af(e.paths,e.name,t,!0),Ui({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Tf(e,t,r,i,n){let a=Ji(r,"verifications"),o=_f(await sr({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Af(e,t,o,!1,n),o}async function o0(e,t,r,i){let n=Ji(r,"verifications"),a=await sr({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=i0(a,t,n);if(o)return o;let s=_f(a,t,n);return await Af(e,t,s,!1,i),r0(s.acceptanceTrace)}var LN,or,Kj,ui=T(()=>{"use strict";ne();ie();Jt();Yn();uu();pu();LN=/^[a-f0-9]{64}$/u,or=Gi,Kj=3*or});var JN={};Qu(JN,{executeNativeSupervisorChecks:()=>Of,readNativeSupervisorCheckEvidence:()=>Zn});import{createHash as s0,randomUUID as c0}from"node:crypto";import{promises as GN}from"node:fs";import jf from"node:path";function as(e){return s0("sha256").update(e).digest("hex")}function $f(e,t){if(I(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||I(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!tr(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function ns(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function l0(e,t){return Promise.all(t.map(async r=>{let i=Xl(r),n=await G(e,jf.resolve(e,...i.logRef.split(/[\\/]/u))),a=await GN.readFile(n,"utf8"),o=Ye(a);return{...i,logContent:o.slice(0,128*1024),logDigest:as(o)}}))}function u0(e,t){return typeof e.logContent=="string"&&typeof e.logDigest=="string"&&e.logDigest.length>0&&t.status===e.status&&t.id===e.id&&t.name===e.name&&JSON.stringify(t.argvDisplay)===JSON.stringify(e.argvDisplay)&&t.cwdRef===e.cwdRef&&t.exitCode===e.exitCode&&t.signal===e.signal&&t.timedOut===e.timedOut&&t.durationMs===e.durationMs&&t.startedAt===e.startedAt&&t.completedAt===e.completedAt&&t.repeatable===e.repeatable&&t.logRef===e.logRef}async function d0(e){try{let t=me(e.paths,e.parent);return(await Promise.all(e.checks.map(async i=>{if(typeof i.logContent!="string"||typeof i.logDigest!="string")return!1;let n=await G(t,jf.resolve(t,...i.logRef.split(/[\\/]/u))),a=Ye(await GN.readFile(n,"utf8"));return as(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function p0(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function h0(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}async function Of(e){if(e.plans.length===0||new Set(e.plans.map(({id:l})=>l)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:l})=>!l))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:l,content:u})=>!l.trim()||Buffer.byteLength(u)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=p0(e.retryCheckIds),r=await A(e.paths,"reserve Supervisor checks",async()=>{let l=await D(e.paths,e.parent),u=ns(l,e.child,e.runId);$f(e.parent,u),lt(u.projectRoot,e.plans);let d=Zl(),p=await Ql({kind:"child",parent:e.parent,child:e.child,runId:e.runId,projectRoot:u.projectRoot,candidateCommit:u.baseCommit,contractHash:u.contractHash??null,plans:e.plans,materials:e.materials}),h=$("comet.native.supervisor-check-plan.v2",{machineId:d,inputFingerprint:p}),f=u.checkExecution;if(f?.status==="running"){let w=await Ln(f.ownerPid,f.ownerIdentity),N=Date.parse(f.expiresAt??"")||Date.parse(f.startedAt)+3e4;if(w){if(!(Date.now()<N))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(f.key!==h)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let y=f.activeProcess;if(y===void 0||y?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${jf.join(me(e.paths,e.parent),"logs","checks")} for operation ${f.operationId}; stop any remaining check process in ${u.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${u.runId}, and dispatch a new Verifier for the preserved candidate.`);if(y&&await Ln(y.pid,y.identity)){if(!(Date.now()<N))throw new Error(`Native Supervisor check ${y.checkId} is still running as PID ${y.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(u),execute:!1}}if(f.checkStates?.length&&f.checkStates.every(({status:b})=>b==="passed"||b==="failed")&&f.receiptRef){f.status="completed";try{return await Zn({...e,task:u,receiptRef:f.receiptRef}),l.stateVersion+=1,await F(e.paths,l),{task:structuredClone(u),execute:!1,key:f.key}}catch{f.status="interrupted"}}f.status="interrupted";for(let b of f.checkStates??[])(b.status==="planned"||b.status==="running")&&(b.status="interrupted")}let m=f?.key===h&&f.machineId===d&&f.inputFingerprint===p;if(t){if(!m||f?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");h0(f.checkStates,e.plans,t)}else if(f?.status==="interrupted"&&m)return{task:structuredClone(u),execute:!1,key:h};if(f?.status==="completed"&&m&&f.receiptRef)try{return await Zn({...e,task:u,receiptRef:f.receiptRef}),{task:structuredClone(u),execute:!1,key:h}}catch{}let v=t&&f?.checkStates?f.checkStates.map(w=>t.has(w.id)?{...w,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...w}):e.plans.map(zn),g=e.plans.map(w=>v.find(N=>N.id===w.id)??zn(w));return u.checkExecution={operationId:c0(),key:h,status:"running",ownerPid:process.pid,ownerIdentity:await ct(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,N)=>w+N.timeoutMs,0)+3e4).toISOString(),machineId:d,inputFingerprint:p,checkStates:g},u.checksReason="running",l.stateVersion+=1,await F(e.paths,l),{task:structuredClone(u),execute:!0,key:h,plansToExecute:e.plans.filter(w=>!t||t.has(w.id))}}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.status==="completed"&&i.checkExecution.receiptRef&&await Zn({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":i.checkExecution.status==="interrupted"?"interrupted":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=me(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await A(e.paths,"register Supervisor check process",async()=>{let u=await D(e.paths,e.parent),d=ns(u,e.child,e.runId);if(d.checkExecution?.operationId!==n||d.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let p=d.checkExecution.checkStates?.find(({id:h})=>h===l.checkId);if(!p||p.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);p.status="running",p.executionCount+=1,p.startedAt=new Date().toISOString(),p.completedAt=null,p.logRef=null}d.checkExecution.activeProcess=l,u.stateVersion+=1,await F(e.paths,u)})},c=async l=>A(e.paths,"record Supervisor check result",async()=>{let u=await D(e.paths,e.parent),d=ns(u,e.child,e.runId);if(d.checkExecution?.operationId!==n||d.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let p=d.checkExecution.checkStates?.find(({id:h})=>h===l.id);if(!p)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(p,Yl(p,l)),d.checkExecution.activeProcess=null,u.stateVersion+=1,await F(e.paths,u)});try{for(let v of o){await s({status:"starting",checkId:v.id});let g=await Bi({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:v,onSpawn:async({pid:w})=>{await s({status:"running",checkId:v.id,pid:w,identity:await ct(w)??void 0})}});if(await c(g),g.status==="interrupted")throw new Error(`Native Supervisor check ${g.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await D(e.paths,e.parent),u=ns(l,e.child,e.runId);$f(e.parent,u);let d=u.checkExecution?.checkStates;if(!d||d.some(({status:v})=>!["passed","failed"].includes(v)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let p=await l0(a,d),h={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:r.key,machineId:u.checkExecution.machineId,inputFingerprint:u.checkExecution.inputFingerprint,checks:p,materials:e.materials.map(({name:v,content:g})=>{let w=Ye(g);return{name:v,content:w,hash:as(w)}})},f=JSON.stringify(h),m=await ts({paths:e.paths,name:e.parent,hash:as(f),text:f});return await A(e.paths,"complete Supervisor checks",async()=>{let v=await D(e.paths,e.parent),g=ns(v,e.child,e.runId);if(g.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");$f(e.parent,g),g.checkExecution.status="completed",g.checkExecution.receiptRef=m,g.checkExecution.activeProcess=null,g.checksReason="completed",v.stateVersion+=1,await F(e.paths,v)}),{status:"completed",operationId:n,receiptRef:m}}catch(l){throw await A(e.paths,"interrupt Supervisor checks",async()=>{let u=await D(e.paths,e.parent),d=u?.children.find(({name:p})=>p===e.child)?.task;if(d?.runId===e.runId&&d.checkExecution?.operationId===n){d.checkExecution.status="interrupted",d.checkExecution.activeProcess=null;for(let p of d.checkExecution.checkStates??[])(p.status==="planned"||p.status==="running")&&(p.status="interrupted");d.checksReason="not-run",u.stateVersion+=1,await F(e.paths,u)}}),l}}async function Zn(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await rs(e.paths,e.parent,t[1])),i=e.task,n=i.checkExecution?.checkStates,a=n!==void 0&&Array.isArray(r.checks)&&r.checks.length===n.length&&r.checks.every((s,c)=>u0(s,n[c])),o=Array.isArray(r.checks)&&await d0({paths:e.paths,parent:e.parent,checks:r.checks});if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||r.machineId!==i.checkExecution.machineId||r.inputFingerprint!==i.checkExecution.inputFingerprint||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!a||!o||!Array.isArray(r.materials)||r.materials.some(({content:s,hash:c})=>as(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Hf=T(()=>{"use strict";Gn();We();_o();pe();Fn();df();ui();ve();ie();ii();kr()});var QN=fr(Gt(),1);import{promises as b0}from"node:fs";import Bt from"node:path";wn();yn();import{execFileSync as R_}from"child_process";import C_ from"fs";import Ri from"path";import{AsyncLocalStorage as Gw}from"node:async_hooks";Ya();var Ci=new Gw,Jw=new Gw;function Uw(e){return Ci.getStore()?e():Ci.run(new Map,e)}function P_(e){let t=Ci.getStore();for(let r of e)t?.set(Jr(r.root),e);return e}function Ur(e,t){return Ua(()=>R_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Kr(e,t){return Jr(e)===Jr(t)}function Jr(e){let t=Ri.resolve(e);try{let r=C_.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function oe(e){try{let t=Jw.getStore()?.get(Jr(e)),r=Ci.getStore()?.get(t??Jr(e));if(r){let c=zw(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Ri.resolve(Ur(e,["rev-parse","--show-toplevel"])),n=Ci.getStore()?.get(Jr(i))??Kw(e),a=zw(i,n);if(Ci.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Ur(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Kr(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Oc(e){try{let t=Ci.getStore()?.get(Jw.getStore()?.get(Jr(e))??Jr(e));return t?t.map(r=>({...r})):(Ur(e,["rev-parse","--is-inside-work-tree"]),Kw(e))}catch{return[]}}function Kw(e){let t=__(Ur(e,["worktree","list","--porcelain","-z"]));return P_(t),t.map(r=>({...r}))}function __(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Ri.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 gr(e){return Oc(e).map(t=>t.root)}function zw(e,t){let r=t.find(a=>Kr(Ri.resolve(a.root),Ri.resolve(e)));if(!r)return null;let i=Ri.resolve(t[0].root),n=Ri.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Kr(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Yw(e){try{return Ur(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function bn(e,t){try{return Ur(e,["check-ref-format","--branch",t]),Ur(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function wr(e,t){try{let r=Ur(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}We();rt();pe();gt();ie();at();dl();dl();Hi();kr();import{randomUUID as m0}from"node:crypto";import vu from"node:path";We();_o();ne();pe();Fn();ve();ie();df();Hi();kr();Gn();We();import{promises as zo}from"node:fs";import Qe from"node:path";gt();Gn();Oo();ie();var ai=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function aN(e,t){let r=Qe.relative(e,t);return r===""||!Qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Qe.sep}`)}function iN(e){return JSON.stringify(e.native)}async function ru(e,t){let r=await Oe(e);if(r&&t){if(iN(r)!==iN(t))throw new Error(`Native worktree configuration differs from the source project: ${Qe.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await rl(e,t),await rN(e),!0):!1}async function C$(e,t){if(!aN(e,t))return!1;let i=`/${Qe.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=Qe.resolve(e,n),o=Qe.join(a,"info","exclude"),s="";try{s=await zo.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await zo.mkdir(Qe.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
217
230
|
`)?"":`
|
|
218
|
-
`;return await
|
|
219
|
-
`,"utf8"),!0}function PI(e,t,r){let i=ze.resolve(e,r??ze.join(".worktrees",t)),n=ze.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(Fy(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(nr(e).some(a=>Ki(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function _I(e){try{throw await fo.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function qy(e){try{return await fo.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Np(e){let t=ze.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=ie(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Dr(t,e.sourceConfig?.native.artifact_root??"docs");return Bw([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=ie(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Gd(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Gd(t,o),!Yi(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!Zs(t))throw new Error("Native branch isolation requires a clean current working directory");if(Yi(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),p=!0}let m;try{m=await kl(t,e.sourceConfig)}catch(h){throw new Vr(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?ze.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ki(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let m;try{m=await kl(t,e.sourceConfig)}catch(h){throw new Vr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Qs(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await qy(c.root)){let p=e.worktreePath?ze.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ki(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await kl(c.root,e.sourceConfig)}catch(h){throw new Vr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await qy(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=Qs(i.primaryWorktreeRoot));let l=Yi(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=PI(i.primaryWorktreeRoot,e.name,e.worktreePath);await _I(u);let f=await RI(i.primaryWorktreeRoot,u),d={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:f,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await kl(u,e.sourceConfig)}catch(p){throw new Vr(`Native worktree preparation is incomplete: ${p.message}`,d,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}function Dl(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`}async function zp(e){let t=Hl.join(".worktrees",`${e.parent}-integration`);return Np({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Dl(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function Jp(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Np({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Hl.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function vj(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function gj(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}function AN(e,t,r){let i=ie(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!zt(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function Ro(e){if(!zt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Hl.resolve(t)!==Hl.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function IN(e,t,r){let i=ie(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!zt(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}async function Gp(e){let t=vj(e.retryCheckIds),r=await _(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let p=await O(e.paths,e.state.parent)??e.state,m=p.integration.checkExecution;if(m?.status==="running"){if(await mn(m.ownerPid,m.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(m.activeProcess===void 0||m.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(m.activeProcess&&await mn(m.activeProcess.pid,m.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(p.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let h=p.children.find(({name:S})=>S===e.name);if(!h)throw new Error(`Native Supervisor child ${e.name} does not exist`);let g=gw(p).find(({status:S})=>S!=="integrated"&&S!=="archived");if(g&&g.name!==e.name)throw new Error(`Native Supervisor integration order requires ${g.name} before ${e.name}`);if(h.status!=="verified"||!h.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:x})=>!x))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:x})=>x)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(Ye(p.integration.worktree,e.checkPlans),!h.verification?.receiptRef||!h.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:S}=await Promise.resolve().then(()=>(Wp(),_N)),N=await S({paths:e.paths,parent:p.parent,task:h.verification.execution,receiptRef:h.verification.receiptRef});if(N.candidateCommit!==h.verifiedCommit||N.checks.some(({status:x})=>x!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let v=Ro(p),w=e.checkPlans!==void 0&&m?.status==="interrupted"&&m.child===e.name&&m.candidateCommit===h.verifiedCommit&&v!==p.integration.headCommit&&v===m.integrationCommit;if(v!==p.integration.headCommit){let S=(()=>{try{return I(p.integration.worktree,["merge-base","--is-ancestor",p.integration.headCommit,v]),!0}catch{return!1}})(),N=(()=>{try{return I(p.integration.worktree,["merge-base","--is-ancestor",h.verifiedCommit,v]),!0}catch{return!1}})();if(!S||!N)throw new Error(`Native Supervisor integration head drifted: expected ${p.integration.headCommit}, got ${v}`)}try{I(p.integration.worktree,["cat-file","-e",`${h.verifiedCommit}^{commit}`])}catch(S){throw new Error(`Native Supervisor verified commit is unavailable: ${h.verifiedCommit}`,{cause:S})}if(v===p.integration.headCommit&&!w){try{I(p.integration.worktree,["merge","--no-ff","--no-edit",h.verifiedCommit])}catch(S){throw new Error(`Native Supervisor integration conflict preserved in ${p.integration.worktree}`,{cause:S})}v=I(p.integration.worktree,["rev-parse","HEAD"])}let y=v;if(e.checkPlans){let S=yl(),N=await wl({kind:"integration",parent:p.parent,child:e.name,runId:h.verification?.execution?.runId??`integration:${e.name}`,projectRoot:p.integration.worktree,candidateCommit:h.verifiedCommit,integrationCommit:y,contractHash:h.contractHash??null,plans:e.checkPlans,materials:[]}),x=T("comet.native.supervisor-integration-plan.v2",{machineId:S,inputFingerprint:N}),k=m?.key===x&&m.machineId===S&&m.inputFingerprint===N&&m.child===e.name&&m.candidateCommit===h.verifiedCommit&&m.integrationCommit===y;if(t){if(!k||m?.status!=="interrupted")throw new Error("Native Supervisor integration retry requires the interrupted current plan on the same candidate, machine and workspace");gj(m.checkStates,e.checkPlans,t)}else if(m?.status==="interrupted"&&k){let P=(m.checkStates??[]).filter(({status:W})=>W==="failed");if(P.length>0)throw new Error(`Native Supervisor integration checks already failed on the identical plan (${P.map(({id:W})=>W).join(", ")}); change the integration check plan or re-verify the child instead of rerunning the same integrate`);return{completed:p}}let E=t&&m?.checkStates?m.checkStates.map(P=>t.has(P.id)?{...P,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...P}):e.checkPlans.map(bn),C=e.checkPlans.map(P=>E.find(W=>W.id===P.id)??bn(P)),H=mj();return p.integration.checkExecution={operationId:H,key:x,child:e.name,candidateCommit:h.verifiedCommit,integrationCommit:y,status:"running",ownerPid:process.pid,ownerIdentity:await Ke(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null,machineId:S,inputFingerprint:N,checkStates:C},p.stateVersion+=1,await q(e.paths,p),{pending:{state:p,candidateCommit:h.verifiedCommit,integrationCommit:y,operationId:H,key:x,machineId:S,inputFingerprint:N,plansToExecute:e.checkPlans.filter(P=>!t||t.has(P.id))}}}let b=$c(p,{name:e.name,integrationCommit:y,checks:e.checks});return await q(e.paths,b),{completed:b}});if(r.completed)return r.completed;let{state:i,candidateCommit:n,integrationCommit:a,operationId:o,key:s}=r.pending,{writeNativeVerificationReportSnapshot:c}=await Promise.resolve().then(()=>(Gr(),RN)),{createHash:l}=await import("node:crypto"),u=async d=>_(e.paths,"record Supervisor integration check process",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(!p||m?.operationId!==o||m.key!==s||m.status!=="running")throw new Error("Native Supervisor integration check operation is stale");if(d?.status==="starting"){let h=m.checkStates?.find(({id:g})=>g===d.checkId);if(!h||h.status!=="planned")throw new Error(`Native Supervisor check ${d.checkId} is not planned`);h.status="running",h.executionCount+=1,h.startedAt=new Date().toISOString(),h.completedAt=null,h.logRef=null}m.activeProcess=d,p.stateVersion+=1,await q(e.paths,p)}),f=async d=>_(e.paths,"record Supervisor integration check result",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(!p||m?.operationId!==o||m.key!==s||m.status!=="running")throw new Error("Native Supervisor integration check operation is stale");let h=m.checkStates?.find(({id:g})=>g===d.id);if(!h)throw new Error(`Native Supervisor check state is missing: ${d.id}`);Object.assign(h,vl(h,d)),m.activeProcess=null,p.stateVersion+=1,await q(e.paths,p)});try{for(let b of r.pending.plansToExecute){await u({status:"starting",checkId:b.id});let S=await Ni({projectRoot:i.integration.worktree,runtimeDir:pe(e.paths,i.parent),operationId:o,plan:b,onSpawn:async({pid:N})=>u({status:"running",checkId:b.id,pid:N,identity:await Ke(N)??void 0})});if(await f(S),S.status==="interrupted")throw new Error(`Native Supervisor integration check ${S.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let d=await O(e.paths,i.parent),m=d?.integration.checkExecution?.checkStates;if(!d||!m||m.some(({status:b})=>!["passed","failed"].includes(b)))throw new Error("Native Supervisor integration check plan remains incomplete; retry each interrupted check explicitly");let h=m.map(gl),g=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:i.parent,child:e.name,candidateCommit:n,integrationCommit:a,operationId:o,planHash:s,results:h}),v=await c({paths:e.paths,name:i.parent,hash:l("sha256").update(g).digest("hex"),text:g}),w=h.map(b=>({name:b.name,status:b.status==="interrupted"?"incomplete":b.status,reason:b.status==="passed"?null:b.timedOut?"timed out":`exit ${b.exitCode??b.signal??"interrupted"}`,receiptRef:v})),y=w.filter(({status:b})=>b!=="passed");return await _(e.paths,"complete Supervisor integration checks",async()=>{let b=await O(e.paths,i.parent),S=b?.children.find(({name:k})=>k===e.name),N=b?.integration.checkExecution;if(!b||!S||N?.operationId!==o||N.key!==s||N.status!=="running"||N.child!==e.name||N.candidateCommit!==n||N.integrationCommit!==a||S.verifiedCommit!==n||Ro(b)!==a)throw new Error("Native Supervisor integration changed during checks");if(N.receiptRef=v,N.checks=w,y.length>0){let k=`Native Supervisor integration checks did not pass (${y.map(({name:E,reason:C})=>`${E}: ${C}`).join("; ")}); receipt ${v}`;throw N.status="interrupted",N.error=k,S.blocker=k,b.stateVersion+=1,await q(e.paths,b),new Error(k)}N.status="completed";let x=$c(b,{name:e.name,integrationCommit:a,checks:w});return await q(e.paths,x),x})}catch(d){throw await _(e.paths,"interrupt Supervisor integration checks",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(p&&m?.operationId===o&&m.key===s&&m.status==="running"){m.status="interrupted",m.error=d.message,m.activeProcess=null;for(let h of m.checkStates??[])(h.status==="planned"||h.status==="running")&&(h.status="interrupted");p.stateVersion+=1,await q(e.paths,p)}}),d}}import{randomUUID as wj}from"node:crypto";import yj from"node:path";rt();st();le();gi();lr();async function Po(e){let t=Dl(e.parent),r=ar(e.paths.projectRoot,t);if(!r)return null;let i=ar(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=nr(e.paths.projectRoot).map(o=>yj.resolve(o)).find(o=>ie(o).currentBranch===t);if(!n)return null;let a=Ja({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 Ue(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}async function Up(e){return _(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await O(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await _e(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let f;try{f=await Jp({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?IN(f.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):AN(f.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let m=Ve(o),h=m.children.find(({name:g})=>g===l.name);h&&(h.blocker=p.message,Ue(m,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),m.stateVersion+=1,o=m,c=!0);continue}let d=Ga(o,{role:u?"verifier":"builder",child:l.name,projectRoot:f.projectRoot,runId:wj()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await q(e.paths,o),{state:o,tasks:s}})}function TN(e,t){if(ft(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ve(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ii(e){let t=Ro(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ve(e);return r.integration.headCommit=t,Ue(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ti(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Ro(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return TN(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Kp(e,t){let r=_t.normalize(_t.resolve(e)),i=_t.normalize(_t.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function bj(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=bj(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 _o(e){try{let t=await Q({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return kj(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function An(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 Sj(e){let t=nr(e.projectRoot);t.some(i=>Kp(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>_t.resolve(n)))]){let n=await _e(i);n&&r.push({projectRoot:i,paths:await Dr(i,n.native.artifact_root),parent:Kp(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Ej(e,t){let r=_t.join(e.paths.changesDir,t,"comet-state.yaml");try{return await lt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function xj(e,t){let r;try{r=await Nj.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=_t.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await lt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function Cj(e,t,r){let i=_t.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${_t.sep}`))return null;let n=i.split(_t.sep).join("/");try{let a=(0,$N.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:B(a.toJS({mapAsMap:!1}))}catch{return null}}function Rj(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 jN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function je(e){let t=_t.join(e.paths.changesDir,e.state.name),r=await _o(t),i=null,n;try{n=await Fe({changeDir:t,validation:dt(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:v})=>v)}:{},policy:"advisory"})}catch(v){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${v.message}`,n=null}if(!n){let v=await O(e.paths,e.state.name,{diagnostics:!0});if(v){let w=Oc(v);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(y=>({...y,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=An({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===Br){let v=await O(e.paths,e.state.name,{diagnostics:!0});if(!v){let b=e.state.workspace.change_branch??e.state.workspace.target_branch;if(b){let S=await Po({paths:e.paths,parent:e.state.name,targetBranch:b,contract:n.contract});S&&(v=S,await q(e.paths,S))}}if(v){let b=Oc(v);return e.state.children_contract_hash!==a||n.drift?{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(S=>({...S,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&b.confirmed}}let w=new Map(n.contract.children.map(b=>[b.name,b])),y=n.contract.children.map(b=>({name:b.name,summary:b.summary,dependsOn:[...b.depends_on],covers:[],status:s&&b.depends_on.every(S=>n.contract.children.filter(({name:N})=>N!==b.name).every(({name:N})=>N!==S))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let b of y){if(b.status!=="ready")continue;w.get(b.name).depends_on.length>0&&(b.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:y,readyChildren:y.filter(({status:b})=>b==="ready").map(({name:b})=>b),allDone:!1}}let c=await Sj(e.paths),l=new Set(n.contract.children.map(({name:v})=>v)),u=new Map,f=new Map;for(let v of c){let w=v.parent&&o?`refs/heads/${o}`:"HEAD";for(let y of await xj(v,l)){let b={...y,source:v,committedState:Cj(v,y.file,w)};u.set(y.state.name,[...u.get(y.state.name)??[],b])}for(let y of l){let b=await Ej(v,y);b&&f.set(y,[...f.get(y)??[],{source:v,state:b}])}}let d=new Map;for(let v of n.contract.children){let w=(u.get(v.name)??[]).find(({source:S,committedState:N})=>S.parent&&N?.name===v.name&&jN(N,o));if(w){d.set(v.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=u.get(v.name)?.[0];if(y){d.set(v.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let b=f.get(v.name)??[];b.length>1?d.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):b[0]&&d.set(v.name,Rj(b[0].state,b[0].source,o))}let p=new Map(n.contract.children.map(v=>[v.name,v])),m=new Map,h=v=>{let w=m.get(v);if(w)return w;let y=p.get(v),S=y.depends_on.map(h).every(({status:H})=>H==="done"),N=d.get(v),x=N?.kind==="active"&&S?y.depends_on.filter(H=>!(u.get(H)??[]).some(({source:P,committedState:W})=>Kp(P.projectRoot,N.projectRoot)&&W?.name===H&&jN(W,o))):[],k,E=N?.message??null;N?.kind==="done"?(k=S?"done":"blocked",S||(E=`Native child ${v} was merged before its dependencies`)):N?.kind==="active"?(k=S&&x.length===0?"active":"blocked",S?x.length>0&&(E=`Native child ${v} does not include merged dependencies: ${x.join(", ")}`):E=`Native child ${v} started before its dependencies merged`):N?.kind==="blocked"?k="blocked":(k=s&&S?"ready":"pending",s||(E="Parent Shape confirmation is required"));let C={name:v,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:k,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:E};return m.set(v,C),C},g=n.contract.children.map(({name:v})=>h(v));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:g,readyChildren:g.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:g.every(({status:v})=>v==="done")}}cn();gi();function $e(e,t,r){return e.language==="zh-CN"?r:t}function Pj(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:$e(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:$e(e,"Reply A or B","回复 A 或 B"),agentInstruction:$e(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($e(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($e(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:$e(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:$e(e,"Accept the result","接受结果"),agentInstruction:$e(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)>=cr)??!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($e(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($e(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 _j(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 Aj(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:$e(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:$e(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function BN(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function ji(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ON(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function Ij(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function HN(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function Tj(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function jj(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 Ur(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:BN({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[ji("summary","--summary"),Ij(e.name,e.flag)]}}function DN(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:$e(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function $j(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Bl(e){return[Ur({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ur({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Oj(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 K(e,t,r={}){let i=Tj(t)&&e.coordination_mode===void 0,n=Pj(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:[ji("summary","--summary")],commandAlternatives:[Ur({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Bl({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Ur({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Bl({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:[ji("summary","--summary")],commandAlternatives:Bl({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Bl({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?BN({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:jj({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?[HN("coordination-mode","--coordination-mode",Nc)]:[]],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:[ON()],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"),f=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=cr)??null,d=f===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:f.name,stateVersion:t.supervisorStateVersion},description:$e(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&d===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:d!==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?[]:d!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:d!==null?[d]:[ji("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=ON();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} ${$e(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:Oj([{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=DN(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(f=>$j(f))?{...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:DN(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:[HN("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Aj(e)],userCommunication:_j(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Ur({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")}}rt();Xa();fe();gn();import{createHash as bb,randomUUID as kb}from"node:crypto";import{promises as Qt}from"node:fs";import Zr from"node:os";import j from"node:path";ut();Fr();mi();Ma();import{randomUUID as Hj}from"node:crypto";var Ao=3,Yp=2;function Oe(e){return e.state_version+1}function Dj(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function LN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Xp(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function Bj(e){return(e??[]).map(t=>({name:J(t.name),result:t.result,note:t.note?J(t.note):null}))}function Kr(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:J(e.summary),completed_at:e.completedAt}}function qN(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,phase:"build",status:"active",state_version:Oe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function FN(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,status:"await-user",state_version:Oe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function VN(e){let t=B(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!mw(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let i=Dj(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=LN(t.acceptance),a=(r.now??new Date).toISOString();return B({...t,phase:"verify",state_version:Oe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:n,builder_handoff:{candidate_id:r.candidateId??Hj(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:J(r.summary),addressed_acceptance_ids:i,checks:Bj(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(o=>J(o)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:J(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:a},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function MN(e){let t=B(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return B({...t,state_version:Oe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Lj(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function qj(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Ne?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:J(e.response.result.summary),risks:e.response.result.risks.map(t=>J(t)),risks_truncated:!1,completed_at:e.completedAt}}function WN(e){let t=B(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Xp(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=vw({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:g})=>g),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:g})=>g==="passed").map(({id:g})=>g),requiredChecksPassed:e.checks.every(({status:g})=>g==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(g=>[g.id,g])),o=t.acceptance.map(g=>{let v=a.get(g.id);return v?{...g,result:v.result,reason:J(v.reason)}:g}),s=o.filter(({result:g})=>g==="failed"||g==="blocked").map(({id:g})=>g),c=qj({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){let g=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),v=t.builder_handoff.identity_provider===Ne;return{response:i,state:B({...g,phase:v?"verify":"archive",status:v?"await-user":"active",state_version:Oe(t),verification_result:"pass",verification_report:"verification.md",blockers:v?[{owner:"user",reason:J("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:v?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:v?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let g=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...g,status:"await-user",state_version:Oe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:J(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=Lj(t,s),f=l>=e.maxVerifyFailures,d=u>=3,p=f||d,m=d?"stalled":f?"budget":void 0,h=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...h,phase:p?"verify":"build",status:p?"await-user":"active",state_version:Oe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:J(m==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:J("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...m===void 0?{}:{stop_reason:m},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function zN(e){let t=B(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Ne||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return B({...t,phase:"archive",status:"active",state_version:Oe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function JN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Ne||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=Xp(t),n=ye(t,Kr({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return B({...n,status:"await-user",state_version:Oe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:J(e.summary),risks:[J("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:J("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function GN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=J(e.summary),n=ye(t,Kr({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return B({...n,phase:"archive",status:"active",state_version:Oe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:J(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function UN(e,t){let r=B(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=ye(r,Kr({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return B({...i,status:"active",state_version:Oe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function KN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Ao,a=ye(t,Kr({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return B({...a,status:n?"blocked":"active",state_version:Oe(t),blockers:n?[{owner:"runtime",reason:J(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function YN(e){let t=B(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=Xp(t),a=t.acceptance.some(({result:o})=>o==="passed");return B({...t,status:"active",state_version:Oe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function Yr(e){let t=B(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=ye(t,Kr({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?LN(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return n?B({...o,phase:"verify",status:"await-user",state_version:Oe(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:J(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):B({...o,phase:"build",status:"active",state_version:Oe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ne();cn();import{promises as XN}from"node:fs";import Fj from"node:os";import jo from"node:path";function Io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function To(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 He(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 In(e,t){return e===null?null:He(e,t)}function Tn(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 Vj(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 Mj(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function jn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qp(e,t){if(e===null)return null;let r=He(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Wj(e,t){let r=He(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Zp(e,t){let r=He(e,t);if(!jo.isAbsolute(r))throw new Error(`${t} must be absolute`);return jo.resolve(r)}function zj(e,t){let r=`Native local checks[${t}]`,i=Io(e,r);if(To(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,f)=>He(u,`${r}.argv[${f}]`,!0)),a=jn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Qp(i.startedAt,`${r}.startedAt`),s=Qp(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=Tn(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=Io(i.activeProcess,`${r}.activeProcess`),f=jn(u.status,["starting","running"],`${r}.activeProcess.status`);if(To(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),f==="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:Tn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:He(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:He(i.id,`${r}.id`),name:He(i.name,`${r}.name`),operationId:He(i.operationId,`${r}.operationId`),status:a,repeatable:Mj(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Tn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Zp(i.cwd,`${r}.cwd`),exitCode:Vj(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:He(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:jn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:He(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function eh(e){let t="Native local execution state",r=Io(e,t);if(To(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Da)throw new Error(`Native local execution schema must be ${Da}`);let i=Io(r.workspace,"Native local workspace");To(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Io(r.execution,"Native local execution");To(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Qp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:He(o.operationId,"Native local execution.operationId"),stage:jn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:jn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:In(o.executionId,"Native local execution.executionId"),status:jn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Tn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:Wj(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Tn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:He(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(zj);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:Da,change:He(r.change,"Native local change"),basedOnStateVersion:Tn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:In(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:In(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:In(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:In(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Zp(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Zp(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:In(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:He(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function re(e){return eh({schema:Da,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:jo.resolve(e.projectRoot),worktreeRoot:jo.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:Fj.hostname()},execution:null,checks:[]})}async function Se(e){let t;try{t=await XN.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 eh(r)}function QN(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}async function F(e,t,r={}){let i=eh(t);await XN.mkdir(jo.dirname(e),{recursive:!0}),await we(e,i,r)}async function Ll(e){let t=null,r=null;try{t=await Se(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=re(e);return await F(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}le();Fr();te();async function th(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let i=new Array(e.length),n=0,a=async()=>{for(;n<e.length;){let o=n;n+=1,i[o]=await r(e[o],o)}};return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),i}import{promises as ZN}from"node:fs";import ql from"node:path";rt();ut();te();var rh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eb="comet-state.yaml",tb="state.json";function se(e,t){if(!rh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ql.join(e.changesDir,t);if(!be(e.changesDir,r))throw new Error("Native change path escaped");return r}function Qe(e,t){return ql.join(se(e,t),eb)}function D(e,t){return ql.join(pe(e,t),tb)}async function $n(e,t){try{let r=await ZN.readFile(Qe(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function ve(e){return Tg(e)}function Fl(e,t){let r=ie(t);if(!r.isGitWorktree||r.currentBranch===null||ar(t,r.currentBranch)===null)return null;if(!Zs(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}async function $(e,t){return lt(Qe(e,t))}async function ce(e){let t=await dn({file:Qe(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ql.join(se(e.paths,t.name),"verification.md");await z(e.paths.nativeRoot,r),await ZN.rm(r,{force:!0})}return t}async function ih(e){let t=await $(e.paths,e.name),r=D(e.paths,e.name);try{let i=await Se(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"}}}ne();import{promises as zl}from"node:fs";import $i from"node:path";xi();var ah=br(rr(),1);import Ho from"path";nt();ne();xi();st();le();te();Mt();po();le();te();nn();$r();var Xj=br(rr(),1);nn();$r();Hr();Hr();rn();hf();nn();Hr();var wM=4*1024*1024;var Qj=null;function Zj(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function rb(e,t){return(...r)=>{let i=Qj;if(i===null)return t(...r);let n=Zj(`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}}rn();var SM=rb("hookWritePolicy",async e=>(await nf(e))?.hook??{allow_paths:[]});Ta();var e$=16*1024;ff();Ea();var S1=Number.MAX_SAFE_INTEGER;ne();Dt();var H1={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import On from"node:path";ne();nt();le();te();var $o=/^[a-f0-9]{64}$/u,nb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,s$=16*1024,X1=process.platform;function c$(e,t){let r=On.relative(e,t);return On.isAbsolute(r)||r===".."||r.startsWith(`..${On.sep}`)?null:r.replaceAll("\\","/")||"."}function ab(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function ob(e,t){if(e.length===0||ab(e)||e.includes("\\")||On.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=On.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function l$(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 nh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ab(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function u$(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(nh(e.changeBranch,"Native workspace change branch"),nh(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 d$(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"||!nb.test(t.baseCommit)||typeof t.targetCommit!="string"||!nb.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");nh(t.targetBranch,"Native workspace Git target branch")}function f$(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"||!$o.test(String(t.projectRootId))||!$o.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");l$(t.capturedAt),ob(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&&!$o.test(String(t.projectRootPathId))||a&&!$o.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!$o.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&d$(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(u$(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 p$(e,t){return On.join(ot(e,t),"workspace.json")}function h$(e,t){let r=p$(e,t),i=qe(e,r),n=c$(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:ob(n,"Native workspace file ref")}}async function m$(e,t){try{let r=h$(e,t),i=await Q({root:r.root,ref:r.ref,maxBytes:s$});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Oo(e,t){let r=await m$(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(f$(r),r)}no();Yc();Yc();var Vl=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"},Do=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"},Ml=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"},EW=Qc("en");function At(e,t){co(t);let r=Ho.join(e.changesDir,t);if(!be(e.changesDir,r))throw new Error("Native change path escaped");return r}async function y$(e,t=Ho.dirname(e)){let r=Ho.relative(t,e).split(Ho.sep).join("/"),i=await Q({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,ah.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 sb(e,t){let r=Ho.join(At(e,t),fr);await z(e.nativeRoot,r);let i=ip(await y$(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}nt();Jt();te();var lb=["outcome","scope","nonGoals","acceptanceExamples"],cb=[...lb,"constraints","decisions","openQuestions","verificationExpectations"];var b$=new Set(["nonGoals","decisions","openQuestions"]),k$={maxFileBytes:Kd};function S$(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
220
|
-
`).
|
|
221
|
-
`)
|
|
222
|
-
`)
|
|
223
|
-
`)
|
|
224
|
-
`)
|
|
225
|
-
`):
|
|
226
|
-
`)
|
|
227
|
-
`)
|
|
228
|
-
`),
|
|
231
|
+
`;return await zo.appendFile(o,`${c}${i}
|
|
232
|
+
`,"utf8"),!0}function P$(e,t,r){let i=Qe.resolve(e,r??Qe.join(".worktrees",t)),n=Qe.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(aN(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(gr(e).some(a=>Kr(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function _$(e){try{throw await zo.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function nN(e){try{return await zo.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pf(e){let t=Qe.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=oe(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await ei(t,e.sourceConfig?.native.artifact_root??"docs");return rb([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=oe(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Lp(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Lp(t,o),!bn(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let h=!1;if(!a){if(!Hc(t))throw new Error("Native branch isolation requires a clean current working directory");if(bn(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),h=!0}let f;try{f=await ru(t,e.sourceConfig)}catch(m){throw new ai(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:f}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?Qe.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Kr(h,i.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${i.currentWorktreeRoot}`);let f;try{f=await ru(t,e.sourceConfig)}catch(m){throw new ai(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:f}}}let s=Oc(i.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await nN(c.root)){let h=e.worktreePath?Qe.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!Kr(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let f;try{f=await ru(c.root,e.sourceConfig)}catch(m){throw new ai(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:f}}}c&&!await nN(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=Oc(i.primaryWorktreeRoot));let l=bn(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=P$(i.primaryWorktreeRoot,e.name,e.worktreePath);await _$(u);let d=await C$(i.primaryWorktreeRoot,u),p={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),p.createdBranch=!l,p.createdWorktree=!0,p.configInitialized=await ru(u,e.sourceConfig)}catch(h){throw new ai(`Native worktree preparation is incomplete: ${h.message}`,p,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:p}})}function gu(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`}async function Df(e){let t=vu.join(".worktrees",`${e.parent}-integration`);return pf({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:gu(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function Bf(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return pf({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:vu.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function v0(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function g0(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}function UN(e,t,r){let i=oe(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!tr(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function os(e){if(!tr(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(vu.resolve(t)!==vu.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function KN(e,t,r){let i=oe(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!tr(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}async function Lf(e){let t=v0(e.retryCheckIds),r=await A(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let h=await D(e.paths,e.state.parent)??e.state,f=h.integration.checkExecution;if(f?.status==="running"){if(await Ln(f.ownerPid,f.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(f.activeProcess===void 0||f.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(f.activeProcess&&await Ln(f.activeProcess.pid,f.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(h.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let m=h.children.find(({name:E})=>E===e.name);if(!m)throw new Error(`Native Supervisor child ${e.name} does not exist`);let v=$y(h).find(({status:E})=>E!=="integrated"&&E!=="archived");if(v&&v.name!==e.name)throw new Error(`Native Supervisor integration order requires ${v.name} before ${e.name}`);if(m.status!=="verified"||!m.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:x})=>!x))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:x})=>x)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(lt(h.integration.worktree,e.checkPlans),!m.verification?.receiptRef||!m.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:E}=await Promise.resolve().then(()=>(Hf(),JN)),b=await E({paths:e.paths,parent:h.parent,task:m.verification.execution,receiptRef:m.verification.receiptRef});if(b.candidateCommit!==m.verifiedCommit||b.checks.some(({status:x})=>x!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let g=os(h),w=e.checkPlans!==void 0&&f?.status==="interrupted"&&f.child===e.name&&f.candidateCommit===m.verifiedCommit&&g!==h.integration.headCommit&&g===f.integrationCommit;if(g!==h.integration.headCommit){let E=(()=>{try{return I(h.integration.worktree,["merge-base","--is-ancestor",h.integration.headCommit,g]),!0}catch{return!1}})(),b=(()=>{try{return I(h.integration.worktree,["merge-base","--is-ancestor",m.verifiedCommit,g]),!0}catch{return!1}})();if(!E||!b)throw new Error(`Native Supervisor integration head drifted: expected ${h.integration.headCommit}, got ${g}`)}try{I(h.integration.worktree,["cat-file","-e",`${m.verifiedCommit}^{commit}`])}catch(E){throw new Error(`Native Supervisor verified commit is unavailable: ${m.verifiedCommit}`,{cause:E})}if(g===h.integration.headCommit&&!w){try{I(h.integration.worktree,["merge","--no-ff","--no-edit",m.verifiedCommit])}catch(E){throw new Error(`Native Supervisor integration conflict preserved in ${h.integration.worktree}`,{cause:E})}g=I(h.integration.worktree,["rev-parse","HEAD"])}let N=g;if(e.checkPlans){let E=Zl(),b=await Ql({kind:"integration",parent:h.parent,child:e.name,runId:m.verification?.execution?.runId??`integration:${e.name}`,projectRoot:h.integration.worktree,candidateCommit:m.verifiedCommit,integrationCommit:N,contractHash:m.contractHash??null,plans:e.checkPlans,materials:[]}),x=$("comet.native.supervisor-integration-plan.v2",{machineId:E,inputFingerprint:b}),k=f?.key===x&&f.machineId===E&&f.inputFingerprint===b&&f.child===e.name&&f.candidateCommit===m.verifiedCommit&&f.integrationCommit===N;if(t){if(!k||f?.status!=="interrupted")throw new Error("Native Supervisor integration retry requires the interrupted current plan on the same candidate, machine and workspace");g0(f.checkStates,e.checkPlans,t)}else if(f?.status==="interrupted"&&k){let _=(f.checkStates??[]).filter(({status:j})=>j==="failed");if(_.length>0)throw new Error(`Native Supervisor integration checks already failed on the identical plan (${_.map(({id:j})=>j).join(", ")}); change the integration check plan or re-verify the child instead of rerunning the same integrate`);return{completed:h}}let S=t&&f?.checkStates?f.checkStates.map(_=>t.has(_.id)?{..._,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{..._}):e.checkPlans.map(zn),C=e.checkPlans.map(_=>S.find(j=>j.id===_.id)??zn(_)),P=m0();return h.integration.checkExecution={operationId:P,key:x,child:e.name,candidateCommit:m.verifiedCommit,integrationCommit:N,status:"running",ownerPid:process.pid,ownerIdentity:await ct(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null,machineId:E,inputFingerprint:b,checkStates:C},h.stateVersion+=1,await F(e.paths,h),{pending:{state:h,candidateCommit:m.verifiedCommit,integrationCommit:N,operationId:P,key:x,machineId:E,inputFingerprint:b,plansToExecute:e.checkPlans.filter(_=>!t||t.has(_.id))}}}let y=vl(h,{name:e.name,integrationCommit:N,checks:e.checks});return await F(e.paths,y),{completed:y}});if(r.completed)return r.completed;let{state:i,candidateCommit:n,integrationCommit:a,operationId:o,key:s}=r.pending,{writeNativeVerificationReportSnapshot:c}=await Promise.resolve().then(()=>(ui(),zN)),{createHash:l}=await import("node:crypto"),u=async p=>A(e.paths,"record Supervisor integration check process",async()=>{let h=await D(e.paths,i.parent),f=h?.integration.checkExecution;if(!h||f?.operationId!==o||f.key!==s||f.status!=="running")throw new Error("Native Supervisor integration check operation is stale");if(p?.status==="starting"){let m=f.checkStates?.find(({id:v})=>v===p.checkId);if(!m||m.status!=="planned")throw new Error(`Native Supervisor check ${p.checkId} is not planned`);m.status="running",m.executionCount+=1,m.startedAt=new Date().toISOString(),m.completedAt=null,m.logRef=null}f.activeProcess=p,h.stateVersion+=1,await F(e.paths,h)}),d=async p=>A(e.paths,"record Supervisor integration check result",async()=>{let h=await D(e.paths,i.parent),f=h?.integration.checkExecution;if(!h||f?.operationId!==o||f.key!==s||f.status!=="running")throw new Error("Native Supervisor integration check operation is stale");let m=f.checkStates?.find(({id:v})=>v===p.id);if(!m)throw new Error(`Native Supervisor check state is missing: ${p.id}`);Object.assign(m,Yl(m,p)),f.activeProcess=null,h.stateVersion+=1,await F(e.paths,h)});try{for(let y of r.pending.plansToExecute){await u({status:"starting",checkId:y.id});let E=await Bi({projectRoot:i.integration.worktree,runtimeDir:me(e.paths,i.parent),operationId:o,plan:y,onSpawn:async({pid:b})=>u({status:"running",checkId:y.id,pid:b,identity:await ct(b)??void 0})});if(await d(E),E.status==="interrupted")throw new Error(`Native Supervisor integration check ${E.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let p=await D(e.paths,i.parent),f=p?.integration.checkExecution?.checkStates;if(!p||!f||f.some(({status:y})=>!["passed","failed"].includes(y)))throw new Error("Native Supervisor integration check plan remains incomplete; retry each interrupted check explicitly");let m=f.map(Xl),v=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:i.parent,child:e.name,candidateCommit:n,integrationCommit:a,operationId:o,planHash:s,results:m}),g=await c({paths:e.paths,name:i.parent,hash:l("sha256").update(v).digest("hex"),text:v}),w=m.map(y=>({name:y.name,status:y.status==="interrupted"?"incomplete":y.status,reason:y.status==="passed"?null:y.timedOut?"timed out":`exit ${y.exitCode??y.signal??"interrupted"}`,receiptRef:g})),N=w.filter(({status:y})=>y!=="passed");return await A(e.paths,"complete Supervisor integration checks",async()=>{let y=await D(e.paths,i.parent),E=y?.children.find(({name:k})=>k===e.name),b=y?.integration.checkExecution;if(!y||!E||b?.operationId!==o||b.key!==s||b.status!=="running"||b.child!==e.name||b.candidateCommit!==n||b.integrationCommit!==a||E.verifiedCommit!==n||os(y)!==a)throw new Error("Native Supervisor integration changed during checks");if(b.receiptRef=g,b.checks=w,N.length>0){let k=`Native Supervisor integration checks did not pass (${N.map(({name:S,reason:C})=>`${S}: ${C}`).join("; ")}); receipt ${g}`;throw b.status="interrupted",b.error=k,E.blocker=k,y.stateVersion+=1,await F(e.paths,y),new Error(k)}b.status="completed";let x=vl(y,{name:e.name,integrationCommit:a,checks:w});return await F(e.paths,x),x})}catch(p){throw await A(e.paths,"interrupt Supervisor integration checks",async()=>{let h=await D(e.paths,i.parent),f=h?.integration.checkExecution;if(h&&f?.operationId===o&&f.key===s&&f.status==="running"){f.status="interrupted",f.error=p.message,f.activeProcess=null;for(let m of f.checkStates??[])(m.status==="planned"||m.status==="running")&&(m.status="interrupted");h.stateVersion+=1,await F(e.paths,h)}}),p}}import{randomUUID as w0}from"node:crypto";import y0 from"node:path";We();gt();ve();Hi();kr();async function ss(e){let t=gu(e.parent),r=wr(e.paths.projectRoot,t);if(!r)return null;let i=wr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=gr(e.paths.projectRoot).map(o=>y0.resolve(o)).find(o=>oe(o).currentBranch===t);if(!n)return null;let a=xo({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 ot(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}async function qf(e){return A(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await D(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Oe(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let d;try{d=await Bf({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?KN(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):UN(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(h){let f=Ue(o),m=f.children.find(({name:v})=>v===l.name);m&&(m.blocker=h.message,ot(f,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),f.stateVersion+=1,o=f,c=!0);continue}let p=Ro(o,{role:u?"verifier":"builder",child:l.name,projectRoot:d.projectRoot,runId:w0()});o=p.state,s.push(p.task)}return(s.length>0||c)&&await F(e.paths,o),{state:o,tasks:s}})}function YN(e,t){if(Nt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ue(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ki(e){let t=os(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ue(e);return r.integration.headCommit=t,ot(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Yi(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=os(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return YN(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Ff(e,t){let r=Bt.normalize(Bt.resolve(e)),i=Bt.normalize(Bt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function N0(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 k0(e){let t=N0(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 cs(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return k0(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ea(e){return $("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 S0(e){let t=gr(e.projectRoot);t.some(i=>Ff(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Bt.resolve(n)))]){let n=await Oe(i);n&&r.push({projectRoot:i,paths:await ei(i,n.native.artifact_root),parent:Ff(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function E0(e,t){let r=Bt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await yt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function x0(e,t){let r;try{r=await b0.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=Bt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await yt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function R0(e,t,r){let i=Bt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Bt.sep}`))return null;let n=i.split(Bt.sep).join("/");try{let a=(0,QN.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:B(a.toJS({mapAsMap:!1}))}catch{return null}}function C0(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 XN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Le(e){let t=Bt.join(e.paths.changesDir,e.state.name),r=await cs(t),i=null,n;try{n=await Je({changeDir:t,validation:bt(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 D(e.paths,e.state.name,{diagnostics:!0});if(g){let w=gl(g);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(N=>({...N,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=ea({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===ti){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(!g){let y=e.state.workspace.change_branch??e.state.workspace.target_branch;if(y){let E=await ss({paths:e.paths,parent:e.state.name,targetBranch:y,contract:n.contract});E&&(g=E,await F(e.paths,E))}}if(g){let y=gl(g);return e.state.children_contract_hash!==a||n.drift?{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&y.confirmed}}let w=new Map(n.contract.children.map(y=>[y.name,y])),N=n.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:s&&y.depends_on.every(E=>n.contract.children.filter(({name:b})=>b!==y.name).every(({name:b})=>b!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let y of N){if(y.status!=="ready")continue;w.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let c=await S0(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let w=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await x0(g,l)){let y={...N,source:g,committedState:R0(g,N.file,w)};u.set(N.state.name,[...u.get(N.state.name)??[],y])}for(let N of l){let y=await E0(g,N);y&&d.set(N,[...d.get(N)??[],{source:g,state:y}])}}let p=new Map;for(let g of n.contract.children){let w=(u.get(g.name)??[]).find(({source:E,committedState:b})=>E.parent&&b?.name===g.name&&XN(b,o));if(w){p.set(g.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let N=u.get(g.name)?.[0];if(N){p.set(g.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=d.get(g.name)??[];y.length>1?p.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):y[0]&&p.set(g.name,C0(y[0].state,y[0].source,o))}let h=new Map(n.contract.children.map(g=>[g.name,g])),f=new Map,m=g=>{let w=f.get(g);if(w)return w;let N=h.get(g),E=N.depends_on.map(m).every(({status:P})=>P==="done"),b=p.get(g),x=b?.kind==="active"&&E?N.depends_on.filter(P=>!(u.get(P)??[]).some(({source:_,committedState:j})=>Ff(_.projectRoot,b.projectRoot)&&j?.name===P&&XN(j,o))):[],k,S=b?.message??null;b?.kind==="done"?(k=E?"done":"blocked",E||(S=`Native child ${g} was merged before its dependencies`)):b?.kind==="active"?(k=E&&x.length===0?"active":"blocked",E?x.length>0&&(S=`Native child ${g} does not include merged dependencies: ${x.join(", ")}`):S=`Native child ${g} started before its dependencies merged`):b?.kind==="blocked"?k="blocked":(k=s&&E?"ready":"pending",s||(S="Parent Shape confirmation is required"));let C={name:g,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:k,phase:b?.phase??null,projectRoot:b?.projectRoot??null,message:S};return f.set(g,C),C},v=n.contract.children.map(({name:g})=>m(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")}}jn();Hi();function Re(e,t,r){return e.language==="zh-CN"?r:t}function P0(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:Re(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:Re(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Re(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(Re(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(Re(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"?Re(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Re(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} ${Re(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:Re(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:Re(e,"Accept the result","接受结果"),agentInstruction:Re(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)>=Nr)??!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(Re(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(Re(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 _0(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 A0(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:Re(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Re(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function rk(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Xi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ZN(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function I0(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function ek(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function T0(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function $0(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function cr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:rk({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Xi("summary","--summary"),I0(e.name,e.flag)]}}function tk(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:Re(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function j0(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function wu(e){return[cr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),cr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function O0(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 Y(e,t,r={}){let i=T0(t)&&e.coordination_mode===void 0,n=P0(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:[Xi("summary","--summary")],commandAlternatives:i?il.map(s=>{let c=cr({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,ek("coordination-mode","--coordination-mode",[s])]}}):[cr({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:[Xi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=cr({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]}}):[],cr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...wu({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:[Xi("summary","--summary")],commandAlternatives:[cr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),cr({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:[Xi("summary","--summary")],commandAlternatives:[cr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...wu({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:[Xi("summary","--summary")],commandAlternatives:wu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:wu({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?rk({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:$0({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:f})=>f),acceptance_review:e.acceptance.map(({id:f})=>({id:f,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[ZN()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:f})=>f==="verified");if(s){let f=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}],...f&&f.length>0?{retry_check_ids:[...f]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:f})=>f==="blocked"||f==="needs-reverify"),l=t.children.some(({status:f})=>f==="needs-reverify"),u=t.children.some(({status:f})=>f==="ready"||f==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(f=>f.status==="blocked"&&(f.builderFailureCount??0)>=Nr)??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:Re(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},h=c&&!l&&!u&&p===null;return{...a,disposition:h?"blocked":"continue",action:"advance-children",commandArgs:h?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:h?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:h?[]:p!==null?[p]:[Xi("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=ZN();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} ${Re(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:O0([{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=tk(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>j0(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:tk(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:[ek("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...A0(e)],userCommunication:_0(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[cr({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")}}We();_o();pe();import{createHash as sS,randomUUID as cS}from"node:crypto";import{promises as ur}from"node:fs";import Tr from"node:os";import O from"node:path";We();br();ne();import{createHash as H0}from"node:crypto";import yu from"node:path";var ik=".comet/runtime/native/runner-input-artifacts.json",nk=256,ak=8*1024*1024;function ok(e){return H0("sha256").update(e).digest("hex")}function Qi(e){return process.platform==="win32"?e.toLowerCase():e}function bu(e,t){let r=yu.relative(e,yu.resolve(e,t)).replaceAll("\\","/");return r&&!yu.isAbsolute(r)&&r!==".."&&!r.startsWith("../")?r:null}async function D0(e){try{let t=await nt(e,ik,262144,{label:"Native Runner input registry"}),r=JSON.parse(t.bytes.toString("utf8"));if(!Array.isArray(r)||r.length>nk)throw new Error("Invalid Native Runner input registry");return r.map(i=>{let n=i;if(!n||typeof n.path!="string"||bu(e,n.path)!==n.path||typeof n.digest!="string"||!/^[a-f0-9]{64}$/u.test(n.digest))throw new Error("Invalid Native Runner input artifact");return{path:n.path,digest:n.digest}})}catch{return[]}}function sk(e){try{return new Set(I(e,["ls-files","-z"]).split("\0").filter(Boolean).map(Qi))}catch{return null}}async function ck(e){let t=await D0(e);if(!t.length)return[];let r=sk(e);if(!r)return[];let i=[];for(let n of t)if(!r.has(Qi(n.path)))try{let a=await nt(e,n.path,ak,{label:"Native Runner input artifact"}),o=bu(e,a.realPath);o&&!r.has(Qi(o))&&ok(a.bytes)===n.digest&&i.push({path:o,digest:n.digest})}catch{}return i}async function Mf(e){return new Set((await ck(e)).map(t=>t.path))}async function lk(e){let t=bu(e.paths.projectRoot,e.file);if(!t)return;let r=sk(e.paths.projectRoot);if(!r||r.has(Qi(t)))return;let i=await nt(e.paths.projectRoot,t,ak,{label:"Native Runner input artifact"});e.validateContent(i.bytes.toString("utf8"));let n=bu(e.paths.projectRoot,i.realPath);if(!n||r.has(Qi(n)))return;let a=(await ck(e.paths.projectRoot)).filter(o=>Qi(o.path)!==Qi(n));if(a.length>=nk)throw new Error("Too many retained Native Runner input files; remove unused protocol files before continuing");await fe(yu.join(e.paths.projectRoot,...ik.split("/")),[...a,{path:n,digest:ok(i.bytes)}],{containedRoot:e.paths.runtimeDir})}Fn();vo();at();ni();ji();ko();import{randomUUID as B0}from"node:crypto";var Vf=3,Wf=2;function qe(e){return e.state_version+1}function L0(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function uk(e){return e.map(t=>({...t,result:"pending",reason:null}))}function zf(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function q0(e){return(e??[]).map(t=>({name:J(t.name),result:t.result,note:t.note?J(t.note):null}))}function di(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:J(e.summary),completed_at:e.completedAt}}function dk(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,phase:"build",status:"active",state_version:qe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function pk(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,status:"await-user",state_version:qe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function hk(e){let t=B(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Iy(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let i=L0(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=r.acceptanceReview===void 0?void 0:Tn(r.acceptanceReview);$n(t.acceptance,n);let a=uk(t.acceptance),o=(r.now??new Date).toISOString();return B({...t,phase:"verify",state_version:qe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??B0(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:J(r.summary),addressed_acceptance_ids:i,acceptance_review:n,checks:q0(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>J(s)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:J(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function fk(e){let t=B(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return B({...t,state_version:qe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function F0(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function M0(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Se?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:J(e.response.result.summary),risks:e.response.result.risks.map(t=>J(t)),risks_truncated:!1,completed_at:e.completedAt}}function mk(e){let t=B(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=zf(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=Ty({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:v})=>v),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:v})=>v==="passed").map(({id:v})=>v),requiredChecksPassed:e.checks.every(({status:v})=>v==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(v=>[v.id,v])),o=t.acceptance.map(v=>{let g=a.get(v.id);return g?{...v,result:g.result,reason:J(g.reason)}:v}),s=o.filter(({result:v})=>v==="failed"||v==="blocked").map(({id:v})=>v),c=M0({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){let v=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===Se;return{response:i,state:B({...v,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:qe(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:J("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let v=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...v,status:"await-user",state_version:qe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:J(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=F0(t,s),d=l>=e.maxVerifyFailures,p=u>=3,h=d||p,f=p?"stalled":d?"budget":void 0,m=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...m,phase:h?"verify":"build",status:h?"await-user":"active",state_version:qe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:h?[{owner:"user",reason:J(f==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:J("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:h?"await-user":"repairing",iteration:h?t.loop.iteration:t.loop.iteration+1,attempt:h?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...f===void 0?{}:{stop_reason:f},execution_failure_count:0,previous_unresolved_ids:s,next_action:h?"await-user":"repair-failed-acceptance"}})}}function vk(e){let t=B(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Se||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return B({...t,phase:"archive",status:"active",state_version:qe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function gk(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Se||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=zf(t),n=ke(t,di({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return B({...n,status:"await-user",state_version:qe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:J(e.summary),risks:[J("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:J("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function wk(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=J(e.summary),n=ke(t,di({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return B({...n,phase:"archive",status:"active",state_version:qe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:J(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function yk(e,t){let r=B(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=ke(r,di({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return B({...i,status:"active",state_version:qe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function bk(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Vf,a=ke(t,di({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return B({...a,status:n?"blocked":"active",state_version:qe(t),blockers:n?[{owner:"runtime",reason:J(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Nk(e){let t=B(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=zf(t),a=t.acceptance.some(({result:o})=>o==="passed");return B({...t,status:"active",state_version:qe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function pi(e){let t=B(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=ke(t,di({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?uk(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return n?B({...o,phase:"verify",status:"await-user",state_version:qe(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:J(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):B({...o,phase:"build",status:"active",state_version:qe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ne();jn();import{promises as kk}from"node:fs";import V0 from"node:os";import ds from"node:path";function ls(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function us(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 Fe(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 ta(e,t){return e===null?null:Fe(e,t)}function ra(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 W0(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 z0(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ia(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Gf(e,t){if(e===null)return null;let r=Fe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function G0(e,t){let r=Fe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Jf(e,t){let r=Fe(e,t);if(!ds.isAbsolute(r))throw new Error(`${t} must be absolute`);return ds.resolve(r)}function J0(e,t){let r=`Native local checks[${t}]`,i=ls(e,r);if(us(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)=>Fe(u,`${r}.argv[${d}]`,!0)),a=ia(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Gf(i.startedAt,`${r}.startedAt`),s=Gf(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=ra(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=ls(i.activeProcess,`${r}.activeProcess`),d=ia(u.status,["starting","running"],`${r}.activeProcess.status`);if(us(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:ra(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:Fe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:Fe(i.id,`${r}.id`),name:Fe(i.name,`${r}.name`),operationId:Fe(i.operationId,`${r}.operationId`),status:a,repeatable:z0(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ra(i.executionCount,`${r}.executionCount`),argv:n,cwd:Jf(i.cwd,`${r}.cwd`),exitCode:W0(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Fe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:ia(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:Fe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function Uf(e){let t="Native local execution state",r=ls(e,t);if(us(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==go)throw new Error(`Native local execution schema must be ${go}`);let i=ls(r.workspace,"Native local workspace");us(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ls(r.execution,"Native local execution");us(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Gf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Fe(o.operationId,"Native local execution.operationId"),stage:ia(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ia(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ta(o.executionId,"Native local execution.executionId"),status:ia(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ra(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:G0(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:ra(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:Fe(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(J0);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:go,change:Fe(r.change,"Native local change"),basedOnStateVersion:ra(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:ta(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:ta(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:ta(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:ta(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Jf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Jf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ta(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:Fe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function ae(e){return Uf({schema:go,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:ds.resolve(e.projectRoot),worktreeRoot:ds.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:V0.hostname()},execution:null,checks:[]})}async function Ce(e){let t;try{t=await kk.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 Uf(r)}function Kf(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 Sk(e,t){if(Kf(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}async function M(e,t,r={}){let i=Uf(t);await kk.mkdir(ds.dirname(e),{recursive:!0}),await fe(e,i,r)}async function Nu(e){let t=null,r=null;try{t=await Ce(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=ae(e);return await M(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}ve();ni();ie();async function Yf(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let i=new Array(e.length),n=0,a=async()=>{for(;n<e.length;){let o=n;n+=1,i[o]=await r(e[o],o)}};return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),i}import{promises as Ek}from"node:fs";import ku from"node:path";We();at();ie();var Xf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xk="comet-state.yaml",Rk="state.json";function le(e,t){if(!Xf.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ku.join(e.changesDir,t);if(!Ee(e.changesDir,r))throw new Error("Native change path escaped");return r}function dt(e,t){return ku.join(le(e,t),xk)}function L(e,t){return ku.join(me(e,t),Rk)}async function na(e,t){try{let r=await Ek.readFile(dt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function ge(e){return Yw(e)}function Su(e,t){let r=oe(t);if(!r.isGitWorktree||r.currentBranch===null||wr(t,r.currentBranch)===null)return null;if(!Hc(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}async function H(e,t){return yt(dt(e,t))}async function he(e){let t=await Dn({file:dt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ku.join(le(e.paths,t.name),"verification.md");await G(e.paths.nativeRoot,r),await Ek.rm(r,{force:!0})}return t}async function Qf(e){let t=await H(e.paths,e.name),r=L(e.paths,e.name);try{let i=await Ce(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"}}}import{promises as Tu}from"node:fs";import rn from"node:path";function rm(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var tn=rm();function jk(e){tn=e}var Zi={exec:()=>null};function aa(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 V(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace($e.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var U0=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),$e={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:aa(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:aa(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:aa(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:aa(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:aa(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:aa(e=>new RegExp(`^ {0,${e}}>`))},K0=/^(?:[ \t]*(?:\n|$))+/,Y0=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,X0=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,fs=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Q0=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,im=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ok=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Hk=V(Ok).replace(/bull/g,im).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(),Z0=V(Ok).replace(/bull/g,im).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(),nm=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,eO=/^[^\n]+/,am=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,tO=V(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",am).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),rO=V(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,im).getRegex(),Pu="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",om=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,iO=V("^ {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",om).replace("tag",Pu).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Dk=e=>V(nm).replace("hr",fs).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",Pu).getRegex(),nO=Dk(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),aO=Dk(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),oO=V(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",aO).getRegex(),sm={blockquote:oO,code:Y0,def:tO,fences:X0,heading:Q0,hr:fs,html:iO,lheading:Hk,list:rO,newline:K0,paragraph:nO,table:Zi,text:eO},Ck=V("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",fs).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",Pu).getRegex(),sO={...sm,lheading:Z0,table:Ck,paragraph:V(nm).replace("hr",fs).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ck).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",Pu).getRegex()},cO={...sm,html:V(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",om).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:Zi,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:V(nm).replace("hr",fs).replace("heading",` *#{1,6} *[^
|
|
233
|
+
]`).replace("lheading",Hk).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},lO=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,uO=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Bk=/^( {2,}|\\)\n(?!\s*$)/,dO=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ar=/[\p{P}\p{S}]/u,oa=/[\s\p{P}\p{S}]/u,ms=/[^\s\p{P}\p{S}]/u,pO=V(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,oa).getRegex(),hO=/[\p{Pi}\p{Ps}"']/u,Lk=/(?!~)[\p{P}\p{S}]/u,fO=/(?!~)[\s\p{P}\p{S}]/u,mO=/(?:[^\s\p{P}\p{S}]|~)/u,vO=V(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",U0?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),qk=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,gO=V(qk,"u").replace(/punct/g,Ar).getRegex(),wO=V(qk,"u").replace(/punct/g,Lk).getRegex(),yO=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,bO=V(yO,"u").replace(/openQuote/g,hO).replace(/punct/g,Ar).getRegex(),Fk="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",NO=V(Fk,"gu").replace(/notPunctSpace/g,ms).replace(/punctSpace/g,oa).replace(/punct/g,Ar).getRegex(),kO=V(Fk,"gu").replace(/notPunctSpace/g,mO).replace(/punctSpace/g,fO).replace(/punct/g,Lk).getRegex(),SO="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",EO=V(SO,"gu").replace(/notPunctSpace/g,ms).replace(/punctSpace/g,oa).replace(/punct/g,Ar).getRegex(),xO=V("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ms).replace(/punctSpace/g,oa).replace(/punct/g,Ar).getRegex(),RO="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",CO=V(RO,"gu").replace(/notPunctSpace/g,ms).replace(/punctSpace/g,oa).replace(/punct/g,Ar).getRegex(),PO=V(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ar).getRegex(),_O="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",AO=V(_O,"gu").replace(/notPunctSpace/g,ms).replace(/punctSpace/g,oa).replace(/punct/g,Ar).getRegex(),IO=V(/\\(punct)/,"gu").replace(/punct/g,Ar).getRegex(),TO=V(/^<(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(),$O=V(om).replace("(?:-->|$)","-->").getRegex(),jO=V("^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",$O).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),xu=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,OO=V(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",xu).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Mk=V(/^!?\[(label)\]\[(ref)\]/).replace("label",xu).replace("ref",am).getRegex(),Vk=V(/^!?\[(ref)\](?:\[\])?/).replace("ref",am).getRegex(),HO=V("reflink|nolink(?!\\()","g").replace("reflink",Mk).replace("nolink",Vk).getRegex(),Pk=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,cm={_backpedal:Zi,anyPunctuation:IO,autolink:TO,blockSkip:vO,br:Bk,code:uO,del:Zi,delLDelim:Zi,delRDelim:Zi,emStrongLDelim:gO,emStrongRDelimAst:NO,emStrongRDelimUnd:xO,escape:lO,link:OO,nolink:Vk,punctuation:pO,reflink:Mk,reflinkSearch:HO,tag:jO,text:dO,url:Zi},DO={...cm,emStrongLDelim:bO,emStrongRDelimAst:EO,emStrongRDelimUnd:CO,link:V(/^!?\[(label)\]\((.*?)\)/).replace("label",xu).getRegex(),reflink:V(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",xu).getRegex()},Zf={...cm,emStrongRDelimAst:kO,emStrongLDelim:wO,delLDelim:PO,delRDelim:AO,url:V(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Pk).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:V(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Pk).getRegex()},BO={...Zf,br:V(Bk).replace("{2,}","*").getRegex(),text:V(Zf.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Eu={normal:sm,gfm:sO,pedantic:cO},ps={normal:cm,gfm:Zf,breaks:BO,pedantic:DO},LO={"&":"&","<":"<",">":">",'"':""","'":"'"},_k=e=>LO[e];function lr(e,t){if(t){if($e.escapeTest.test(e))return e.replace($e.escapeReplace,_k)}else if($e.escapeTestNoEncode.test(e))return e.replace($e.escapeReplaceNoEncode,_k);return e}function Ak(e){try{e=encodeURI(e).replace($e.percentDecode,"%")}catch{return null}return e}function Ik(e,t){let r=e.replace($e.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split($e.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace($e.slashPipe,"|");return i}function hi(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 Tk(e){let t=e.split(`
|
|
234
|
+
`),r=t.length-1;for(;r>=0&&$e.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
|
|
235
|
+
`)}function qO(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 FO(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 $k(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 MO(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
|
|
236
|
+
`).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(`
|
|
237
|
+
`)}var Ru=class{options;rules;lexer;constructor(e){this.options=e||tn}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]:Tk(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=MO(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=hi(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:hi(t[0],`
|
|
238
|
+
`),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:hi(t[0],`
|
|
239
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=hi(t[0],`
|
|
240
|
+
`).split(`
|
|
241
|
+
`),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(`
|
|
242
|
+
`),u=l.replace(this.rules.other.blockquoteSetextReplace,`
|
|
243
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
244
|
+
${l}`:l,n=n?`${n}
|
|
245
|
+
${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 h=p,f=r.join(`
|
|
246
|
+
`),m=h.raw+`
|
|
247
|
+
`+f.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(m);a[a.length-1]=v,i=`${i}
|
|
248
|
+
${f}`,n=n.substring(0,n.length-h.text.length)+v.text;break}else if(p?.type==="list"){let h=p,f=h.raw+`
|
|
249
|
+
`+r.join(`
|
|
250
|
+
`),m=this.list(f);a[a.length-1]=m,i=i.substring(0,i.length-p.raw.length)+m.raw,n=n.substring(0,n.length-h.raw.length)+m.raw,r=f.substring(a.at(-1).raw.length).split(`
|
|
251
|
+
`);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=FO(t[2].split(`
|
|
252
|
+
`,1)[0],t[1].length),p=e.split(`
|
|
253
|
+
`,1)[0],h=!d.trim(),f=0;if(this.options.pedantic?(f=2,u=d.trimStart()):h?f=t[1].length+1:(f=d.search(this.rules.other.nonSpaceChar),f=f>4?1:f,u=d.slice(f),f+=t[1].length),h&&this.rules.other.blankLine.test(p)&&(l+=p+`
|
|
254
|
+
`,e=e.substring(p.length+1),c=!0),!c){let m=this.rules.other.nextBulletRegex(f),v=this.rules.other.hrRegex(f),g=this.rules.other.fencesBeginRegex(f),w=this.rules.other.headingBeginRegex(f),N=this.rules.other.htmlBeginRegex(f),y=this.rules.other.blockquoteBeginRegex(f);for(;e;){let E=e.split(`
|
|
255
|
+
`,1)[0],b;if(p=E,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),b=p):b=p.replace(this.rules.other.tabCharGlobal," "),g.test(p)||w.test(p)||N.test(p)||y.test(p)||m.test(p)||v.test(p))break;if(b.search(this.rules.other.nonSpaceChar)>=f||!p.trim())u+=`
|
|
256
|
+
`+b.slice(f);else{if(h||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(d)||w.test(d)||v.test(d))break;u+=`
|
|
257
|
+
`+p}h=!p.trim(),l+=E+`
|
|
258
|
+
`,e=e.substring(E.length+1),d=b.slice(f)}}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=Tk(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:hi(t[0],`
|
|
259
|
+
`),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=Ik(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
260
|
+
`):[],a={type:"table",raw:hi(t[0],`
|
|
261
|
+
`),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(Ik(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:hi(t[0],`
|
|
262
|
+
`),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)===`
|
|
263
|
+
`?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=hi(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=qO(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)),$k(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 $k(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,h=e.slice(0,n+i.index+p+o);if(Math.min(n,o)%2){let m=h.slice(1,-1);return{type:"em",raw:h,text:m,tokens:this.lexer.inlineTokens(m)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}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}}}},pt=class em{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||tn,this.options.tokenizer=this.options.tokenizer||new Ru,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:$e,block:Eu.normal,inline:ps.normal};this.options.pedantic?(r.block=Eu.pedantic,r.inline=ps.pedantic):this.options.gfm&&(r.block=Eu.gfm,this.options.breaks?r.inline=ps.breaks:r.inline=ps.gfm),this.tokenizer.rules=r}static get rules(){return{block:Eu,inline:ps}}static lex(t,r){return new em(r).lex(t)}static lexInline(t,r){return new em(r).inlineTokens(t)}lex(t){t=t.replace($e.carriageReturn,`
|
|
264
|
+
`),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let i=this.inlineQueue[r];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace($e.tabCharGlobal," ").replace($e.spaceLine,""));let n=1/0;for(;t;){if(t.length<n)n=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},t,r))?(t=t.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
|
|
265
|
+
`: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(`
|
|
266
|
+
`)?"":`
|
|
267
|
+
`)+a.raw,s.text+=`
|
|
268
|
+
`+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(`
|
|
269
|
+
`)?"":`
|
|
270
|
+
`)+a.raw,s.text+=`
|
|
271
|
+
`+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(`
|
|
272
|
+
`)?"":`
|
|
273
|
+
`)+a.raw,s.text+=`
|
|
274
|
+
`+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(`
|
|
275
|
+
`)?"":`
|
|
276
|
+
`)+a.raw,s.text+=`
|
|
277
|
+
`+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)}},Cu=class{options;parser;constructor(e){this.options=e||tn}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match($e.notSpaceStart)?.[0],n=e.replace($e.endingNewline,"")+`
|
|
278
|
+
`;return i?'<pre><code class="language-'+lr(i)+'">'+(r?n:lr(n,!0))+`</code></pre>
|
|
279
|
+
`:"<pre><code>"+(r?n:lr(n,!0))+`</code></pre>
|
|
280
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
281
|
+
${this.parser.parse(e)}</blockquote>
|
|
282
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
283
|
+
`}hr(e){return`<hr>
|
|
284
|
+
`}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+`>
|
|
285
|
+
`+i+"</"+n+`>
|
|
286
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
287
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
288
|
+
`}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>
|
|
289
|
+
<thead>
|
|
290
|
+
`+t+`</thead>
|
|
291
|
+
`+i+`</table>
|
|
292
|
+
`}tablerow({text:e}){return`<tr>
|
|
293
|
+
${e}</tr>
|
|
294
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
|
|
295
|
+
`}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>${lr(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=Ak(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+lr(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=Ak(e);if(n===null)return lr(r);e=n;let a=`<img src="${e}" alt="${lr(r)}"`;return t&&(a+=` title="${lr(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:lr(e.text)}},lm=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}},Lt=class tm{options;renderer;textRenderer;constructor(t){this.options=t||tn,this.options.renderer=this.options.renderer||new Cu,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new lm}static parse(t,r){return new tm(r).parse(t)}static parseInline(t,r){return new tm(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}},hs=class{options;block;constructor(e){this.options=e||tn}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?pt.lex:pt.lexInline}provideParser(e=this.block){return e?Lt.parse:Lt.parseInline}},VO=class{defaults=rm();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Lt;Renderer=Cu;TextRenderer=lm;Lexer=pt;Tokenizer=Ru;Hooks=hs;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 Cu(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 Ru(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 hs;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];hs.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&hs.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 pt.lex(e,t??this.defaults)}parser(e,t){return Lt.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?pt.lex:pt.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?Lt.parse:Lt.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?pt.lex:pt.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?Lt.parse:Lt.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+=`
|
|
296
|
+
Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+lr(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},en=new VO;function re(e,t){return en.parse(e,t)}re.options=re.setOptions=function(e){return en.setOptions(e),re.defaults=en.defaults,jk(re.defaults),re};re.getDefaults=rm;re.defaults=tn;function WO(...e){return en.use(...e),re.defaults=en.defaults,jk(re.defaults),re}re.use=WO;re.walkTokens=function(e,t){return en.walkTokens(e,t)};re.parseInline=en.parseInline;re.Parser=Lt;re.parser=Lt.parse;re.Renderer=Cu;re.TextRenderer=lm;re.Lexer=pt;re.lexer=pt.lex;re.Tokenizer=Ru;re.Hooks=hs;re.parse=re;var Iz=re.options,Tz=re.setOptions,$z=re.walkTokens,jz=re.parseInline;var Oz=Lt.parse,Hz=pt.lex;ne();Vi();var dm=fr(Gt(),1);import ws from"path";rt();ne();Vi();gt();ve();ie();Zt();Go();ve();ie();Cn();Qr();var YO=fr(Gt(),1);Cn();Qr();br();br();Rn();ah();Cn();br();var n2=4*1024*1024;import{AsyncLocalStorage as XO}from"node:async_hooks";var QO=new XO;function ZO(){let e=QO.getStore();return e?.active?e:null}function eH(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Wk(e,t){return(...r)=>{let i=ZO();if(i===null)return t(...r);let n=eH(`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}}Rn();var u2=Wk("hookWritePolicy",async e=>(await Kp(e))?.hook??{allow_paths:[]});co();var tH=16*1024;ih();eo();var uG=Number.MAX_SAFE_INTEGER;ne();Jt();var SG={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import sa from"node:path";ne();rt();ve();ie();var vs=/^[a-f0-9]{64}$/u,Gk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,cH=16*1024,BG=process.platform;function lH(e,t){let r=sa.relative(e,t);return sa.isAbsolute(r)||r===".."||r.startsWith(`..${sa.sep}`)?null:r.replaceAll("\\","/")||"."}function Jk(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Uk(e,t){if(e.length===0||Jk(e)||e.includes("\\")||sa.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=sa.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function uH(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 um(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Jk(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function dH(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(um(e.changeBranch,"Native workspace change branch"),um(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 pH(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"||!Gk.test(t.baseCommit)||typeof t.targetCommit!="string"||!Gk.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");um(t.targetBranch,"Native workspace Git target branch")}function hH(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"||!vs.test(String(t.projectRootId))||!vs.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");uH(t.capturedAt),Uk(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&&!vs.test(String(t.projectRootPathId))||a&&!vs.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!vs.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&pH(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(dH(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 fH(e,t){return sa.join(vt(e,t),"workspace.json")}function mH(e,t){let r=fH(e,t),i=Ge(e,r),n=lH(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Uk(n,"Native workspace file ref")}}async function vH(e,t){try{let r=mH(e,t),i=await Z({root:r.root,ref:r.ref,maxBytes:cH});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function gs(e,t){let r=await vH(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(hH(r),r)}Do();Il();Il();var _u=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"},ys=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"},Au=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"},dJ=$l("en");function qt(e,t){Fo(t);let r=ws.join(e.changesDir,t);if(!Ee(e.changesDir,r))throw new Error("Native change path escaped");return r}async function bH(e,t=ws.dirname(e)){let r=ws.relative(t,e).split(ws.sep).join("/"),i=await Z({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,dm.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 Kk(e,t){let r=ws.join(qt(e,t),xr);await G(e.nativeRoot,r);let i=Jh(await bH(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}rt();rr();ie();var pm=["outcome","scope","nonGoals","acceptanceExamples"],Yk=[...pm,"constraints","decisions","openQuestions","verificationExpectations"];var kH=new Set(["nonGoals","decisions","openQuestions"]),ca=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},SH={maxFileBytes:Fp};function EH(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
297
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}function hm(e){return{valid:e.length===0,findings:e}}function fm(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 xH(e){return fm(e).trim()}function Iu(e){let t=xH(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(`
|
|
298
|
+
`).trim()}function RH(e){let t=Iu(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 Xk(e){let t=Iu(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 Qk(e,t){let r=[];return Iu(e).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${t}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:t}):Xk(e)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${t}. Replace it with complete target requirements.`,path:t}),hm(r)}function mm(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 vm(e,t,r={}){let i=[],n;try{n=(await Z({root:e,ref:t,maxBytes:SH.maxFileBytes})).text}catch(s){return hm([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of EH(n))a.set(Tl(s)??s,c);for(let s of r.compact?pm:Yk)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?Yk.filter(s=>!r.compact||a.has(s)):pm;for(let s of o){let c=a.get(s)??"";Iu(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):Xk(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!kH.has(s)&&RH(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return mm(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),hm(i)}rt();pe();ve();Dl();Vh();at();ni();ne();Vi();ji();import{promises as CH}from"node:fs";function Ft(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
299
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Ir(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function PH(e){return e.archived?Xe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Xe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Xe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Xe(e.language,"Verification passed","验收通过")}function _H(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Xe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?PH(e):e.verification_result==="blocked"?Xe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Xe(t,"Failed","未通过"):Xe(t,"Pending","待处理")}function AH(e){if(e.verification?.assurance==="semantic-verification-unavailable")return Xe(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return Xe(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return Xe(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Se?Se:"host-attested"),r=t===Se&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function IH(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=p=>Kh(r,p),n=(p,h)=>Xe(r,p,h),a=e.acceptance.map(p=>`| ${Ir(p.id)} | ${Ir(p.result)} | ${Ir(p.source)} | ${Ir(p.text)} | ${Ir(Ft(p.reason))} |`).join(`
|
|
300
|
+
`),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(p=>{let h=p.argv_display.map(Ft).join(" ");return`| ${Ir(Ft(p.name))} | ${Ir(h||"—")} | ${Ir(p.cwd_ref)} | ${p.status} | ${p.exit_code??"—"} | ${p.duration_ms} ms |`})].join(`
|
|
301
|
+
`),s=e.builder_handoff?[`### ${n("Builder-reported evidence","Builder 报告的证据")}`,"",n("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(p=>`- ${Ft(p.name)}: ${p.result} — ${Ft(p.note)}`),...e.builder_handoff.checks_truncated?[n("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(p=>`- ${n("Known limitation","已知限制")}: ${Ft(p)}`),...e.builder_handoff.known_limits_truncated?[n("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
|
|
302
|
+
`):"",c=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(p=>`- **${p.owner}**: ${Ft(p.reason)}${p.acceptance_ids.length>0?` (acceptance: ${p.acceptance_ids.join(", ")})`:""} — next: \`${p.resolution_action}\``).join(`
|
|
303
|
+
`),l=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(p=>`- ${Ft(p)}`).join(`
|
|
304
|
+
`),u=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(p=>`| ${p.goal_cycle} | ${p.iteration} | ${p.attempt} | ${p.outcome} | ${p.unresolved_ids.join(", ")||"—"} | ${Ir(Ft(p.summary))} | ${p.completed_at} |`)].join(`
|
|
305
|
+
`),d=t?.finalVerification.layers?`
|
|
229
306
|
## ${n("Supervisor evidence layers","Supervisor 分层证据")}
|
|
230
307
|
|
|
231
308
|
- ${n("Child verification","Child 验证")}: ${t.finalVerification.layers.childVerification}
|
|
@@ -241,13 +318,13 @@ generated_from_state_version: ${e.state_version}
|
|
|
241
318
|
|
|
242
319
|
## ${i("currentResult")}
|
|
243
320
|
|
|
244
|
-
- ${n("Result","结果")}: **${
|
|
245
|
-
- ${n("Verification status","验证情况")}: **${
|
|
321
|
+
- ${n("Result","结果")}: **${_H(e)}**
|
|
322
|
+
- ${n("Verification status","验证情况")}: **${AH(e)}**
|
|
246
323
|
- ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
|
|
247
324
|
- ${n("Iteration","迭代")}: ${e.verification.iteration}
|
|
248
325
|
- ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
|
|
249
326
|
- ${n("Completed","完成时间")}: ${e.verification.completed_at}
|
|
250
|
-
- ${n("Summary","摘要")}: ${
|
|
327
|
+
- ${n("Summary","摘要")}: ${Ft(e.verification.summary)}
|
|
251
328
|
|
|
252
329
|
## ${i("acceptance")}
|
|
253
330
|
|
|
@@ -273,38 +350,39 @@ ${l}
|
|
|
273
350
|
|
|
274
351
|
${u}
|
|
275
352
|
|
|
276
|
-
${
|
|
353
|
+
${d}
|
|
277
354
|
|
|
278
355
|
${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into summary","更早的历史记录已折叠到摘要中")}: ${e.history_overflow.dropped_entries}.
|
|
279
356
|
|
|
280
357
|
`:""}## ${i("conclusion")}
|
|
281
358
|
|
|
282
|
-
${
|
|
283
|
-
`}function
|
|
359
|
+
${Ft(e.verification.summary)}
|
|
360
|
+
`}function TH(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Zk(e){let t;try{t=await CH.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=TH(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function fi(e){await mt(e.file,IH(e.state,e.supervisor))}ie();Vi();ui();gt();var wm=fr(Gt(),1);br();var RJ=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 eS=5,$H=600,TJ=256*1024,jH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OH=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var HH=/^[a-f0-9]{64}$/iu;function tS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mi(e,t,r=4096){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string within the association limit`);return e}function gm(e,t){let r=mi(e,t).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a project-relative path`);return r}function DH(e,t){let r=mi(e,t,64).toLowerCase();if(!HH.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function BH(e,t){let r=`Capability association evidence[${t}]`,i=tS(e,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:gm(i.source,`${r}.source`),kind:mi(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:mi(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:mi(i.snippet,`${r}.snippet`,$H)}}}function rS(e){let t=typeof e=="string"?(()=>{if(e.length>65536)throw new Error("Capability association exceeds the size limit");let l=(0,wm.parseDocument)(e,{uniqueKeys:!0});if(l.errors.length>0)throw new Error(l.errors[0].message);return l.toJS({mapAsMap:!1})})():e,r=tS(t,"Capability association"),i=Object.keys(r).filter(l=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(l));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=LH(mi(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((l,u)=>gm(l,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>eS)throw new Error(`Capability association evidence must contain at most ${eS} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let c=r.confidence;if(c!=="high"&&c!=="medium"&&c!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:gm(r.current_spec,"Capability association current_spec"),current_hash:DH(r.current_hash,"Capability association current_hash"),confidence:c,...r.query===void 0?{}:{query:mi(r.query,"Capability association query")},reason:mi(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(BH)}}function LH(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=t==="native"?jH:OH;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return i.join("/")}at();ni();async function la(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...ke(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}kr();var qH=$l("en",{compact:!0}),iS="capability-association.yaml";function $u(e,t=!1){if(t){let i=n=>{if(Array.isArray(n))return n.filter(a=>a?.type!=="space").map(i);if(n&&typeof n=="object"){let a=n;return Object.fromEntries(Object.entries(a).filter(([o])=>o!=="raw"&&!(o==="text"&&Array.isArray(a.tokens))).map(([o,s])=>[o,o==="text"&&a.type==="text"&&typeof s=="string"?s.replace(/[\t ]*\n[\t ]*/gu," "):i(s)]))}return n};return JSON.stringify(i(pt.lex(e.replace(/\r\n?/gu,`
|
|
361
|
+
`))))}let r=e.replace(/\r\n?/gu,`
|
|
284
362
|
`).split(`
|
|
285
|
-
`);for(;
|
|
363
|
+
`);for(;r.length>0&&r.at(-1)?.trim().length===0;)r.pop();return`${r.map(i=>i.replace(/[\t ]+$/gu,"")).join(`
|
|
286
364
|
`)}
|
|
287
|
-
`}function
|
|
365
|
+
`}function FH(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function MH(e){let t=[],r=!1;for(let i of fm(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!FH(n[1]??"")})}function nS(e,t){let r=e.map(({code:i,message:n,path:a})=>`- ${i}${a?` (${a})`:""}: ${n}`).join(`
|
|
288
366
|
`);return[`Native ${t.phase} document checks failed for ${t.change}.`,r,"Recovery: edit the reported formal file in the configured Native change directory, then rerun the latest continuation command. The current state and existing work are preserved; do not edit comet-state.yaml or bypass the Hook."].join(`
|
|
289
|
-
`)}async function fh(e){let t=se(e.paths,e.state.name),r=[...(await lh(t,e.state.brief,{strict:!0})).findings],i="";try{i=(await Q({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:l})=>l!=="remove"),o=e.state.spec_changes.filter(({operation:l})=>l!=="remove"),s=new Set(a.map(({capability:l})=>l));if(e.specChanges!==void 0)for(let l of o)s.has(l.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${l.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${l.capability}/spec.md`});let c=n.length>0&&n.every(({operation:l})=>l==="remove");a.length===0&&o.length===0&&!c&&!F$(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let l of a){let u=`specs/${l.capability}/spec.md`;if(l.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:l.source??u});continue}try{let f=(await Q({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...db(f,u).findings)}catch(f){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${f.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function Gl(e){let t=await fh(e);if(!t.valid)throw new Error(gb(t.findings,{change:e.state.name,phase:e.state.phase}))}function Tt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Ul(e){let t=se(e.paths,e.state.name),r=$i.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await zl.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!rh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=$i.join(t,...s.split("/")),l=await zl.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=$i.join(e.paths.specsDir,o.name,"spec.md"),f="create",d=null;try{let g=await zl.lstat(u);if(!g.isFile()||g.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify",d=ur((await Q({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(g){if(g.code!=="ENOENT")throw g}let p=`specs/${o.name}/${Ww}`,m=$i.join(t,...p.split("/")),h={};try{let g=await zl.lstat(m);if(!g.isFile()||g.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${p}`);let v=await Q({root:t,ref:p,maxBytes:null,includeHash:!1}),w=io(v.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let y=d??ur(""),b=e.state.spec_changes.find(S=>S.capability===o.name);if(b?.delta_source!==void 0){if(b.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==y)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);h={delta_source:p,base_hash:w.base_hash}}catch(g){if(g.code!=="ENOENT")throw g}a.push({capability:o.name,operation:f,source:s,...h})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Kl(e){let t=se(e.paths,e.state.name),r=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(ch(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await Q({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await Q({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),f=io(u.text);c=Uw(s.text,f);let d="";try{d=(await Q({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(p){if(p.code!=="ENOENT")throw p}if(ur(d)===f.base_hash){let p=Yw({baselineMarkdown:d,delta:f,allowAlreadyApplied:!0});if(ur(s.text)!==p.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}l=T("comet.native.shape-artifact-content.v1",Jl(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:T("comet.native.shape-artifact-content.v1",Jl(s.text)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await Q({root:t,ref:vb,maxBytes:65536,includeHash:!1}),s=mb(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let l=$i.relative(e.paths.projectRoot,$i.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll($i.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=T("comet.native.shape-artifact-content.v1",Jl(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:rl({briefMarkdown:r.text,specs:i}),formalHash:T("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:T("comet.native.shape-artifact-content.v1",Jl(r.text))},specs:n,association:{source:vb,contentHash:a}})}}function Yl(e){return T("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function ph(e){return _(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await Ul({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await Gl({paths:e.paths,state:t,specChanges:r});let i=await Kl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Fe({changeDir:se(e.paths,t.name),acceptanceIds:n.map(({id:d})=>d),validation:dt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Hc(e.paths,t.name);let d=Fl(t.workspace,e.paths.projectRoot);if(d===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=ye({...t,workspace:d},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${d.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await _o(se(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let c=s?e.coordinationMode??t.coordination_mode:void 0;if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!s&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let l={...o,spec_changes:r,shape_confirmation_hash:Yl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c})};delete l.children_contract_hash,delete l.coordination_mode,s&&(l.coordination_mode=c);let u=FN({state:l,acceptance:n.map(d=>({...d}))});e.enforceDocumentConstraints===!0&&(u.document_constraints_version=1),a&&(u.children_contract_hash=An({acceptance:u.acceptance,children:a.contract}));let f=await ce({paths:e.paths,previous:t,next:u});return await F(D(e.paths,t.name),re({portableState:f,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function Bo(e){if(e.state.document_constraints_version===1){let l=await fh(e);if(!l.valid){let u=l.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Ul(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let f=e.state.spec_changes[u];return f!==void 0&&l.capability===f.capability&&l.source===f.source&&l.delta_source===f.delta_source&&l.base_hash===f.base_hash&&(l.operation===f.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Kl({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!my(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Fe({changeDir:se(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:dt({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Yl({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?An({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Je(e){let t=await Bo(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await qo({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Lo(e){return _(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:qo({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function qo(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...ye(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}function eu(e,t){let r=j.relative(j.resolve(e),j.resolve(t));if(j.isAbsolute(r)||r===".."||r.startsWith(`..${j.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(j.sep).join("/");return Za(e,i),i}function V$(e){return e.split("\0").some(t=>t.startsWith("160000 "))}function Xl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return vn({id:e.id,name:e.name,executable:r,argv:i,cwdRef:eu(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Sb(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:eu(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function Eb(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||j.resolve(e.workspace.projectRoot)!==j.resolve(r)||j.resolve(e.workspace.worktreeRoot)!==j.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==Zr.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>Xl(o,r)===vn(t[s]))}function wb(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>Xl(i,r)===vn(t[n]))}async function Ql(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await hn(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await hn(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function yb(e){return{...e,execution:e.execution===null?null:{...e.execution,status:"interrupted"},checks:e.checks.map(t=>t.status==="planned"||t.status==="running"?{...t,status:"interrupted",activeProcess:null}:t)}}function Zl(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:Za(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function xb(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return Cb(e,t,r,i)}function Cb(e,t,r,i){return{...Zl(t,r,i),executionCount:e.executionCount}}function Rb(e){return bb("sha256").update(e).digest("hex")}async function Mo(e){let t=await Qt.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=bb("sha256"),i=await Qt.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(M$);for(;;){let{bytesRead:s}=await i.read(o,0,o.length,null);if(s===0)break;n+=s,r.update(o.subarray(0,s).toString("base64"))}}finally{await i.close()}let a=await Qt.lstat(e);if(a.size!==t.size||a.mtimeMs!==t.mtimeMs)throw new Error("Native check input changed while reading");return{digest:r.digest("hex"),size:n}}var Pb=2e4,_b=1024*1024*1024,M$=65535,Ab=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],W$=new Set([".agents",".cache",".claude",".codex",".comet",".git",".idea",".next",".nuxt",".output",".parcel-cache",".svelte-kit",".tmp",".turbo",".vscode",".worktrees","coverage","logs","node_modules","temp","tmp"]),hh=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],Ib=new Set(["comet-state.yaml","children.yaml","verification.md"]);function Bn(e,t){if(!t)return[...hh];let r=j.relative(e,t).replaceAll("\\","/");if(j.isAbsolute(r)||r===".."||r.startsWith("../"))return[...hh];let i=r===""?"":`${r}/`;return[...hh,...["changes","archive"].flatMap(n=>[...Ib].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function mh(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!Ib.has(j.basename(i)))return!1;let n=j.resolve(t,...i.split("/")),a=j.relative(j.resolve(r),n);if(j.isAbsolute(a)||a===".."||a.startsWith(`..${j.sep}`))return!1;let[,o]=a.split(j.sep);return a.startsWith(`comet${j.sep}`)&&(o==="changes"||o==="archive")}function Dn(){return{complete:!1,files:[]}}function z$(e){let t=e==="."?"":`${e}/`;return Ab.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function Tb(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function jb(e,t,r){let i=[...new Set(t.map(({cwdRef:s})=>s))];if(i.length===0)return{complete:!0,files:[]};let n;try{n=[...new Set(I(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...i.flatMap(z$)]).split("\0").filter(Boolean).map(s=>s.replaceAll("\\","/")))].sort()}catch{return Dn()}if(n.length>Pb)return Dn();let a=[],o=0;for(let s of n){if(mh(s,e,r))continue;let c=j.resolve(e,...s.split("/"));if(!be(e,c)||Tb(s))return Dn();try{let l=await Qt.lstat(c);if(!l.isFile()||o+l.size>_b)return Dn();let{digest:u,size:f}=await Mo(c);o+=f,a.push({path:s,digest:u,size:f})}catch{return Dn()}}return{complete:!0,files:a}}async function J$(e,t,r){let i=[...new Set(t.map(({cwdRef:c})=>c))],n=new Map,a=0,o=c=>Ab.includes(c),s=async(c,l,u)=>{let f;try{f=await Qt.readdir(c,{withFileTypes:!0})}catch{return!1}f.sort((d,p)=>d.name.localeCompare(p.name,"en"));for(let d of f){let p=l?`${l}/${d.name}`:d.name;if(mh(p,e,r)||d.isDirectory()&&W$.has(d.name))continue;let m=j.join(c,d.name);if(d.isDirectory()){if(!await s(m,p,u||o(d.name)))return!1;continue}if(u){if(Tb(p)||!d.isFile())return!1;try{let h=await Qt.lstat(m);if(a+h.size>_b)return!1;let{digest:g,size:v}=await Mo(m);if(a+=v,n.set(p,{path:p,digest:g,size:v}),n.size>Pb)return!1}catch{return!1}}}return!0};for(let c of i){let l=Za(e,c);if(!await s(l,c==="."?"":c,o(j.basename(l))))return Dn()}return{complete:!0,files:[...n.values()].sort((c,l)=>c.path.localeCompare(l.path,"en"))}}function vh(e,t){return T("comet.native.local-check-evidence.v1",{id:e.id,name:e.name,status:e.status,repeatable:e.repeatable,timeoutMs:e.timeoutMs,argv:e.argv,cwd:j.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:Rb(t)})}async function G$(e){let t={complete:!0,capture:"git",head:null,branch:null,status:null,diff:null,stagedDiff:null,submodules:null,untracked:[],ignored:{complete:!0,files:[]},physical:{complete:!0,files:[]},reuseNonce:null},r=!1;try{t.head=I(e.projectRoot,["rev-parse","HEAD"]),r=!0,t.branch=I(e.projectRoot,["branch","--show-current"]),t.status=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);let i=I(e.projectRoot,["diff","--name-only","-z","HEAD","--",...Bn(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.diff=await th(i,4,async o=>{let s=j.resolve(e.projectRoot,...o.split("/"));try{let{digest:c}=await Mo(s);return{path:o,digest:c}}catch{return{path:o,digest:null}}}),t.diff.some(({digest:o})=>o===null)&&(t.complete=!1);let n=I(e.projectRoot,["ls-files","--stage","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);t.stagedDiff=Rb(n),t.submodules=V$(n)?I(e.projectRoot,["submodule","status","--recursive"]):"";let a=I(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.untracked=await th(a,4,async o=>{let s=j.resolve(e.projectRoot,...o.split("/"));try{let{digest:c,size:l}=await Mo(s);return{path:o,digest:c,size:l}}catch{return{path:o,digest:null,size:null}}}),t.untracked.some(({digest:o})=>o===null)&&(t.complete=!1),t.ignored=await jb(e.projectRoot,e.plans,e.managedArtifactRoot),t.ignored.complete||(t.complete=!1)}catch{r?t.complete=!1:(t.capture="physical-tree",t.physical=await J$(e.projectRoot,e.plans,e.managedArtifactRoot),t.complete=t.physical.complete)}return T("comet.native.check-input.v1",{candidateId:e.state.builder_handoff?.candidate_id??null,shapeConfirmationHash:e.state.shape_confirmation_hash??null,acceptance:e.state.acceptance.map(({id:i,source:n,text:a})=>({id:i,source:n,text:a})),git:t,projectRoot:j.resolve(e.projectRoot),machineId:Zr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,path:process.env.PATH??null,pathext:process.env.PATHEXT??null,boundEnvironment:Object.entries(process.env).filter(([i])=>$b.has(i.toUpperCase())).map(([i,n])=>[i,n??null]).sort(([i],[n])=>i.localeCompare(n))})}var $b=new Set(["PATH","PATHEXT","NODE_OPTIONS","NODE_ENV","NODE_PATH","LANG","LC_ALL","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","SHELL","TMPDIR","TEMP","TMP","HTTP_PROXY","HTTPS_PROXY","NO_PROXY"]);function U$(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function K$(){return Object.entries(process.env).filter(([e])=>$b.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function Nb(e){try{let t=I(e.projectRoot,["rev-parse","HEAD"]),r=I(e.projectRoot,["branch","--show-current"]),i=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...Bn(e.projectRoot,e.managedArtifactRoot)]),n=I(e.projectRoot,["ls-files","--stage","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);if(t===null||i===null)return null;let a=[];for(let s of ka(e.projectRoot).filter(c=>!mh(c,e.projectRoot,e.managedArtifactRoot))){let c=j.resolve(e.projectRoot,...s.split("/")),l=null;try{l=(await Mo(c)).digest}catch{return null}a.push({path:s,digest:l})}a.sort((s,c)=>s.path.localeCompare(c.path,"en"));let o=await jb(e.projectRoot,e.plans??[],e.managedArtifactRoot);return o.complete?T("comet.native.check-input-gate.v1",{candidateId:e.candidateId,head:t,branch:r,status:i,staged:n,workingTree:a,ignored:o,projectRoot:j.resolve(e.projectRoot),machineId:Zr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:K$()}):null}catch{return null}}function ei(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);if(r.status==="passed"&&(r.evidence!=="runtime"||!r.evidenceDigest))throw new Error(`Native Runtime check ${r.id} has no Runtime execution evidence`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:J(i),argv_display:eo(r.argv.slice(1)).map(n=>J(n)),argv_truncated:!1,cwd_ref:eu(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:U$(r)}})}function Y$(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Oi(e){if(e.local===null||e.local.change!==e.state.name)return re({portableState:e.state,projectRoot:e.projectRoot,branch:ve(e.projectRoot)});let t=e.local.execution?.operationId??kb();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function ti(e){try{let t=await Se(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}async function Wo(e){let t=await ti({paths:e.paths,state:e.state}),r=KN({state:e.state,summary:e.summary}),i=await ce({paths:e.paths,previous:e.state,next:r});return await F(D(e.paths,e.state.name),Oi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function X$(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await z(t,j.resolve(t,...r.log.split(/[\\/]/u)));if(!(await Qt.stat(i)).isFile())return!1;let n=await Qt.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==vh(r,n))return!1}catch{return!1}}return!0}async function Q$(e){return _(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Je({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=ve(e.projectRoot),i=D(e.paths,t.name),n=(await Ll({file:i,portableState:t,projectRoot:e.projectRoot,branch:r,containedRoot:e.paths.runtimeDir})).state,a=await Nb({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),o=await Nb({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:[],managedArtifactRoot:e.paths.artifactRoot}),s=a===null,l=a!==null&&n.inputFingerprint!==null&&n.inputFingerprintGate===a&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.machineId===Zr.hostname()?n.inputFingerprint:await G$({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),u=pe(e.paths,t.name),f=await X$(n,u),d=n.checks.every(k=>k.status==="passed"),p=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),m=n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname()&&n.inputFingerprint===l,h=o!==null&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname(),g=h&&n.inputFingerprint!==null&&n.inputFingerprint!==l,v=Eb(n,e.plans,e.projectRoot,t,l,r)||h&&wb(n,e.plans,e.projectRoot),w=n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname(),y=m&&d&&!f;if(p&&p.size===0)throw new Error("Native check retry list must contain at least one ID");if(!m&&n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&n.execution.status==="running"){let k=await Ql(n);if(k!=="orphaned")throw new Error(k==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before changing its binding":"Native check plan is already in progress on another workspace binding");n=yb(n),await F(i,n,{containedRoot:e.paths.runtimeDir})}if(!m&&w&&n.inputFingerprint!==null&&(n.execution!==null||n.checks.length>0)){let k=n.inputFingerprint!==l;if(!(s&&!k||g)){let E=Yr({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),C=await ce({paths:e.paths,previous:t,next:E});throw await F(i,re({portableState:C,projectRoot:e.paths.projectRoot,branch:r}),{containedRoot:e.paths.runtimeDir}),new Error("Native check input changed after the candidate was built; the change returned to Build for a new candidate")}}if(!m&&!h){let k=re({portableState:t,projectRoot:e.projectRoot,branch:r});await F(i,k,{containedRoot:e.paths.runtimeDir}),n=k}let b=wb(n,e.plans,e.projectRoot);if(n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&b&&v){let k=n.execution;if(k.status==="running"){let C=await Ql(n);if(C!=="orphaned")throw new Error(C==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before retrying":"Native check plan is already in progress");n=yb(n),await F(i,n,{containedRoot:e.paths.runtimeDir}),k=n.execution}let E=n.checks.filter(C=>C.status==="interrupted");if(E.length===0&&k.status==="completed"&&d&&!y&&!g){let C=new Map(e.plans.map(({id:H,name:P})=>[H,P]));return{kind:"reuse",state:t,checks:ei({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:C})}}if(E.length===0&&k.status==="completed"&&!d&&!y&&!g)throw new Error(`Native check plan contains a failed check (${n.checks.filter(({status:C})=>C==="failed").map(({id:C})=>C).join(", ")}); submit a new Builder candidate`);if(E.length>0&&E.some(C=>!C.repeatable)&&!y){let C=Yr({state:t,reason:`A non-repeatable Runtime check was interrupted (${E.filter(P=>!P.repeatable).map(({id:P})=>P).join(", ")}); a new Builder candidate is required before it can run again.`}),H=await ce({paths:e.paths,previous:t,next:C});throw await F(D(e.paths,t.name),re({portableState:H,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${E.find(P=>!P.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(E.length>0&&p===null&&!y&&!g){let C=new Map(e.plans.map(({id:H,name:P})=>[H,P]));return{kind:"reuse",state:t,checks:ei({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:C})}}if(p){let C=[...p].filter(P=>!E.some(W=>W.id===P));if(C.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${C.join(", ")}`);let H=E.filter(P=>p.has(P.id)&&P.executionCount>=3);if(H.length>0)throw new Error(`Native check retry limit (3) reached: ${H.map(({id:P})=>P).join(", ")}`)}}if(n.execution!==null&&n.checks.length>0){if(!(n.execution.stage==="checking"&&n.execution.actor==="runtime"&&n.checks.some(E=>E.status==="interrupted")&&b)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan")}else if((n.execution!==null||n.checks.length>0)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan");let S=kb(),N=await Ke(process.pid),x={...n,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:l,inputFingerprintGate:a,candidateInputFingerprintGate:o,workspace:{...n.workspace,projectRoot:j.resolve(e.projectRoot),worktreeRoot:j.resolve(e.projectRoot),branch:ve(e.projectRoot),machineId:Zr.hostname()},execution:{operationId:S,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...N?{ownerIdentity:N}:{}},checks:e.plans.map(k=>{let E=n.checks.find(C=>C.id===k.id);return g&&E?Zl(k,S,e.projectRoot):y&&E?Cb(E,k,S,e.projectRoot):E?.status==="interrupted"&&(p===null||p.has(E.id))?xb(E,k,S,e.projectRoot):E?{...E,operationId:S,activeProcess:null}:Zl(k,S,e.projectRoot)})};return await F(i,x,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:x,plans:e.plans.filter(k=>{let E=n.checks.find(C=>C.id===k.id);return y||g||E===void 0||E.status==="interrupted"&&(p===null||p.has(E.id))})}})}async function Fo(e){return _(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await $(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await Se(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await F(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function zo(e){let t=e.projectRoot??e.paths.projectRoot;Ye(t,e.plans);let r=[],i=new Set;for(let c of e.plans){to(t,c);let l=vn(c);i.has(l)||(i.add(l),r.push(c))}let n=await Q$({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=pe(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Fo({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(p=>p.id===c.id?{...p,status:"running",executionCount:p.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:p)})});let u=await Ni({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:d})=>{let p=await Ke(d);await Fo({paths:e.paths,state:n.state,operationId:a,update:m=>({...m,checks:m.checks.map(h=>h.id===c.id?{...h,activeProcess:{status:"running",pid:d,...p?{identity:p}:{}}}:h)})})}}),f=await Qt.readFile(j.resolve(o,...u.logRef.split("/")),"utf8");await Fo({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(p=>{if(p.id!==c.id)return p;let m={...p,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...m,evidenceDigest:vh(m,f)}})})})}await Fo({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Fo({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted",activeProcess:null}:u)})})}catch{}throw c}let s=await Se(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:ei({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function gh(e){if(e.checkIds.length===0)throw new Error("Native check retry list must contain at least one ID");let t=e.projectRoot??e.paths.projectRoot,r=await $(e.paths,e.name);if(r.phase!=="verify"||r.status!=="active"||r.loop.stage!=="verify-ready"||r.builder_handoff===null)throw new Error("Native check retry requires an active Verify-ready candidate");let i=await Se(D(e.paths,e.name));if(i===null||i.change!==r.name||i.basedOnStateVersion!==r.state_version||i.execution===null||i.execution.stage!=="checking"||i.execution.actor!=="runtime")throw new Error("Native check retry has no current Runtime check execution");let n=new Set(e.checkIds);if(n.size!==e.checkIds.length)throw new Error("Native check retry list contains duplicate IDs");let a=i.checks.filter(c=>n.has(c.id)),o=e.checkIds.filter(c=>!a.some(l=>l.id===c));if(o.length>0)throw new Error(`Native check retry IDs are unknown: ${o.join(", ")}`);for(let c of a){if(c.status!=="interrupted")throw new Error(`Native check ${c.id} is not interrupted and cannot be retried`);if(!c.repeatable)throw new Error(`Native check ${c.id} is not repeatable and cannot be retried`);if(c.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${c.id}`)}let s=i.checks.map(c=>{let[l,...u]=c.argv;if(!l)throw new Error(`Native local check ${c.id} has no executable`);return{id:c.id,name:c.name,executable:l,argv:u,cwdRef:eu(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return zo({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function Ob(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Yp)throw new Error(`Native Verifier request-checks exceeded ${Yp} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let m=Xl(p,e.projectRoot);n.set(m,p),p.status!=="interrupted"&&i.set(m,p),a.set(p.id,m)}let o=new Map,s=new Map;for(let p of e.response.checks){let m=Y$(p);to(e.projectRoot,m);let h=vn(m),g=s.get(m.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let v=a.get(m.id);if(v!==void 0&&v!==h)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);if(w?.status==="interrupted"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(h)||o.set(h,m)}Ye(e.projectRoot,[...o.values()]);let c=[...o.entries()],l=c.filter(([p])=>!i.has(p));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=r.execution.requestCheckRounds+1,f=new Map(c.map(([,p])=>[p.id,p.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(p=>{let m=Xl(p,e.projectRoot),h=o.get(m);return h&&p.status==="interrupted"?xb(p,h,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Zl(p,r.execution.operationId,e.projectRoot))]};return await F(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,p])=>p),requestedNames:f,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function Vo(e){return _(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await $(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await Se(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await F(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Hb(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await Vo({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>c.id===r.id?{...c,status:"running",executionCount:c.executionCount+1,startedAt:i,activeProcess:{status:"starting"}}:c)})});let n=pe(e.paths,e.reservation.state.name),a=await Ni({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await Ke(s);await Vo({paths:e.paths,reservation:e.reservation,update:l=>({...l,checks:l.checks.map(u=>u.id===r.id?{...u,activeProcess:{status:"running",pid:s,...c?{identity:c}:{}}}:u)})})}}),o=await Qt.readFile(await z(n,j.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await Vo({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>{if(c.id!==r.id)return c;let l={...c,status:a.status,exitCode:a.exitCode,startedAt:a.startedAt,completedAt:a.completedAt,log:a.logRef,activeProcess:null,evidence:"runtime"};return{...l,evidenceDigest:vh(l,o)}})})})}t=await Vo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await Vo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted",activeProcess:null}:n)})})}catch{}throw r}return{checks:ei({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}ne();Bc();rt();import{accessSync as yJ,constants as NJ,promises as qb}from"node:fs";import Mb from"node:path";st();le();st();le();gi();lr();ut();Fr();async function wh(e){return _(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await Je({paths:e.paths,state:t});let r=await Ul({paths:e.paths,state:t}),i=await Kl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Fe({changeDir:se(e.paths,t.name),acceptanceIds:n.map(({id:v})=>v),validation:dt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Hc(e.paths,t.name);let v=Fl(t.workspace,e.paths.projectRoot);if(v===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=ye({...t,workspace:v},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${v.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await _o(se(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,c=t.coordination_mode;if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let l=Yl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let v=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await qo({paths:e.paths,state:t,reason:v,keepFailureBudget:!0}),new Error(`${v}; Native change returned to Shape and requires confirmation`)}let u=qN({state:{...o,spec_changes:r},acceptance:n.map(v=>({...v}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=An({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let v=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(v?.outcome==="fail"&&v.unresolved_ids.length>0){let w=await je({paths:e.paths,state:u}),y=new Map((w?.children??[]).map(({name:N,status:x})=>[N,x])),b=new Set(a.contract.children.filter(({name:N})=>{let x=y.get(N);return x!=="done"&&x!=="integrated"&&x!=="archived"}).flatMap(({covers:N})=>N)),S=v.unresolved_ids.filter(N=>!b.has(N));if(S.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${S.join(", ")}`)}}let f=null,d=a?.contract.schema==="comet.native.children.v2"?await O(e.paths,t.name):null,p=null,m=null;if(a?.contract.schema==="comet.native.children.v2"){if(p=o.workspace.change_branch??o.workspace.target_branch,!p)throw new Error("Native Supervisor v2 requires a target branch");if(m=ar(e.paths.projectRoot,p),!m)throw new Error(`Native Supervisor target branch has no commit: ${p}`);d||(d=await Po({paths:e.paths,parent:t.name,targetBranch:p,contract:a.contract})),d||(f=await zp({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:p,sourceConfig:await _e(e.paths.projectRoot)}))}let h=a?.contract.schema==="comet.native.children.v2"&&p&&m?d?_f({state:d,contract:a.contract}):f?Ja({parent:u.name,targetBranch:p,targetCommit:m,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!h)throw new Error("Native Supervisor integration state is unavailable");let g=await ce({paths:e.paths,previous:t,next:u});return await F(D(e.paths,t.name),re({portableState:g,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),h&&await q(e.paths,h),g})}import{randomUUID as Z$}from"node:crypto";import tu from"node:path";le();Ma();mi();function Db(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function eO(e){let{state:t,local:r,envelope:i}=e;if(!Ac(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function tO(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function yh(e){return _(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Je({paths:e.paths,state:t}),await Fe({changeDir:se(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:dt(t)})||t.children_contract_hash){let a=await je({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=VN({state:t,input:e.input}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Nh(e){return _(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Je({paths:e.paths,state:t});let i=(await Ll({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:ve(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");ei({local:i,projectRoot:r,supplied:e.checks});let n=MN(t),a=await ce({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Z$();return await F(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function bh(e){return _(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier start confirmation requires an active Verifier attempt");let r=D(e.paths,e.name),i=await Se(r),n=i?.execution;if(i===null||i.change!==t.name||i.basedOnStateVersion!==t.state_version||!n||n.stage!=="verifying"||n.actor!=="verifier"||n.status!=="running"||n.executionId===null||n.executionId!==e.verifierExecutionRef)throw new Error("Native Verifier start confirmation is stale for the current attempt");if(t.builder_handoff?.candidate_id!==e.candidateId)throw new Error("Native Verifier start confirmation is stale for the current candidate");return n.verifierStartedAt===void 0&&await F(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function kh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await _(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await $(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Je({paths:e.paths,state:r});let n=await ti({paths:e.paths,state:r}),a=eO({state:r,local:n,envelope:e.envelope}),o;try{o=Va(a.payload)}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,p=await Wo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${Ao} was recorded`,{cause:f})}let s=tO(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=ei({local:n,projectRoot:i,supplied:e.checks}));let f=WN({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(f.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Ob({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:f.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:f.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=f}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,p=await Wo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${Ao} was recorded`,{cause:f})}let u=await ce({paths:e.paths,previous:r,next:l.state});return await F(D(e.paths,r.name),u.loop.next_action==="resolve-verifier-blocker"||u.loop.next_action==="run-final-full-verification"?Oi({local:n,state:u,projectRoot:i}):re({portableState:u,projectRoot:i,branch:ve(i)}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await Xr({file:tu.join(se(e.paths,r.name),"verification.md"),state:u}),{kind:"final-result",result:{state:u,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await Hb({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await _(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await $(e.paths,e.name);return a.state_version!==t.state.state_version?null:Wo({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Ao} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Sh(e){return _(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=await ti({paths:e.paths,state:t});if(Db({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Wo({paths:e.paths,state:t,summary:e.summary})})}async function Eh(e){return _(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);await Je({paths:e.paths,state:t});let r=await ti({paths:e.paths,state:t}),i=Db({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=ei({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=JN({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await ce({paths:e.paths,previous:t,next:a});return await F(D(e.paths,t.name),Oi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tu.join(se(e.paths,t.name),"verification.md"),state:o}),o})}async function xh(e){return _(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Je({paths:e.paths,state:t});let r=GN({state:t,summary:e.summary}),i=await ce({paths:e.paths,previous:t,next:r});return await F(D(e.paths,t.name),re({portableState:i,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tu.join(se(e.paths,t.name),"verification.md"),state:i}),i})}async function Ch(e){return _(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Je({paths:e.paths,state:t});let r=await ti({paths:e.paths,state:t}),i=UN(t,{reason:e.reason}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),Oi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Rh(e){return _(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await ti({paths:e.paths,state:t}),i=YN(t),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),Oi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Hi(e){return _(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks?await ti({paths:e.paths,state:t}):null,i=Yr({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),e.preserveLocalChecks?Oi({local:r,state:n,projectRoot:e.paths.projectRoot}):re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Jo(e){if(e.state.verification===null)return"not-applicable";let t=tu.join(se(e.paths,e.state.name),"verification.md");return await fb({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Xr({file:t,state:e.state}),"rebuilt")}import rO from"node:path";lr();le();async function Ph(e){return _(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Je({paths:e.paths,state:t});let r=await O(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Ii(r).stateVersion!==r.stateVersion)return Hn({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await q(e.paths,Ti(r,t))}let i=zN(t),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Xr({file:rO.join(se(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as Bb}from"node:fs";lr();le();cl();async function Go(e){let t=await $(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await je({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function Lb(e){let t=await $(e.paths,e.name),r=await sl(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await O(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await Bb.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Ii(n);if(i||a.stateVersion!==n.stateVersion){let o=await Hn({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await Bb.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await q(e.paths,Ti(n,t)),{state:t,action:"recorded-final-verification"}}async function ru(e){return _(e.paths,`recover Supervisor final verification ${e.name}`,()=>Lb(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}var uJ=16*1024;kn();Bc();var Fb="comet.native.workspace-finish.v1",iO="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Wb=new RegExp(`^${iO}$`,"u"),nO=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function aO(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==Fb||typeof t.name!="string"||!Wb.test(t.name)||typeof t.transactionId!="string"||!nO.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Mb.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:Fb,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function oO(e,t){if(!Wb.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Mb.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function zb(e,t,r={}){let i=oO(e,t);try{let n=await qb.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=aO(JSON.parse(await qb.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}}import{randomUUID as sO}from"node:crypto";import{promises as Uo}from"node:fs";import cO from"node:path";ne();nt();le();lp();cl();il();ut();te();var Jb=["evidence.md","repair.md","archive.md","checkpoint.md"],lO="verification.md";async function uO(e,t){let r=await sl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Gb(e,t){await Uo.mkdir(e.transactionsDir,{recursive:!0}),await we(ol(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Ub(e,t,r={}){let i=r.removeVerificationReport===!1?Jb:[...Jb,lO];await Promise.all([Uo.rm(pe(e,t),{recursive:!0,force:!0}),Uo.rm(gf(e,t),{recursive:!0,force:!0}),...i.map(n=>Uo.rm(cO.join(At(e,t),n),{force:!0}))])}async function Kb(e,t){await F(D(e,t.name),re({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Yb(e,t){try{let r=await Oo(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Xb(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ie(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function dO(e){let t=At(e.paths,e.state.name),r=await Q({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return rl({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Qb(e,t){let r=await sb(e,t);if(r.status==="runtime-incompatible")throw new Vt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Zb(e){return _(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await uO(e.paths,e.name),r=await $n(e.paths,e.name)?await lt(Qe(e.paths,e.name)):null;if(!t&&r)return await Ub(e.paths,e.name,{removeVerificationReport:!1}),await Kb(e.paths,r),r;let i=null,n=null;for(t||(i=await Qb(e.paths,e.name),n=await Yb(e.paths,e.name),Xb(e.paths,n),t={schema:nl,id:sO(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Gb(e.paths,t));;){let a=gy(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Qb(e.paths,e.name),n??=await Yb(e.paths,e.name),Xb(e.paths,n),r=vy({state:i,acceptance:await dO({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await La(Qe(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Ub(e.paths,e.name):a.action==="commit-transaction"&&(r??=await lt(Qe(e.paths,e.name)),await Kb(e.paths,r)),t={...t,status:a.nextStatus},await Gb(e.paths,t)}return await Uo.rm(ol(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??lt(Qe(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as tk}from"node:fs";import rk from"node:path";le();import{promises as _h}from"node:fs";import fO from"node:path";fe();var pO=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),hO=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),mO=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),vO=new Set(["status","summary"]);function iu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function nu(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 gO(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Di(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function wO(e,t,r,i){let n=iu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=nu(n,pO,"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=iu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=nu(o,hO,"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=iu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=nu(c,vO,"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,f]of n.children.entries()){let d=iu(f,`Native Supervisor child ${u}`);if(!d)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:m,...h}=d,g=nu(h,mO,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(g)return g;let v=r.children[u],w=v.covers.length>0?v.covers.map(b=>({id:b,source:r.acceptance_index?.[b]?.source??"brief.md",text:r.acceptance_index?.[b]?.text??b})):[{id:`child:${v.name}`,source:"children.yaml",text:v.summary??v.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(w)||m!==void 0&&m!==T("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${v.name} acceptance scope does not match the legacy contract`;if(d.name!==v.name||d.summary!==v.summary||!gO(d.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let y=v.depends_on.length===0?"ready":"pending";if(d.status!==y)return`Native Supervisor child ${v.name} has progressed beyond its initial ${y} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if((d.builderFailureCount??0)!==0)return`Native Supervisor child ${v.name} contains Builder failure progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function qn(e){let t=wi(e.paths,e.state.name),r;try{let c=await _h.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Di(t,"","Native Supervisor overlay is not a regular file");r=await _h.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Di(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Di(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=fO.join(e.paths.changesDir,e.state.name),a;try{a=await Fe({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Di(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 O(e.paths,e.state.name)}catch(c){return Di(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Di(t,r,"Native Supervisor overlay disappeared during inspection");let s=wO(i,e.state,a.contract,o);return s?Di(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}}async function ek(e){let t=await qn({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await _h.rm(t.file,{force:!1})}ut();Fr();function Ah(e,t){let r=ie(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function yO(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function NO(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:ye(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(t),completed_at:i});return B({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?yO(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function bO(e){try{let t=await Se(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Ih(e){return _(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(t.status==="done")return await Jo({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Ah(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await qn({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await ek({paths:e.paths,state:t,expected:i}),n=!0);let a=D(e.paths,e.name),o=await bO(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,c=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(c&&o.local?.execution?.status==="running"){let h=o.local.execution,g=await Ql(o.local),v=h.stage==="verifying"&&h.actor==="verifier"&&h.executionId!==null,w=g==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&h.stage==="checking"&&h.actor==="runtime";if(v||g!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:v?h.verifierStartedAt===void 0&&h.requestCheckRounds===0?`Native Verifier execution ${h.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${h.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:g==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(c&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(h=>h.status==="planned"||h.status==="running"?{...h,status:"interrupted"}:h)},await F(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Jo({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(h=>h.status==="interrupted"&&!h.repeatable):void 0;if(l){let h=Yr({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await dn({file:Qe(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot}),await tk.rm(rk.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let g=re({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await F(a,g,{containedRoot:e.paths.runtimeDir}),{state:t,local:g,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",f=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=u||f;if(d){let h=NO(t,f?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",f);t=await dn({file:Qe(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot})}let p=re({portableState:t,projectRoot:e.paths.projectRoot,branch:ie(e.paths.projectRoot).currentBranch});await tk.mkdir(rk.dirname(D(e.paths,t.name)),{recursive:!0}),await F(a,p,{containedRoot:e.paths.runtimeDir}),await Jo({paths:e.paths,state:t});let m=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:p,action:d?"reverify":"resume-stable-boundary",reason:s,message:m??(d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`)}})}import ik from"node:path";function nk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function xe(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:nk(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:nk(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=>ik.relative(t.projectRoot,ik.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}_c();function Th(e){return e.charCodeAt(0)===65279?e.slice(1):e}kn();rt();import{randomUUID as dk}from"node:crypto";import{promises as ak}from"node:fs";import Ko from"node:path";gn();Wp();Ma();le();mi();function Mn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function V(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Fn(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>V(r,`${t}[${i}]`))}function kO(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Mn(t,`Native Builder check ${r}`);if(ee(i,["name","result","note"],`Native Builder check ${r}`,`/checks/${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:V(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function au(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Mn(t,`Native Runtime check ${r}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`,`/checks/${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:V(i.id,`Native Runtime check ${r} id`),name:V(i.name,`Native Runtime check ${r} name`),executable:V(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:V(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function ok(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:V(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function SO(e){let t=Mn(e,"Native Supervisor evidence");return ee(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:V(t.summary,"Native Supervisor evidence summary"),checks:Fn(t.checks,"Native Supervisor evidence checks"),acceptance:Tc(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:V(t.receiptRef,"Native Supervisor receipt ref")}}}function EO(e){let t=Mn(e,"Native Runner input");if(t.kind==="builder-handoff"){let r=["kind","summary","addressed_acceptance_ids","checks","known_limits"];Object.hasOwn(t,"verification_checks")&&r.push("verification_checks"),ee(t,Object.hasOwn(t,"review")?[...r,"review"]:r,"Native Runner Builder input");let i=null;if(t.review!==void 0&&t.review!==null){let n=Mn(t.review,"Native Builder review");if(ee(n,["status","summary","reviewer_execution_ref"],"Native Builder review","/review"),n.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");i={status:"passed",summary:V(n.summary,"Native Builder review summary"),reviewer_execution_ref:V(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:V(t.summary,"Native Builder summary"),addressed_acceptance_ids:Fn(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:kO(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:au(t.verification_checks)}:{},known_limits:Fn(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return ee(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:au(t.checks)};if(t.kind==="retry-checks")return ee(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:Fn(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return ee(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:V(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:V(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:Va(t.response,"/response")};if(t.kind==="verifier-started")return ee(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:V(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:V(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:V(t.summary,"Native Verifier execution error summary"),...ok(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:V(t.summary,"Native unavailable Verifier summary"),...ok(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ee(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),candidateCommit:V(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ee(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),reason:V(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(ee(t,["kind","child","stateVersion"],"Native Supervisor Builder retry input"),!Number.isSafeInteger(t.stateVersion)||t.stateVersion<1)throw new Error("Native Supervisor Builder retry stateVersion is invalid");return{kind:"supervisor-retry-builder",child:V(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return ee(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ee(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),reason:V(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ee(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:SO(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),checks:au(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Fn(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=Mn(i,"Native Supervisor material");return ee(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:V(a.name,"Native Supervisor material name"),content:V(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:V(t.child,"Native Supervisor child"),checks:au(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Fn(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function Hh(e,t){let r=Ko.resolve(t,e),i=await ak.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(Th(await ak.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return EO(n)}function xO(e){return e.kind==="builder-handoff"||e.kind==="dispatch-verifier"||e.kind==="retry-checks"||e.kind==="verifier-response"||e.kind==="verifier-started"||e.kind==="verifier-execution-error"||e.kind==="verifier-unavailable"}function CO(e){return e.kind.startsWith("supervisor-")}function RO(e){return e.response.kind!=="request-checks"?[]:e.response.checks.map(({id:t,name:r,executable:i,argv:n,cwdRef:a,timeoutMs:o,repeatable:s})=>({id:t,name:r,executable:i,argv:[...n],cwdRef:a,timeoutMs:o,repeatable:s}))}function sk(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.stage!=="verify-ready")throw new Error("Native Runner check input requires an active Verify-ready candidate")}function jh(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result")throw new Error("Native Runner Verifier input requires an active Verifier attempt")}function PO(e,t){if(new Set(t).size!==t.length)throw new Error("Native Builder addressed acceptance IDs contain duplicates");let r=new Set(e.acceptance.map(({id:n})=>n)),i=t.filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native Builder addressed acceptance IDs contain unknown IDs: ${i.join(", ")}`)}async function $h(e){let t=await Se(D(e.paths,e.state.name)),r=t?.execution;if(t===null||t.basedOnStateVersion!==e.state.state_version||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null)throw new Error("Native Runner Verifier input requires an active Runtime Verifier execution");return r}async function Dh(e){let t=await qn({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await O(e.paths,e.name),i=r!==null&&e.state.phase==="verify"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),n=r!==null&&e.state.phase==="build"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),a=await je({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(CO(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&xO(e.input)&&!i&&!(e.input.kind==="builder-handoff"&&n))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(e.input.kind==="builder-handoff"){if(e.state.phase!=="build"||e.state.status!=="active")throw new Error("Native Builder input requires an active Build boundary");if(PO(e.state,e.input.addressed_acceptance_ids),a&&(!a.confirmed||!a.allDone))throw new Error("Native parent Build advances child changes and does not accept a Builder handoff");if(n&&e.state.loop.stage==="repairing"&&e.state.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first");e.input.verification_checks!==void 0&&Ye(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(sk(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");Ye(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(sk(e.state),e.input.check_ids.length===0||new Set(e.input.check_ids).size!==e.input.check_ids.length)throw new Error("Native check retry list must contain unique IDs");let c=await Se(D(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(f=>f.id===l);if(!u||u.status!=="interrupted")throw new Error(`Native check retry ID is not an interrupted current check: ${l}`);if(!u.repeatable)throw new Error(`Native check ${l} is not repeatable and cannot be retried`);if(u.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${l}`)}return}if(e.input.kind==="verifier-response"){jh(e.state);let c=await $h({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");Ye(o,RO(e.input));return}if(e.input.kind==="verifier-started"){jh(e.state);let c=await $h({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner started input is stale for the current candidate or execution");return}if(e.input.kind==="verifier-execution-error"||e.input.kind==="verifier-unavailable"){jh(e.state);let c=await $h({paths:e.paths,state:e.state});if(e.input.stateVersion!==e.state.state_version||e.input.iteration!==e.state.loop.iteration||e.input.attempt!==e.state.loop.attempt||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current attempt");return}let s=e.input;if(s.kind==="supervisor-retry-builder"){if(!r)throw new Error("Native Supervisor Builder retry requires a current Supervisor state");let c=r.children.find(({name:l})=>l===s.child);if(!c)throw new Error(`Native Supervisor child ${s.child} does not exist`);if(s.stateVersion!==r.stateVersion||c.status!=="blocked"||c.task!==null||(c.builderFailureCount??0)<cr)throw new Error("Native Supervisor Builder retry input is stale or not currently required");return}if(e.input.kind==="supervisor-checks"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:u})=>u)).size!==c.checks.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(c.checks.some(({repeatable:u})=>!u))throw new Error("Native Supervisor checks must be repeatable for safe recovery");let l=r?.children.find(({name:u})=>u===c.child)?.task;if(!l||l.role!=="verifier"||l.runId!==c.runId)throw new Error("Native Supervisor check runId is not current");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");Ye(l.projectRoot,c.checks);return}if(e.input.kind==="supervisor-integrate"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:l})=>l)).size!==c.checks.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(c.checks.some(({repeatable:l})=>!l))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");Ye(r.integration.worktree,c.checks)}}function ck(e){return`${Ne}:${e}:${dk()}`}function lk(e,t,r,i){if(Ko.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==Ko.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!zt(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function _O(e,t){let r=ie(e.projectRoot),i=Ko.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Ko.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!zt(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function Vn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Ne)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function AO(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function uk(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Vn(r),s=AO(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Ne,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:se(t,r.name),supervisorStateRef:a?wi(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:u,source:f})=>({capability:l,operation:u,ref:f})),acceptanceCount:r.acceptance.length,scopeCount:c.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:o.review?{status:o.review.status,summary:o.review.summary}:null,runtimeChecks:i.map(l=>({...l})),builderReportedChecks:o.checks.map(l=>({...l})),builderKnownLimits:o.known_limits.map(l=>({...l})),startupInstruction:'As this Verifier, submit the startup receipt first: save {"kind":"verifier-started","candidateId":"<candidateId above>","verifierExecutionRef":"<verifierExecutionRef above>"} as a temporary JSON file and run comet native next <change> --runner-input <file> --project-root <projectRoot above>. It only records that this Verifier actually started; a repeat submission is accepted without side effects. Then read the scenarios and proceed.',evidenceInstruction:"Independently inspect the current candidate against every scenario in scopeIds exactly once. Runtime checks are bound evidence; Builder-reported checks and review are claims to corroborate, not Runtime receipts. Reuse applicable completed evidence, request only missing or invalidated checks, and do not repeat full suites by default. Use one Verifier for this dispatch; keep it running across wait-tool timeouts. Return the actual scoped findings, risks, and incomplete checks without omitting limitations. Keep using the same CLI executable that produced this dispatch; do not switch to a different PATH installation.",responseInstruction:"Return one acceptance entry for each ID in scopeIds and no other acceptance IDs. Runtime safely filters a known already-passed superset only when every extra entry still reports passed; nonexistent IDs and conflicting out-of-scope results remain invalid."}}async function Oh(e){Vn(e.state);let t=await Se(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function fk(e){let t=e.input,r=await $(e.paths,e.name),i=await qn({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await O(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:m})=>m==="integrated"||m==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:m})=>m==="integrated"||m==="archived");if(n&&t.kind==="supervisor-checks"){let m=await Mp({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),h=await O(e.paths,e.name),g=h?.children.find(({name:v})=>v===t.child)?.task;return{state:r,supervisorState:h,supervisorTask:g&&g.runId===t.runId?Lr(g,e.name,e.paths.projectRoot):null,checks:[],checkExecution:m,requestChecks:null,verifierDispatch:null,continuation:K(r)}}if(n&&t.kind==="supervisor-builder-result")return _(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:b})=>b===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{lk(h.task,t.candidateCommit,"builder",`comet/supervisor/${m.parent}/${t.child}`)}catch(b){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:b.message})),b}let g=h.task.projectRoot,v=If(m,t),w=Ga(v,{role:"verifier",child:t.child,projectRoot:g,runId:dk()});await q(e.paths,w.state);let y=await $(e.paths,e.name);return{state:y,supervisorTask:Lr(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:K(y)}});if(n&&t.kind==="supervisor-builder-failure")return _(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:w})=>w===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let g=jc(m,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,g);let v=await $(e.paths,e.name);return{state:v,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(n&&t.kind==="supervisor-retry-builder")return _(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=jf(m,{child:t.child,expectedStateVersion:t.stateVersion});await q(e.paths,h);let g=await $(e.paths,e.name);return{state:g,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-reconnect")return _(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:w})=>w===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{_O(h,`comet/supervisor/${m.parent}/${t.child}`)}catch(w){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:w.message})),w}let g=Af(m,{child:t.child,runId:t.runId});await q(e.paths,g.state);let v=await $(e.paths,e.name);return{state:v,supervisorState:g.state,supervisorTask:Lr(g.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(n&&t.kind==="supervisor-cancel")return _(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=jc(m,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,h);let g=await $(e.paths,e.name);return{state:g,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-verifier-result")return _(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:y})=>y===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{lk(h.task,h.candidateCommit,"verifier",`comet/supervisor/${m.parent}/${t.child}`)}catch(y){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:y.message})),y}let g=t.evidence.receiptRef||t.verdict==="pass"?await _n({paths:e.paths,parent:e.name,task:h.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!g||g.checks.some(({status:y,exitCode:b})=>y!=="passed"||b!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let v=Tf(m,{...t,evidence:{...t.evidence,checks:g?.checks.map(({name:y,status:b})=>`${y}: ${b}`)??[],execution:structuredClone(h.task)}});await q(e.paths,v);let w=await $(e.paths,e.name);return{state:w,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(w)}});if(n&&t.kind==="supervisor-integrate"){let m=await Gp({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),h=await Go({paths:e.paths,name:e.name,trigger:"v2-integrate"}),g=h.state;return{state:g,supervisorState:m,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:K(g)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="retry-checks"||t.kind==="verifier-response"||t.kind==="verifier-started"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let h=Cf().captureExecutionIdentity({identityProvider:Ne,executionRef:ck("builder")}),g=await yh({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let v=await zo({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=v.checks.filter(({status:S})=>S==="failed").map(({id:S})=>S),y=v.checks.filter(({status:S})=>S==="interrupted").map(({id:S})=>S),b=t.verification_checks.filter(({id:S,repeatable:N})=>y.includes(S)&&!N).map(({id:S})=>S);if(w.length>0||b.length>0){let S=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${b.join(", ")}`,N=await Hi({paths:e.paths,name:e.name,reason:S,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:N,checks:v.checks,runtimeCheckExecution:{disposition:v.disposition},requestChecks:null,verifierDispatch:null,continuation:K(N)}}return{state:v.state,checks:v.checks,runtimeCheckExecution:{disposition:v.disposition},continuationCheckPlans:t.verification_checks,...y.length>0?{continuationRetryCheckIds:y}:{},requestChecks:null,verifierDispatch:null,continuation:K(v.state,void 0,{...y.length>0?{retryCheckIds:y}:{verificationCheckPlans:t.verification_checks}})}}return{state:g,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let m=await $(e.paths,e.name);Vn(m);let h=await gh({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),g=h.checks.filter(({status:v})=>v==="interrupted").map(({id:v})=>v);if(g.length>0){let w=((await Se(D(e.paths,e.name)))?.checks??[]).filter(({id:y,status:b,executionCount:S})=>g.includes(y)&&b==="interrupted"&&S>=3).map(({id:y})=>y);if(w.length>0){let y=await Hi({paths:e.paths,name:e.name,reason:`Native Runtime checks reached the retry limit after repeated interruptions: ${w.join(", ")}`,failureBudget:{maxVerifyFailures:e.maxVerifyFailures},preserveLocalChecks:!0});return{state:y,checks:h.checks,requestChecks:null,verifierDispatch:null,continuation:K(y)}}}return{state:h.state,checks:h.checks,...g.length>0?{continuationRetryCheckIds:g}:{},requestChecks:null,verifierDispatch:null,continuation:K(h.state,void 0,{retryCheckIds:g.length>0?g:void 0})}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let m=await $(e.paths,e.name);if(m.builder_handoff!==null&&m.builder_handoff.identity_provider!==Ne){let b=await Hi({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:b,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(b)}}Vn(m);let h=await zo({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),g=h.checks,v=g.filter(({status:b})=>b==="interrupted").map(({id:b})=>b);if(v.length>0){let b=t.checks.filter(({id:N,repeatable:x})=>v.includes(N)&&!x).map(({id:N})=>N);if(b.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${b.join(", ")}`);let S=await $(e.paths,e.name);return{state:S,checks:g,runtimeCheckExecution:{disposition:h.disposition},continuationRetryCheckIds:v,requestChecks:null,verifierDispatch:null,continuation:K(S,void 0,{retryCheckIds:v})}}let w=ck("verifier"),y=await Nh({paths:e.paths,name:e.name,checks:g,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:y,checks:g,runtimeCheckExecution:{disposition:h.disposition},requestChecks:null,verifierDispatch:uk({paths:e.paths,state:y,checks:g,verifierExecutionRef:w,supervisor:a?n:null}),continuation:K(y,void 0,{verifierExecutionRef:w})}}if(t.kind==="verifier-started"){let m=await bh({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind==="verifier-execution-error"){let m=await $(e.paths,e.name);Vn(m),await Oh({paths:e.paths,state:m});let h=await Sh({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(h)}}if(t.kind==="verifier-unavailable"){let m=await Eh({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:m.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await $(e.paths,e.name),c=Vn(s),l=await Oh({paths:e.paths,state:s});if(t.candidateId!==c.candidate_id||t.verifierExecutionRef!==l)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");let u=Cf(),f=u.captureExecutionIdentity({identityProvider:Ne,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let m=await O(e.paths,e.name);if(!m)throw new Error("Native Supervisor state disappeared before final verification");d=Ii(m)}let p=await kh({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:f,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&p.response.kind==="final-result"){if(p.state.verification_result==="pass"&&(p.checks.length===0||p.checks.some(({status:g})=>g!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let m=d??await O(e.paths,e.name);if(!m)throw new Error("Native Supervisor state disappeared during verification");let h=Ti(m,p.state);return await q(e.paths,h),{...p,supervisorState:h,verifierDispatch:null,continuation:K(p.state)}}return{...p,verifierDispatch:p.requestChecks===null?null:uk({paths:e.paths,state:p.state,checks:p.checks,verifierExecutionRef:await Oh({paths:e.paths,state:p.state}),supervisor:a?n:null}),continuation:K(p.state,void 0,{verifierExecutionRef:l})}}mi();cn();Ta();import Xo from"path";import{realpathSync as m0}from"fs";function pk(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 wr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function hk(e){return e?e.command?`${wr.next} ${e.command}`:e.ask_user?`${wr.next} ${e.ask_user}`:null:null}function mk(e,t){let r=[e.summary],i=hk(e.next);return i&&r.push(i),e.user_message&&r.push("",wr.relay,e.user_message),t!==void 0&&r.push("",wr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
367
|
+
`)}async function ym(e){let t=le(e.paths,e.state.name),r=[...(await vm(t,e.state.brief,{strict:!0,compact:e.state.document_constraints_version===2})).findings],i="";try{i=(await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:l})=>l!=="remove"),o=e.state.spec_changes.filter(({operation:l})=>l!=="remove"),s=new Set(a.map(({capability:l})=>l));if(e.specChanges!==void 0)for(let l of o)s.has(l.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${l.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${l.capability}/spec.md`});let c=n.length>0&&n.every(({operation:l})=>l==="remove");a.length===0&&o.length===0&&!c&&!MH(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let l of a){let u=`specs/${l.capability}/spec.md`;if(l.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:l.source??u});continue}try{let d=(await Z({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...Qk(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function ju(e){let t=await ym(e);if(!t.valid)throw new ca(nS(t.findings,{change:e.state.name,phase:e.state.phase}),t.findings,e.state.name)}function Mt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Ou(e){let t=le(e.paths,e.state.name),r=rn.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Tu.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Xf.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=rn.join(t,...s.split("/")),l=await Tu.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=rn.join(e.paths.specsDir,o.name,"spec.md"),d="create",p=null;try{let v=await Tu.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",p=Sr((await Z({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let h=`specs/${o.name}/${cb}`,f=rn.join(t,...h.split("/")),m={};try{let v=await Tu.lstat(f);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${h}`);let g=await Z({root:t,ref:h,maxBytes:null,includeHash:!1}),w=Ho(g.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let N=p??Sr(""),y=e.state.spec_changes.find(E=>E.capability===o.name);if(y?.delta_source!==void 0){if(y.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==N)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);m={delta_source:h,base_hash:w.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:d,source:s,...m})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Hu(e){let t=le(e.paths,e.state.name),r=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(mm(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await Z({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await Z({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=Ho(u.text);c=pb(s.text,d);let p="";try{p=(await Z({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(h){if(h.code!=="ENOENT")throw h}if(Sr(p)===d.base_hash){let h=fb({baselineMarkdown:p,delta:d,allowAlreadyApplied:!0});if(Sr(s.text)!==h.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}l=$("comet.native.shape-artifact-content.v1",$u(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:$("comet.native.shape-artifact-content.v1",$u(s.text,e.state.document_constraints_version===2)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await Z({root:t,ref:iS,maxBytes:65536,includeHash:!1}),s=rS(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let l=rn.relative(e.paths.projectRoot,rn.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(rn.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=$("comet.native.shape-artifact-content.v1",$u(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:Hl({briefMarkdown:r.text,specs:i,resolveBriefReferences:e.state.document_constraints_version===2}),formalHash:$("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:$("comet.native.shape-artifact-content.v1",$u(r.text,e.state.document_constraints_version===2))},specs:n,association:{source:iS,contentHash:a}})}}function bs(e){return $("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function bm(e){return A(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=e.enforceDocumentConstraints===!0?{...t,document_constraints_version:2}:t,i=await Ou({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await ju({paths:e.paths,state:r,specChanges:i});let n=await Hu({paths:e.paths,state:r,specChanges:i}),{acceptance:a}=n,o=await Je({changeDir:le(e.paths,t.name),acceptanceIds:a.map(({id:h})=>h),validation:bt({...t,acceptance:a})}),s=t;if(o&&t.workspace.change_branch===null){await wl(e.paths,t.name);let h=Su(t.workspace,e.paths.projectRoot);if(h===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");s=ke({...t,workspace:h},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${h.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let c=await cs(le(e.paths,t.name))||o?.contract.schema==="comet.native.children.v2"&&o.contract.children.length>=2;if(c&&!o)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let l=c?e.coordinationMode??t.coordination_mode:void 0;if(!c&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let u={...s,...r.document_constraints_version===void 0?{}:{document_constraints_version:r.document_constraints_version},spec_changes:i,shape_confirmation_hash:bs({formalHash:n.formalHash,childrenHash:o?.hash??null,coordinationMode:l})};delete u.children_contract_hash,delete u.coordination_mode,c&&(u.coordination_mode=l);let d=pk({state:u,acceptance:a.map(h=>({...h}))});o&&(d.children_contract_hash=ea({acceptance:d.acceptance,children:o.contract}));let p=await he({paths:e.paths,previous:t,next:d});return await M(L(e.paths,t.name),ae({portableState:p,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),p})}async function Ns(e){if(e.state.document_constraints_version!==void 0){let l=await ym(e);if(!l.valid){let u=l.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Ou(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&l.delta_source===d.delta_source&&l.base_hash===d.base_hash&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Hu({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!$b(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Je({changeDir:le(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:bt({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&bs({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?ea({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Ze(e){let t=await Ns(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Ss({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function ks(e){return A(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Ss({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function Ss(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...ke(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}function qu(e,t){let r=O.relative(O.resolve(e),O.resolve(t));if(O.isAbsolute(r)||r===".."||r.startsWith(`..${O.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(O.sep).join("/");return Io(e,i),i}function VH(e){return e.split("\0").some(t=>t.startsWith("160000 "))}function Du(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return qn({id:e.id,name:e.name,executable:r,argv:i,cwdRef:qu(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function lS(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:qu(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function uS(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||O.resolve(e.workspace.projectRoot)!==O.resolve(r)||O.resolve(e.workspace.worktreeRoot)!==O.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==Tr.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>Du(o,r)===qn(t[s]))}function km(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>Du(i,r)===qn(t[n]))}async function Bu(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await Bn(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await Bn(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function aS(e){return{...e,execution:e.execution===null?null:{...e.execution,status:"interrupted"},checks:e.checks.map(t=>t.status==="planned"||t.status==="running"?{...t,status:"interrupted",activeProcess:null}:t)}}function Lu(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:Io(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function WH(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return Em(e,t,r,i)}function Em(e,t,r,i){return{...Lu(t,r,i),executionCount:e.executionCount}}function dS(e){return sS("sha256").update(e).digest("hex")}async function Rs(e){let t=await ur.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=sS("sha256"),i=await ur.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(zH);for(;;){let{bytesRead:s}=await i.read(o,0,o.length,null);if(s===0)break;n+=s,r.update(o.subarray(0,s).toString("base64"))}}finally{await i.close()}let a=await ur.lstat(e);if(a.size!==t.size||a.mtimeMs!==t.mtimeMs)throw new Error("Native check input changed while reading");return{digest:r.digest("hex"),size:n}}var pS=2e4,hS=1024*1024*1024,zH=65535,fS=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],GH=new Set([".agents",".cache",".claude",".codex",".comet",".git",".idea",".next",".nuxt",".output",".parcel-cache",".svelte-kit",".tmp",".turbo",".vscode",".worktrees","coverage","logs","node_modules","temp","tmp"]),Nm=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],mS=new Set(["comet-state.yaml","children.yaml","verification.md"]);function vS(e,t){if(!t)return[...Nm];let r=O.relative(e,t).replaceAll("\\","/");if(O.isAbsolute(r)||r===".."||r.startsWith("../"))return[...Nm];let i=r===""?"":`${r}/`;return[...Nm,...["changes","archive"].flatMap(n=>[...mS].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function xm(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!mS.has(O.basename(i)))return!1;let n=O.resolve(t,...i.split("/")),a=O.relative(O.resolve(r),n);if(O.isAbsolute(a)||a===".."||a.startsWith(`..${O.sep}`))return!1;let[,o]=a.split(O.sep);return a.startsWith(`comet${O.sep}`)&&(o==="changes"||o==="archive")}function ua(){return{complete:!1,files:[]}}function JH(e){let t=e==="."?"":`${e}/`;return fS.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function gS(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function wS(e,t,r,i=new Set){let n=[...new Set(t.map(({cwdRef:c})=>c))];if(n.length===0)return{complete:!0,files:[]};let a;try{a=[...new Set(I(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...n.flatMap(JH)]).split("\0").filter(Boolean).map(c=>c.replaceAll("\\","/")))].sort()}catch{return ua()}if(a.length>pS)return ua();let o=[],s=0;for(let c of a){if(i.has(c)||xm(c,e,r))continue;let l=O.resolve(e,...c.split("/"));if(!Ee(e,l)||gS(c))return ua();try{let u=await ur.lstat(l);if(!u.isFile()||s+u.size>hS)return ua();let{digest:d,size:p}=await Rs(l);s+=p,o.push({path:c,digest:d,size:p})}catch{return ua()}}return{complete:!0,files:o}}async function UH(e,t,r,i=new Set){let n=[...new Set(t.map(({cwdRef:l})=>l))],a=new Map,o=0,s=l=>fS.includes(l),c=async(l,u,d)=>{let p;try{p=await ur.readdir(l,{withFileTypes:!0})}catch{return!1}p.sort((h,f)=>h.name.localeCompare(f.name,"en"));for(let h of p){let f=u?`${u}/${h.name}`:h.name;if(i.has(f)||xm(f,e,r)||h.isDirectory()&&GH.has(h.name))continue;let m=O.join(l,h.name);if(h.isDirectory()){if(!await c(m,f,d||s(h.name)))return!1;continue}if(d){if(gS(f)||!h.isFile())return!1;try{let v=await ur.lstat(m);if(o+v.size>hS)return!1;let{digest:g,size:w}=await Rs(m);if(o+=w,a.set(f,{path:f,digest:g,size:w}),a.size>pS)return!1}catch{return!1}}}return!0};for(let l of n){let u=Io(e,l);if(!await c(u,l==="."?"":l,s(O.basename(u))))return ua()}return{complete:!0,files:[...a.values()].sort((l,u)=>l.path.localeCompare(u.path,"en"))}}function Rm(e,t){return $("comet.native.local-check-evidence.v1",{id:e.id,name:e.name,status:e.status,repeatable:e.repeatable,timeoutMs:e.timeoutMs,argv:e.argv,cwd:O.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:dS(t)})}async function yS(e){let t=await Mf(e.projectRoot),r=[...vS(e.projectRoot,e.managedArtifactRoot),...[...t].map(a=>`:(exclude,literal)${a}`)],i={complete:!0,capture:"git",head:null,branch:null,status:null,diff:null,stagedDiff:null,submodules:null,untracked:[],ignored:{complete:!0,files:[]},physical:{complete:!0,files:[]},reuseNonce:null},n=!1;try{i.head=I(e.projectRoot,["rev-parse","HEAD"]),n=!0,i.branch=I(e.projectRoot,["branch","--show-current"]),i.status=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...r]);let a=I(e.projectRoot,["diff","--name-only","-z","HEAD","--",...r]).split("\0").filter(Boolean).sort();i.diff=await Yf(a,4,async c=>{let l=O.resolve(e.projectRoot,...c.split("/"));try{let{digest:u}=await Rs(l);return{path:c,digest:u}}catch{return{path:c,digest:null}}}),i.diff.some(({digest:c})=>c===null)&&(i.complete=!1);let o=I(e.projectRoot,["ls-files","--stage","-z","--",...r]);i.stagedDiff=dS(o),i.submodules=VH(o)?I(e.projectRoot,["submodule","status","--recursive"]):"";let s=I(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...r]).split("\0").filter(Boolean).sort();i.untracked=await Yf(s,4,async c=>{let l=O.resolve(e.projectRoot,...c.split("/"));try{let{digest:u,size:d}=await Rs(l);return{path:c,digest:u,size:d}}catch{return{path:c,digest:null,size:null}}}),i.untracked.some(({digest:c})=>c===null)&&(i.complete=!1),i.ignored=await wS(e.projectRoot,e.plans,e.managedArtifactRoot,t),i.ignored.complete||(i.complete=!1)}catch{n?i.complete=!1:(i.capture="physical-tree",i.physical=await UH(e.projectRoot,e.plans,e.managedArtifactRoot,t),i.complete=i.physical.complete)}return $("comet.native.check-input.v1",{candidateId:e.state.builder_handoff?.candidate_id??null,shapeConfirmationHash:e.state.shape_confirmation_hash??null,acceptance:e.state.acceptance.map(({id:a,source:o,text:s})=>({id:a,source:o,text:s})),git:i,projectRoot:O.resolve(e.projectRoot),machineId:Tr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,path:process.env.PATH??null,pathext:process.env.PATHEXT??null,boundEnvironment:Object.entries(process.env).filter(([a])=>bS.has(a.toUpperCase())).map(([a,o])=>[a,o??null]).sort(([a],[o])=>a.localeCompare(o))})}var bS=new Set(["PATH","PATHEXT","NODE_OPTIONS","NODE_ENV","NODE_PATH","LANG","LC_ALL","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","SHELL","TMPDIR","TEMP","TMP","HTTP_PROXY","HTTPS_PROXY","NO_PROXY"]);function KH(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function YH(){return Object.entries(process.env).filter(([e])=>bS.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function NS(e){try{let t=await Mf(e.projectRoot),r=[...vS(e.projectRoot,e.managedArtifactRoot),...[...t].map(c=>`:(exclude,literal)${c}`)],i=I(e.projectRoot,["rev-parse","HEAD"]),n=I(e.projectRoot,["branch","--show-current"]),a=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...r]),o=I(e.projectRoot,["ls-files","--stage","-z","--",...r]);if(i===null||a===null)return null;let s=[];for(let c of Qa(e.projectRoot).filter(l=>!t.has(l)&&!xm(l,e.projectRoot,e.managedArtifactRoot))){let l=O.resolve(e.projectRoot,...c.split("/")),u=null;try{u=(await Rs(l)).digest}catch{return null}s.push({path:c,digest:u})}return s.sort((c,l)=>c.path.localeCompare(l.path,"en")),{runnerInputs:t,binding:{candidateId:e.candidateId,head:i,branch:n,status:a,staged:o,workingTree:s,projectRoot:O.resolve(e.projectRoot),machineId:Tr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:YH()}}}catch{return null}}async function Sm(e,t){if(t===null)return null;try{let r=await wS(e.projectRoot,e.plans??[],e.managedArtifactRoot,t.runnerInputs);return r.complete?$("comet.native.check-input-gate.v1",{...t.binding,ignored:r}):null}catch{return null}}async function oS(e){return Sm(e,await NS(e))}async function kS(e){let t=await NS(e);return{branch:t===null?ge(e.projectRoot):t.binding.branch||null,gate:await Sm(e,t),candidateGate:await Sm({...e,plans:[]},t)}}function vi(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);if(r.status==="passed"&&(r.evidence!=="runtime"||!r.evidenceDigest))throw new Error(`Native Runtime check ${r.id} has no Runtime execution evidence`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:J(i),argv_display:To(r.argv.slice(1)).map(n=>J(n)),argv_truncated:!1,cwd_ref:qu(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:KH(r)}})}function XH(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function gi(e){if(e.local===null||e.local.change!==e.state.name)return ae({portableState:e.state,projectRoot:e.projectRoot,branch:ge(e.projectRoot)});let t=e.local.execution?.operationId??cS();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function $r(e){try{let t=await Ce(L(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}async function Cm(e){let t=await $r({paths:e.paths,state:e.state}),r=bk({state:e.state,summary:e.summary}),i=await he({paths:e.paths,previous:e.state,next:r});return await M(L(e.paths,e.state.name),gi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function SS(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await G(t,O.resolve(t,...r.log.split(/[\\/]/u)));if(!(await ur.stat(i)).isFile())return!1;let n=await ur.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==Rm(r,n))return!1}catch{return!1}}return!0}async function ES(e){let{local:t,previous:r,next:i,plans:n,paths:a}=e;if(!t||!t.checks.length||t.checks.some(({status:s})=>s!=="passed")||t.basedOnStateVersion!==r.state_version||t.candidateId!==r.builder_handoff?.candidate_id||t.workspace.machineId!==Tr.hostname()||t.inputFingerprint==null||t.inputFingerprintGate==null||t.execution?.stage==="checking"&&t.execution.status==="running"||r.shape_confirmation_hash!==i.shape_confirmation_hash||JSON.stringify(r.acceptance.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l})))!==JSON.stringify(i.acceptance.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l}))))return null;let o=t.workspace.worktreeRoot;if(O.resolve(t.workspace.projectRoot)!==O.resolve(e.projectRoot??a.projectRoot)||O.resolve(o)!==O.resolve(e.projectRoot??a.projectRoot))return null;try{if(t.workspace.branch!==ge(o)||!km(t,n,o)||!await SS(t,me(a,i.name)))return null;let s={projectRoot:o,candidateId:t.candidateId??null,plans:n,managedArtifactRoot:a.artifactRoot},c=await oS(s);if(c===null||c!==t.inputFingerprintGate)return null;let l=await yS({state:i,projectRoot:o,plans:n,managedArtifactRoot:a.artifactRoot}),u=await kS({...s,candidateId:i.builder_handoff.candidate_id});return u.gate===null||u.candidateGate===null||await oS(s)!==c?null:{...gi({local:t,state:i,projectRoot:a.projectRoot}),candidateId:i.builder_handoff.candidate_id,inputFingerprint:l,inputFingerprintGate:u.gate,candidateInputFingerprintGate:u.candidateGate}}catch{return null}}async function QH(e){return A(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let{gate:r,candidateGate:i,branch:n}=await kS({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),a=n,o=L(e.paths,t.name),s=(await Nu({file:o,portableState:t,projectRoot:e.projectRoot,branch:a,containedRoot:e.paths.runtimeDir})).state;a!==null&&s.workspace.branch===`heads/${a}`&&(a=ge(e.projectRoot));let c=r===null,u=r!==null&&s.inputFingerprint!==null&&s.inputFingerprintGate===r&&s.candidateInputFingerprintGate===i&&s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.machineId===Tr.hostname()?s.inputFingerprint:await yS({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),d=me(e.paths,t.name),p=await SS(s,d),h=s.checks.every(S=>S.status==="passed"),f=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),m=s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname()&&s.inputFingerprint===u,v=i!==null&&s.candidateInputFingerprintGate===i&&s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname(),g=v&&s.inputFingerprint!==null&&s.inputFingerprint!==u,w=uS(s,e.plans,e.projectRoot,t,u,a)||v&&km(s,e.plans,e.projectRoot),N=s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname(),y=m&&h&&!p;if(f&&f.size===0)throw new Error("Native check retry list must contain at least one ID");if(!m&&s.execution?.stage==="checking"&&s.execution.actor==="runtime"&&s.execution.status==="running"){let S=await Bu(s);if(S!=="orphaned")throw new Error(S==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before changing its binding":"Native check plan is already in progress on another workspace binding");s=aS(s),await M(o,s,{containedRoot:e.paths.runtimeDir})}if(!m&&N&&s.inputFingerprint!==null&&(s.execution!==null||s.checks.length>0)){let S=s.inputFingerprint!==u;if(!(c&&!S||g)){let C=pi({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),P=await he({paths:e.paths,previous:t,next:C});throw await M(o,ae({portableState:P,projectRoot:e.paths.projectRoot,branch:a}),{containedRoot:e.paths.runtimeDir}),new Error("Native check input changed after the candidate was built; the change returned to Build for a new candidate")}}if(!m&&!v){let S=ae({portableState:t,projectRoot:e.projectRoot,branch:a});await M(o,S,{containedRoot:e.paths.runtimeDir}),s=S}let E=km(s,e.plans,e.projectRoot);if(s.execution?.stage==="checking"&&s.execution.actor==="runtime"&&E&&w){let S=s.execution;if(S.status==="running"){let P=await Bu(s);if(P!=="orphaned")throw new Error(P==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before retrying":"Native check plan is already in progress");s=aS(s),await M(o,s,{containedRoot:e.paths.runtimeDir}),S=s.execution}let C=s.checks.filter(P=>P.status==="interrupted");if(C.length===0&&S.status==="completed"&&h&&!y&&!g){let P=new Map(e.plans.map(({id:_,name:j})=>[_,j]));return{kind:"reuse",state:t,checks:vi({local:s,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(C.length===0&&S.status==="completed"&&!h&&!y&&!g)throw new Error(`Native check plan contains a failed check (${s.checks.filter(({status:P})=>P==="failed").map(({id:P})=>P).join(", ")}); submit a new Builder candidate`);if(C.length>0&&C.some(P=>!P.repeatable)&&!y){let P=pi({state:t,reason:`A non-repeatable Runtime check was interrupted (${C.filter(j=>!j.repeatable).map(({id:j})=>j).join(", ")}); a new Builder candidate is required before it can run again.`}),_=await he({paths:e.paths,previous:t,next:P});throw await M(L(e.paths,t.name),ae({portableState:_,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${C.find(j=>!j.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(C.length>0&&f===null&&!y&&!g){let P=new Map(e.plans.map(({id:_,name:j})=>[_,j]));return{kind:"reuse",state:t,checks:vi({local:s,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(f){let P=[...f].filter(j=>!C.some(ue=>ue.id===j));if(P.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${P.join(", ")}`);let _=C.filter(j=>f.has(j.id)&&j.executionCount>=3);if(_.length>0)throw new Error(`Native check retry limit (3) reached: ${_.map(({id:j})=>j).join(", ")}`)}}if(s.execution!==null&&s.checks.length>0){if(!(s.execution.stage==="checking"&&s.execution.actor==="runtime"&&s.checks.some(C=>C.status==="interrupted")&&E)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan")}else if((s.execution!==null||s.checks.length>0)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan");let b=cS(),x=await ct(process.pid),k={...s,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:u,inputFingerprintGate:r,candidateInputFingerprintGate:i,workspace:{...s.workspace,projectRoot:O.resolve(e.projectRoot),worktreeRoot:O.resolve(e.projectRoot),branch:ge(e.projectRoot),machineId:Tr.hostname()},execution:{operationId:b,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...x?{ownerIdentity:x}:{}},checks:e.plans.map(S=>{let C=s.checks.find(P=>P.id===S.id);return g&&C?Lu(S,b,e.projectRoot):y&&C?Em(C,S,b,e.projectRoot):C?.status==="interrupted"&&(f===null||f.has(C.id))?WH(C,S,b,e.projectRoot):C?{...C,operationId:b,activeProcess:null}:Lu(S,b,e.projectRoot)})};return await M(o,k,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:k,plans:e.plans.filter(S=>{let C=s.checks.find(P=>P.id===S.id);return y||g||C===void 0||C.status==="interrupted"&&(f===null||f.has(C.id))})}})}async function Es(e){return A(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=L(e.paths,t.name),i=await Ce(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await M(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function Cs(e){let t=e.projectRoot??e.paths.projectRoot;lt(t,e.plans);let r=[],i=new Set;for(let c of e.plans){$o(t,c);let l=qn(c);i.has(l)||(i.add(l),r.push(c))}let n=await QH({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=me(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Es({paths:e.paths,state:n.state,operationId:a,update:p=>({...p,checks:p.checks.map(h=>h.id===c.id?{...h,status:"running",executionCount:h.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:h)})});let u=await Bi({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:p})=>{let h=await ct(p);await Es({paths:e.paths,state:n.state,operationId:a,update:f=>({...f,checks:f.checks.map(m=>m.id===c.id?{...m,activeProcess:{status:"running",pid:p,...h?{identity:h}:{}}}:m)})})}}),d=await ur.readFile(O.resolve(o,...u.logRef.split("/")),"utf8");await Es({paths:e.paths,state:n.state,operationId:a,update:p=>({...p,checks:p.checks.map(h=>{if(h.id!==c.id)return h;let f={...h,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...f,evidenceDigest:Rm(f,d)}})})})}await Es({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Es({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted",activeProcess:null}:u)})})}catch{}throw c}let s=await Ce(L(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:vi({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function Pm(e){if(e.checkIds.length===0)throw new Error("Native check retry list must contain at least one ID");let t=e.projectRoot??e.paths.projectRoot,r=await H(e.paths,e.name);if(r.phase!=="verify"||r.status!=="active"||r.loop.stage!=="verify-ready"||r.builder_handoff===null)throw new Error("Native check retry requires an active Verify-ready candidate");let i=await Ce(L(e.paths,e.name));if(i===null||i.change!==r.name||i.basedOnStateVersion!==r.state_version||i.execution===null||i.execution.stage!=="checking"||i.execution.actor!=="runtime")throw new Error("Native check retry has no current Runtime check execution");let n=new Set(e.checkIds);if(n.size!==e.checkIds.length)throw new Error("Native check retry list contains duplicate IDs");let a=i.checks.filter(c=>n.has(c.id)),o=e.checkIds.filter(c=>!a.some(l=>l.id===c));if(o.length>0)throw new Error(`Native check retry IDs are unknown: ${o.join(", ")}`);for(let c of a){if(c.status!=="interrupted")throw new Error(`Native check ${c.id} is not interrupted and cannot be retried`);if(!c.repeatable)throw new Error(`Native check ${c.id} is not repeatable and cannot be retried`);if(c.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${c.id}`)}let s=i.checks.map(c=>{let[l,...u]=c.argv;if(!l)throw new Error(`Native local check ${c.id} has no executable`);return{id:c.id,name:c.name,executable:l,argv:u,cwdRef:qu(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return Cs({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function xS(e){let t=L(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Wf)throw new Error(`Native Verifier request-checks exceeded ${Wf} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let h of r.checks){let f=Du(h,e.projectRoot);n.set(f,h),h.status==="passed"&&i.set(f,h),a.set(h.id,f)}let o=new Map,s=new Map;for(let h of e.response.checks){let f=XH(h);$o(e.projectRoot,f);let m=qn(f),v=s.get(f.id);if(v!==void 0&&v!==m)throw new Error(`Native Verifier check ID ${f.id} refers to conflicting commands`);let g=a.get(f.id);if(g!==void 0&&g!==m)throw new Error(`Native Verifier check ID ${f.id} conflicts with a Runtime check`);s.set(f.id,m);let w=n.get(m);if(w&&w.status!=="passed"&&!w.repeatable)throw new Error(`Native check ${w.id} did not pass and is not repeatable; user resolution is required`);if(w&&w.status!=="passed"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(m)||o.set(m,f)}lt(e.projectRoot,[...o.values()]);let c=[...o.entries()],l=c.filter(([h])=>!i.has(h));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=r.execution.requestCheckRounds+1,d=new Map(c.map(([,h])=>[h.id,h.name])),p={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(h=>{let f=Du(h,e.projectRoot),m=o.get(f);return m&&h.status!=="passed"?Em(h,m,r.execution.operationId,e.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>Lu(h,r.execution.operationId,e.projectRoot))]};return await M(t,p,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:p,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,h])=>h),requestedNames:d,reusedCheckIds:c.filter(([h])=>i.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function xs(e){return A(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=L(e.paths,t.name),i=await Ce(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await M(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function RS(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await xs({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>c.id===r.id?{...c,status:"running",executionCount:c.executionCount+1,startedAt:i,activeProcess:{status:"starting"}}:c)})});let n=me(e.paths,e.reservation.state.name),a=await Bi({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await ct(s);await xs({paths:e.paths,reservation:e.reservation,update:l=>({...l,checks:l.checks.map(u=>u.id===r.id?{...u,activeProcess:{status:"running",pid:s,...c?{identity:c}:{}}}:u)})})}}),o=await ur.readFile(await G(n,O.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await xs({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>{if(c.id!==r.id)return c;let l={...c,status:a.status,exitCode:a.exitCode,startedAt:a.startedAt,completedAt:a.completedAt,log:a.logRef,activeProcess:null,evidence:"runtime"};return{...l,evidenceDigest:Rm(l,o)}})})})}t=await xs({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await xs({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted",activeProcess:null}:n)})})}catch{}throw r}return{checks:vi({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}import{accessSync as f6,constants as m6,promises as AS}from"node:fs";import pa from"node:path";ne();var ZH=fr(Gt(),1);We();pe();rt();at();yn();We();gt();ve();gt();ve();Hi();kr();at();ni();async function _m(e){return A(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0&&t.coordination_mode!==void 0&&e.coordinationMode!==t.coordination_mode)throw new Error("--coordination-mode is already bound to this Shape confirmation; revise Shape before changing it");await Ze({paths:e.paths,state:t});let r=await Ou({paths:e.paths,state:t}),i=await Hu({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Je({changeDir:le(e.paths,t.name),acceptanceIds:n.map(({id:g})=>g),validation:bt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await wl(e.paths,t.name);let g=Su(t.workspace,e.paths.projectRoot);if(g===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=ke({...t,workspace:g},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${g.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await cs(le(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,c=e.coordinationMode??t.coordination_mode;if(!s&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let l=bs({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:t.coordination_mode});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let g=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Ss({paths:e.paths,state:t,reason:g,keepFailureBudget:!0}),new Error(`${g}; Native change returned to Shape and requires confirmation`)}let u=dk({state:{...o,spec_changes:r,shape_confirmation_hash:bs({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c})},acceptance:n.map(g=>({...g}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=ea({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let g=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(g?.outcome==="fail"&&g.unresolved_ids.length>0){let w=await Le({paths:e.paths,state:u}),N=new Map((w?.children??[]).map(({name:b,status:x})=>[b,x])),y=new Set(a.contract.children.filter(({name:b})=>{let x=N.get(b);return x!=="done"&&x!=="integrated"&&x!=="archived"}).flatMap(({covers:b})=>b)),E=g.unresolved_ids.filter(b=>!y.has(b));if(E.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${E.join(", ")}`)}}let d=null,p=a?.contract.schema==="comet.native.children.v2"?await D(e.paths,t.name):null,h=null,f=null;if(a?.contract.schema==="comet.native.children.v2"){if(h=o.workspace.change_branch??o.workspace.target_branch,!h)throw new Error("Native Supervisor v2 requires a target branch");if(f=wr(e.paths.projectRoot,h),!f)throw new Error(`Native Supervisor target branch has no commit: ${h}`);p||(p=await ss({paths:e.paths,parent:t.name,targetBranch:h,contract:a.contract})),p||(d=await Df({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:h,sourceConfig:await Oe(e.paths.projectRoot)}))}let m=a?.contract.schema==="comet.native.children.v2"&&h&&f?p?Nh({state:p,contract:a.contract}):d?xo({parent:u.name,targetBranch:h,targetCommit:f,integrationBranch:d.binding.changeBranch,integrationWorktree:d.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!m)throw new Error("Native Supervisor integration state is unavailable");let v=await he({paths:e.paths,previous:t,next:u});return await M(L(e.paths,t.name),ae({portableState:v,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),m&&await F(e.paths,m),v})}import{randomUUID as eD}from"node:crypto";import Fu from"node:path";ve();ko();ji();function CS(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function tD(e){let{state:t,local:r,envelope:i}=e;if(!pl(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function rD(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Am(e){return A(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),await Je({changeDir:le(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:o})=>o),validation:bt(t)})||t.children_contract_hash){let o=await Le({paths:e.paths,state:t});if(!o?.confirmed||!o.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=hk({state:t,input:e.input}),n=e.verificationChecks===void 0?null:await ES({paths:e.paths,previous:t,next:i,plans:e.verificationChecks,projectRoot:e.projectRoot,local:await $r({paths:e.paths,state:t})}),a=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),n??ae({portableState:a,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Im(e){return A(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Ze({paths:e.paths,state:t});let i=(await Nu({file:L(e.paths,t.name),portableState:t,projectRoot:r,branch:ge(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");vi({local:i,projectRoot:r,supplied:e.checks});let n=fk(t),a=await he({paths:e.paths,previous:t,next:n}),o=L(e.paths,t.name),s=eD();return await M(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function Tm(e){return A(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier start confirmation requires an active Verifier attempt");let r=L(e.paths,e.name),i=await Ce(r),n=i?.execution;if(i===null||i.change!==t.name||i.basedOnStateVersion!==t.state_version||!n||n.stage!=="verifying"||n.actor!=="verifier"||n.status!=="running"||n.executionId===null||n.executionId!==e.verifierExecutionRef)throw new Error("Native Verifier start confirmation is stale for the current attempt");if(t.builder_handoff?.candidate_id!==e.candidateId)throw new Error("Native Verifier start confirmation is stale for the current candidate");return n.verifierStartedAt===void 0&&await M(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function $m(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await A(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await H(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Ze({paths:e.paths,state:r});let n=await $r({paths:e.paths,state:r}),a=tD({state:r,local:n,envelope:e.envelope}),o;try{o=No(a.payload)}catch(d){throw new Error(`Native Verifier response was rejected: ${d.message}; correct the response and continue the same active Verifier`,{cause:d})}let s=rD(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=vi({local:n,projectRoot:i,supplied:e.checks}));let d=mk({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(d.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let p=await xS({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:d.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:d.response,reservation:p}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=d}catch(d){throw new Error(`Native Verifier response was rejected: ${d.message}; correct the response or request missing checks using the same active Verifier`,{cause:d})}let u=await he({paths:e.paths,previous:r,next:l.state});return await M(L(e.paths,r.name),gi({local:n,state:u,projectRoot:i}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await fi({file:Fu.join(le(e.paths,r.name),"verification.md"),state:u}),{kind:"final-result",result:{state:u,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await RS({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier-requested check execution failed: ${r.message}`,n=await A(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Cm({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Vf} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function jm(e){return A(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=await $r({paths:e.paths,state:t});if(CS({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Cm({paths:e.paths,state:t,summary:e.summary})})}async function Om(e){return A(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=CS({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=vi({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=gk({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await he({paths:e.paths,previous:t,next:a});return await M(L(e.paths,t.name),gi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await fi({file:Fu.join(le(e.paths,t.name),"verification.md"),state:o}),o})}async function Hm(e){return A(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Ze({paths:e.paths,state:t});let r=wk({state:t,summary:e.summary}),i=await he({paths:e.paths,previous:t,next:r});return await M(L(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await fi({file:Fu.join(le(e.paths,t.name),"verification.md"),state:i}),i})}async function Dm(e){return A(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Ze({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=yk(t,{reason:e.reason}),n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),gi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Bm(e){return A(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await $r({paths:e.paths,state:t}),i=Nk(t),n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),gi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function nn(e){return A(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks!==!1,i=r?await $r({paths:e.paths,state:t}):null,n=pi({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),a=await he({paths:e.paths,previous:t,next:n});return await M(L(e.paths,t.name),r?gi({local:i,state:a,projectRoot:e.paths.projectRoot}):ae({portableState:a,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Ps(e){if(e.state.verification===null)return"not-applicable";let t=Fu.join(le(e.paths,e.state.name),"verification.md");return await Zk({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await fi({file:t,state:e.state}),"rebuilt")}import iD from"node:path";kr();ve();async function Lm(e){return A(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Ze({paths:e.paths,state:t}),e.finish!==void 0&&!["keep","merge","push","pull-request"].includes(e.finish))throw new Error("Native workspace finish must be keep, merge, push, or pull-request");if(e.finish!==void 0&&t.workspace.isolation==="current")throw new Error("A workspace finish choice requires an isolated Native workspace");let r=await D(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Ki(r).stateVersion!==r.stateVersion)return la({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await F(e.paths,Yi(r,t))}let i=vk(t);e.finish!==void 0&&(i.workspace={...i.workspace,finish:e.finish});let n=await he({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await fi({file:iD.join(le(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as PS}from"node:fs";kr();ve();Ml();async function _s(e){let t=await H(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await Le({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function _S(e){let t=await H(e.paths,e.name),r=await Fl(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await D(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await PS.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Ki(n);if(i||a.stateVersion!==n.stateVersion){let o=await la({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await PS.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await F(e.paths,Yi(n,t)),{state:t,action:"recorded-final-verification"}}async function Mu(e){return A(e.paths,`recover Supervisor final verification ${e.name}`,()=>_S(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}var n6=16*1024;Gn();yn();var IS="comet.native.workspace-finish.v1",aD="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",jS=new RegExp(`^${aD}$`,"u"),oD=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,As=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function TS(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function sD(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==IS||typeof t.name!="string"||!jS.test(t.name)||typeof t.transactionId!="string"||!oD.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!pa.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"&&pa.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!pa.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");TS(r.commitMessage,"commit-message"),r.mergeMessage!==null&&TS(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||!As.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!pa.posix.isAbsolute(i)&&!pa.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!As.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!As.test(r.target)||!As.test(r.source)||r.sha!==null&&!As.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:IS,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 cD(e,t){if(!jS.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return pa.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function OS(e,t,r={}){let i=cD(e,t);try{let n=await AS.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=sD(JSON.parse(await AS.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}}import{randomUUID as lD}from"node:crypto";import{promises as Is}from"node:fs";import uD from"node:path";ne();rt();ve();ef();Ml();Dl();at();ie();var HS=["evidence.md","repair.md","archive.md","checkpoint.md"],dD="verification.md";async function pD(e,t){let r=await Fl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function DS(e,t){await Is.mkdir(e.transactionsDir,{recursive:!0}),await fe(ql(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function BS(e,t,r={}){let i=r.removeVerificationReport===!1?HS:[...HS,dD];await Promise.all([Is.rm(me(e,t),{recursive:!0,force:!0}),Is.rm(ch(e,t),{recursive:!0,force:!0}),...i.map(n=>Is.rm(uD.join(qt(e,t),n),{force:!0}))])}async function LS(e,t){await M(L(e,t.name),ae({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function qS(e,t){try{let r=await gs(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function FS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=oe(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function hD(e){let t=qt(e.paths,e.state.name),r=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Hl({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function MS(e,t){let r=await Kk(e,t);if(r.status==="runtime-incompatible")throw new Qt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function VS(e){return A(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await pD(e.paths,e.name),r=await na(e.paths,e.name)?await yt(dt(e.paths,e.name)):null;if(!t&&r)return await BS(e.paths,e.name,{removeVerificationReport:!1}),await LS(e.paths,r),r;let i=null,n=null;for(t||(i=await MS(e.paths,e.name),n=await qS(e.paths,e.name),FS(e.paths,n),t={schema:Bl,id:lD(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await DS(e.paths,t));;){let a=Ob(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await MS(e.paths,e.name),n??=await qS(e.paths,e.name),FS(e.paths,n),r=jb({state:i,acceptance:await hD({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await yo(dt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await BS(e.paths,e.name):a.action==="commit-transaction"&&(r??=await yt(dt(e.paths,e.name)),await LS(e.paths,r)),t={...t,status:a.nextStatus},await DS(e.paths,t)}return await Is.rm(ql(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??yt(dt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as zS}from"node:fs";import GS from"node:path";ve();import{promises as qm}from"node:fs";import fD from"node:path";pe();var mD=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),vD=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),gD=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),wD=new Set(["status","summary"]);function Vu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Wu(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 yD(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function an(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function bD(e,t,r,i){let n=Vu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Wu(n,mD,"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=Vu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Wu(o,vD,"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=Vu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Wu(c,wD,"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=Vu(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:h,contractHash:f,...m}=p,v=Wu(m,gD,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],w=g.covers.length>0?g.covers.map(y=>({id:y,source:r.acceptance_index?.[y]?.source??"brief.md",text:r.acceptance_index?.[y]?.text??y})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(h!==void 0&&JSON.stringify(h)!==JSON.stringify(w)||f!==void 0&&f!==$("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||!yD(p.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let N=g.depends_on.length===0?"ready":"pending";if(p.status!==N)return`Native Supervisor child ${g.name} has progressed beyond its initial ${N} 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 ha(e){let t=Di(e.paths,e.state.name),r;try{let c=await qm.lstat(t);if(!c.isFile()||c.isSymbolicLink())return an(t,"","Native Supervisor overlay is not a regular file");r=await qm.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:an(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return an(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=fD.join(e.paths.changesDir,e.state.name),a;try{a=await Je({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return an(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 D(e.paths,e.state.name)}catch(c){return an(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return an(t,r,"Native Supervisor overlay disappeared during inspection");let s=bD(i,e.state,a.contract,o);return s?an(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}}async function WS(e){let t=await ha({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await qm.rm(t.file,{force:!1})}at();ni();function Fm(e,t){let r=oe(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function ND(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function kD(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:ke(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(t),completed_at:i});return B({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?ND(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function SD(e){try{let t=await Ce(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Mm(e){return A(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Ps({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Fm(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await ha({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await WS({paths:e.paths,state:t,expected:i}),n=!0);let a=L(e.paths,e.name),o=await SD(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,c=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(c&&o.local?.execution?.status==="running"){let m=o.local.execution,v=await Bu(o.local),g=m.stage==="verifying"&&m.actor==="verifier"&&m.executionId!==null,w=v==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&m.stage==="checking"&&m.actor==="runtime";if(g||v!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:g?m.verifierStartedAt===void 0&&m.requestCheckRounds===0?`Native Verifier execution ${m.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${m.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:v==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(c&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(m=>m.status==="planned"||m.status==="running"?{...m,status:"interrupted"}:m)},await M(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Ps({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(m=>m.status==="interrupted"&&!m.repeatable):void 0;if(l){let m=pi({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Dn({file:dt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot}),await zS.rm(GS.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let v=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await M(a,v,{containedRoot:e.paths.runtimeDir}),{state:t,local:v,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",p=u||d;if(p){let m=kD(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Dn({file:dt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot})}let h=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:oe(e.paths.projectRoot).currentBranch});await zS.mkdir(GS.dirname(L(e.paths,t.name)),{recursive:!0}),await M(a,h,{containedRoot:e.paths.runtimeDir}),await Ps({paths:e.paths,state:t});let f=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:h,action:p?"reverify":"resume-stable-boundary",reason:s,message:f??(p?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`)}})}import JS from"node:path";function US(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Pe(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:US(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:US(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=>JS.relative(t.projectRoot,JS.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}mo();vo();function zu(e){return e.charCodeAt(0)===65279?e.slice(1):e}Vo();Gn();pe();import{randomUUID as ZS}from"node:crypto";import{promises as KS}from"node:fs";import Ts from"node:path";We();Fn();Hf();ko();ve();ji();function va(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function W(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function fa(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>W(r,`${t}[${i}]`))}function ED(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=va(t,`Native Builder check ${r}`);if(ee(i,["name","result","note"],`Native Builder check ${r}`,`/checks/${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:W(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function Gu(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=va(t,`Native Runtime check ${r}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`,`/checks/${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:W(i.id,`Native Runtime check ${r} id`),name:W(i.name,`Native Runtime check ${r} name`),executable:W(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:W(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function YS(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:W(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function xD(e){let t=va(e,"Native Supervisor evidence");return ee(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:W(t.summary,"Native Supervisor evidence summary"),checks:fa(t.checks,"Native Supervisor evidence checks"),acceptance:fl(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:W(t.receiptRef,"Native Supervisor receipt ref")}}}function eE(e){let t=va(e,"Native Runner input");if(t.kind==="builder-handoff"){let r=["kind","summary","addressed_acceptance_ids","checks","known_limits"];Object.hasOwn(t,"acceptance_review")&&r.push("acceptance_review"),Object.hasOwn(t,"verification_checks")&&r.push("verification_checks"),ee(t,Object.hasOwn(t,"review")?[...r,"review"]:r,"Native Runner Builder input");let i=null;if(t.review!==void 0&&t.review!==null){let n=va(t.review,"Native Builder review");if(ee(n,["status","summary","reviewer_execution_ref"],"Native Builder review","/review"),n.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");i={status:"passed",summary:W(n.summary,"Native Builder review summary"),reviewer_execution_ref:W(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:W(t.summary,"Native Builder summary"),...Object.hasOwn(t,"acceptance_review")?{acceptance_review:Tn(t.acceptance_review)}:{},addressed_acceptance_ids:fa(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:ED(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:Gu(t.verification_checks)}:{},known_limits:fa(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return ee(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:Gu(t.checks)};if(t.kind==="retry-checks")return ee(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:fa(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return ee(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:W(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:W(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:No(t.response,"/response")};if(t.kind==="verifier-started")return ee(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:W(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:W(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:W(t.summary,"Native Verifier execution error summary"),...YS(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:W(t.summary,"Native unavailable Verifier summary"),...YS(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ee(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),candidateCommit:W(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ee(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),reason:W(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(ee(t,["kind","child","stateVersion"],"Native Supervisor Builder retry input"),!Number.isSafeInteger(t.stateVersion)||t.stateVersion<1)throw new Error("Native Supervisor Builder retry stateVersion is invalid");return{kind:"supervisor-retry-builder",child:W(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return ee(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ee(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),reason:W(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ee(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:xD(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),checks:Gu(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:fa(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=va(i,"Native Supervisor material");return ee(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:W(a.name,"Native Supervisor material name"),content:W(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:W(t.child,"Native Supervisor child"),checks:Gu(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:fa(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function Jm(e,t){let r=Ts.resolve(t,e),i=await KS.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(zu(await KS.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return eE(n)}async function Um(e){await A(e.paths,"register-runner-input",async()=>{await lk({paths:e.paths,file:e.file,validateContent:t=>{let r=eE(JSON.parse(zu(t)));if($("comet.native.runner-input.v1",r)!==$("comet.native.runner-input.v1",e.input))throw new Error("Native Runner input changed after parsing")}})})}function RD(e){return e.kind==="builder-handoff"||e.kind==="dispatch-verifier"||e.kind==="retry-checks"||e.kind==="verifier-response"||e.kind==="verifier-started"||e.kind==="verifier-execution-error"||e.kind==="verifier-unavailable"}function CD(e){return e.kind.startsWith("supervisor-")}function PD(e){return e.response.kind!=="request-checks"?[]:e.response.checks.map(({id:t,name:r,executable:i,argv:n,cwdRef:a,timeoutMs:o,repeatable:s})=>({id:t,name:r,executable:i,argv:[...n],cwdRef:a,timeoutMs:o,repeatable:s}))}function XS(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.stage!=="verify-ready")throw new Error("Native Runner check input requires an active Verify-ready candidate")}function Vm(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result")throw new Error("Native Runner Verifier input requires an active Verifier attempt")}function _D(e,t){if(new Set(t).size!==t.length)throw new Error("Native Builder addressed acceptance IDs contain duplicates");let r=new Set(e.acceptance.map(({id:n})=>n)),i=t.filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native Builder addressed acceptance IDs contain unknown IDs: ${i.join(", ")}`)}async function Wm(e){let t=await Ce(L(e.paths,e.state.name)),r=t?.execution;if(t===null||t.basedOnStateVersion!==e.state.state_version||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null)throw new Error("Native Runner Verifier input requires an active Runtime Verifier execution");return r}async function Km(e){let t=await ha({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),i=r!==null&&e.state.phase==="verify"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),n=r!==null&&e.state.phase==="build"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),a=await Le({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(CD(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&RD(e.input)&&!i&&!(e.input.kind==="builder-handoff"&&n))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(e.input.kind==="builder-handoff"){if(e.state.phase!=="build"||e.state.status!=="active")throw new Error("Native Builder input requires an active Build boundary");if(_D(e.state,e.input.addressed_acceptance_ids),$n(e.state.acceptance,e.input.acceptance_review),a&&(!a.confirmed||!a.allDone))throw new Error("Native parent Build advances child changes and does not accept a Builder handoff");if(n&&e.state.loop.stage==="repairing"&&e.state.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first");e.input.verification_checks!==void 0&<(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(XS(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");lt(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(XS(e.state),e.input.check_ids.length===0||new Set(e.input.check_ids).size!==e.input.check_ids.length)throw new Error("Native check retry list must contain unique IDs");let c=await Ce(L(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(d=>d.id===l);if(!u||u.status!=="interrupted")throw new Error(`Native check retry ID is not an interrupted current check: ${l}`);if(!u.repeatable)throw new Error(`Native check ${l} is not repeatable and cannot be retried`);if(u.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${l}`)}return}if(e.input.kind==="verifier-response"){Vm(e.state);let c=await Wm({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");lt(o,PD(e.input));return}if(e.input.kind==="verifier-started"){Vm(e.state);let c=await Wm({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner started input is stale for the current candidate or execution");return}if(e.input.kind==="verifier-execution-error"||e.input.kind==="verifier-unavailable"){Vm(e.state);let c=await Wm({paths:e.paths,state:e.state});if(e.input.stateVersion!==e.state.state_version||e.input.iteration!==e.state.loop.iteration||e.input.attempt!==e.state.loop.attempt||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current attempt");return}let s=e.input;if(s.kind==="supervisor-retry-builder"){if(!r)throw new Error("Native Supervisor Builder retry requires a current Supervisor state");let c=r.children.find(({name:l})=>l===s.child);if(!c)throw new Error(`Native Supervisor child ${s.child} does not exist`);if(s.stateVersion!==r.stateVersion||c.status!=="blocked"||c.task!==null||(c.builderFailureCount??0)<Nr)throw new Error("Native Supervisor Builder retry input is stale or not currently required");return}if(e.input.kind==="supervisor-checks"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:u})=>u)).size!==c.checks.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(c.checks.some(({repeatable:u})=>!u))throw new Error("Native Supervisor checks must be repeatable for safe recovery");let l=r?.children.find(({name:u})=>u===c.child)?.task;if(!l||l.role!=="verifier"||l.runId!==c.runId)throw new Error("Native Supervisor check runId is not current");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");lt(l.projectRoot,c.checks);return}if(e.input.kind==="supervisor-integrate"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:l})=>l)).size!==c.checks.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(c.checks.some(({repeatable:l})=>!l))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");lt(r.integration.worktree,c.checks)}}function tE(e){return`${Se}:${e}:${ZS()}`}function QS(e,t,r,i){if(Ts.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==Ts.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!tr(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function AD(e,t){let r=oe(e.projectRoot),i=Ts.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Ts.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!tr(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function ma(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Se)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function ID(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function rE(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=ma(r),s=ID(r),c=r.acceptance.filter(({result:d})=>d==="pending").map(({id:d})=>d),l=r.acceptance.filter(({id:d})=>c.includes(d)).map(({id:d,source:p,text:h})=>({id:d,source:p,text:h})),u=l.length<=Yh.maxItems&&Buffer.byteLength(JSON.stringify(l),"utf8")<=Yh.maxSerializedBytes;return{coordination:Se,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:le(t,r.name),supervisorStateRef:a?Di(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:d,operation:p,source:h})=>({capability:d,operation:p,ref:h})),acceptanceCount:r.acceptance.length,scopeCount:c.length,scopeIds:c,...u?{acceptance:l}:{},startupInput:{kind:"verifier-started",candidateId:o.candidate_id,verifierExecutionRef:n},detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:o.review?{status:o.review.status,summary:o.review.summary}:null,builderSummary:o.summary.text,runtimeChecks:i.map(d=>({...d})),builderReportedChecks:o.checks.map(d=>({...d})),builderKnownLimits:o.known_limits.map(d=>({...d})),startupInstruction:"As this Verifier, submit the startup receipt first: copy startupInput into a temporary JSON file and run comet native next <change> --runner-input <file> --project-root <projectRoot above>. It records that this Verifier actually started; a repeat submission is accepted without side effects. Read acceptance when included; otherwise follow detailsPageArgs until every scopeId has been read. Then inspect the linked brief and Spec and proceed.",evidenceInstruction:"Independently inspect the current candidate against every scenario in scopeIds exactly once. Runtime checks are bound evidence; Builder-reported checks and review are claims to corroborate, not Runtime receipts. Reuse applicable completed evidence, request only missing or invalidated checks, and do not repeat full suites by default. Use one Verifier for this dispatch; keep it running across wait-tool timeouts. Return the actual scoped findings, risks, and incomplete checks without omitting limitations. Keep using the same CLI executable that produced this dispatch; do not switch to a different PATH installation.",responseInstruction:"Return one acceptance entry for each ID in scopeIds and no other acceptance IDs. Runtime safely filters a known already-passed superset only when every extra entry still reports passed; nonexistent IDs and conflicting out-of-scope results remain invalid."}}async function zm(e){let t=tE("verifier"),r=await Im({paths:e.paths,name:e.name,checks:e.checks,verifierExecutionId:t,...e.supervisor?{projectRoot:e.supervisor.integration.worktree}:{}});return{state:r,checks:e.checks,runtimeCheckExecution:{disposition:e.disposition},requestChecks:null,verifierDispatch:rE({paths:e.paths,state:r,checks:e.checks,verifierExecutionRef:t,supervisor:e.supervisor}),continuation:Y(r,void 0,{verifierExecutionRef:t,verifierStartup:"unconfirmed"})}}async function Gm(e){ma(e.state);let t=await Ce(L(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function iE(e){let t=e.input;e.inputFile&&await Um({paths:e.paths,file:e.inputFile,input:t});let r=await H(e.paths,e.name),i=await ha({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:f})=>f==="integrated"||f==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:f})=>f==="integrated"||f==="archived");if(n&&t.kind==="supervisor-checks"){let f=await Of({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await D(e.paths,e.name),v=m?.children.find(({name:g})=>g===t.child)?.task;return{state:r,supervisorState:m,supervisorTask:v&&v.runId===t.runId?ri(v,e.name,e.paths.projectRoot):null,checks:[],checkExecution:f,requestChecks:null,verifierDispatch:null,continuation:Y(r)}}if(n&&t.kind==="supervisor-builder-result")return A(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=f.children.find(({name:y})=>y===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{QS(m.task,t.candidateCommit,"builder",`comet/supervisor/${f.parent}/${t.child}`)}catch(y){throw await F(e.paths,Co(f,{child:t.child,runId:t.runId,reason:y.message})),y}let v=m.task.projectRoot,g=Sh(f,t),w=Ro(g,{role:"verifier",child:t.child,projectRoot:v,runId:ZS()});await F(e.paths,w.state);let N=await H(e.paths,e.name);return{state:N,supervisorTask:ri(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(N)}});if(n&&t.kind==="supervisor-builder-failure")return A(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=f.children.find(({name:w})=>w===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let v=ml(f,{child:t.child,runId:t.runId,reason:t.reason});await F(e.paths,v);let g=await H(e.paths,e.name);return{state:g,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(g)}});if(n&&t.kind==="supervisor-retry-builder")return A(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=xh(f,{child:t.child,expectedStateVersion:t.stateVersion});await F(e.paths,m);let v=await H(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}});if(n&&t.kind==="supervisor-reconnect")return A(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=f.children.find(({name:w})=>w===t.child)?.task;if(!m||m.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{AD(m,`comet/supervisor/${f.parent}/${t.child}`)}catch(w){throw await F(e.paths,Co(f,{child:t.child,runId:t.runId,reason:w.message})),w}let v=kh(f,{child:t.child,runId:t.runId});await F(e.paths,v.state);let g=await H(e.paths,e.name);return{state:g,supervisorState:v.state,supervisorTask:ri(v.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(g)}});if(n&&t.kind==="supervisor-cancel")return A(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=ml(f,{child:t.child,runId:t.runId,reason:t.reason});await F(e.paths,m);let v=await H(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}});if(n&&t.kind==="supervisor-verifier-result")return A(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let f=await D(e.paths,e.name);if(!f)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=f.children.find(({name:N})=>N===t.child);if(!m?.task||m.task.role!=="verifier"||!m.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{QS(m.task,m.candidateCommit,"verifier",`comet/supervisor/${f.parent}/${t.child}`)}catch(N){throw await F(e.paths,Co(f,{child:t.child,runId:t.runId,reason:N.message})),N}let v=t.evidence.receiptRef||t.verdict==="pass"?await Zn({paths:e.paths,parent:e.name,task:m.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!v||v.checks.some(({status:N,exitCode:y})=>N!=="passed"||y!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=Eh(f,{...t,evidence:{...t.evidence,checks:v?.checks.map(({name:N,status:y})=>`${N}: ${y}`)??[],execution:structuredClone(m.task)}});await F(e.paths,g);let w=await H(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(w)}});if(n&&t.kind==="supervisor-integrate"){let f=await Lf({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await _s({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=m.state;return{state:v,supervisorState:f,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:m.parentAdvance,continuation:Y(v)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="retry-checks"||t.kind==="verifier-response"||t.kind==="verifier-started"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){if(o&&t.verification_checks?.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let m=wh().captureExecutionIdentity({identityProvider:Se,executionRef:tE("builder")}),v=await Am({paths:e.paths,name:e.name,verificationChecks:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{},input:{identity:m,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,acceptanceReview:t.acceptance_review,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let g=await Cs({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=g.checks.filter(({status:E})=>E==="failed").map(({id:E})=>E),N=g.checks.filter(({status:E})=>E==="interrupted").map(({id:E})=>E),y=t.verification_checks.filter(({id:E,repeatable:b})=>N.includes(E)&&!b).map(({id:E})=>E);if(w.length>0||y.length>0){let E=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${y.join(", ")}`,b=await nn({paths:e.paths,name:e.name,reason:E,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:b,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},requestChecks:null,verifierDispatch:null,continuation:Y(b)}}return N.length===0?zm({paths:e.paths,name:e.name,checks:g.checks,disposition:g.disposition,supervisor:o?n:null}):{state:g.state,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},continuationCheckPlans:t.verification_checks,...N.length>0?{continuationRetryCheckIds:N}:{},requestChecks:null,verifierDispatch:null,continuation:Y(g.state,void 0,{...N.length>0?{retryCheckIds:N}:{verificationCheckPlans:t.verification_checks}})}}return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let f=await H(e.paths,e.name);ma(f);let m=await Pm({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks.filter(({status:g})=>g==="interrupted").map(({id:g})=>g);if(v.length>0){let w=((await Ce(L(e.paths,e.name)))?.checks??[]).filter(({id:N,status:y,executionCount:E})=>v.includes(N)&&y==="interrupted"&&E>=3).map(({id:N})=>N);if(w.length>0){let N=await nn({paths:e.paths,name:e.name,reason:`Native Runtime checks reached the retry limit after repeated interruptions: ${w.join(", ")}`,failureBudget:{maxVerifyFailures:e.maxVerifyFailures},preserveLocalChecks:!0});return{state:N,checks:m.checks,requestChecks:null,verifierDispatch:null,continuation:Y(N)}}}return v.length===0&&m.checks.every(({status:g})=>g==="passed")?zm({paths:e.paths,name:e.name,checks:m.checks,disposition:"executed",supervisor:a?n:null}):{state:m.state,checks:m.checks,...v.length>0?{continuationRetryCheckIds:v}:{},requestChecks:null,verifierDispatch:null,continuation:Y(m.state,void 0,{retryCheckIds:v.length>0?v:void 0})}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let f=await H(e.paths,e.name);if(f.builder_handoff!==null&&f.builder_handoff.identity_provider!==Se){let w=await nn({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:w,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(w)}}ma(f);let m=await Cs({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks,g=v.filter(({status:w})=>w==="interrupted").map(({id:w})=>w);if(g.length>0){let w=t.checks.filter(({id:y,repeatable:E})=>g.includes(y)&&!E).map(({id:y})=>y);if(w.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${w.join(", ")}`);let N=await H(e.paths,e.name);return{state:N,checks:v,runtimeCheckExecution:{disposition:m.disposition},continuationRetryCheckIds:g,requestChecks:null,verifierDispatch:null,continuation:Y(N,void 0,{retryCheckIds:g})}}return zm({paths:e.paths,name:e.name,checks:v,disposition:m.disposition,supervisor:a?n:null})}if(t.kind==="verifier-started"){let f=await Tm({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:f,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(f,void 0,{verifierExecutionRef:t.verifierExecutionRef,verifierStartup:"confirmed"})}}if(t.kind==="verifier-execution-error"){let f=await H(e.paths,e.name);ma(f),await Gm({paths:e.paths,state:f});let m=await jm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(m)}}if(t.kind==="verifier-unavailable"){let f=await Om({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:f,checks:f.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:Y(f)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await H(e.paths,e.name),c=ma(s),l=await Gm({paths:e.paths,state:s});if(t.candidateId!==c.candidate_id||t.verifierExecutionRef!==l)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");let u=wh(),d=u.captureExecutionIdentity({identityProvider:Se,executionRef:l}),p=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let f=await D(e.paths,e.name);if(!f)throw new Error("Native Supervisor state disappeared before final verification");p=Ki(f)}let h=await $m({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:d,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&h.response.kind==="final-result"){if(h.state.verification_result==="pass"&&(h.checks.length===0||h.checks.some(({status:v})=>v!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let f=p??await D(e.paths,e.name);if(!f)throw new Error("Native Supervisor state disappeared during verification");let m=Yi(f,h.state);return await F(e.paths,m),{...h,supervisorState:m,verifierDispatch:null,continuation:Y(h.state)}}return{...h,verifierDispatch:h.requestChecks===null?null:rE({paths:e.paths,state:h.state,checks:h.checks,verifierExecutionRef:await Gm({paths:e.paths,state:h.state}),supervisor:a?n:null}),continuation:Y(h.state,void 0,{verifierExecutionRef:l,verifierStartup:"confirmed"})}}ji();jn();co();import js from"path";import{realpathSync as vB}from"fs";function nE(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 jr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function aE(e){return e?e.command?`${jr.next} ${e.command}`:e.ask_user?`${jr.next} ${e.ask_user}`:null:null}function oE(e,t){let r=[e.summary],i=aE(e.next);return i&&r.push(i),e.user_message&&r.push("",jr.relay,e.user_message),t!==void 0&&r.push("",jr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
290
368
|
`)}
|
|
291
|
-
`}function
|
|
292
|
-
`)}
|
|
293
|
-
`)}}let r=t.continuation;if(
|
|
369
|
+
`}function sE(e,t,r){let i=[e.summary],n=aE(e.next);return n&&i.push(n),e.user_message&&i.push("",jr.relay,e.user_message),i.push("",`${jr.detail} ${t}`),r!==void 0&&i.push("",jr.details,JSON.stringify(r,null,2)),i.join(`
|
|
370
|
+
`)}pe();rt();pe();var TD=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});ui();Zt();gt();ie();ne();rr();Oo();ve();ie();Zt();ii();pe();pe();uu();Yn();rr();var cE={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:[]},$D=ut("comet-native-runtime:v3:scope-reopen"),k9=[{skillVersion:"3",skillHash:ut("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ut("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ut("comet-native-runtime:v1")}];rr();rr();Do();var uE=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],r4=new Set(uE),qD=new Set([...uE,"minimum_runtime_version","revision"]),i4=new Set([...qD,"operation"]),FD=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),n4=new Set([...FD,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Vo();rt();rt();Vo();pe();var l4={maxAcceptanceCriteria:Ol.maxCriteria};ui();Go();Yn();uu();import{execFile as YD}from"node:child_process";wn();Ya();Th();import{promisify as XD}from"node:util";ne();rr();ie();Zt();Za();ii();ve();ne();Sf();ie();Jt();ui();ve();ii();var $s=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Go();pu();Yn();var u3=64*1024;var d3=3600*1e3;var p3=XD(YD);pu();var Ju=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}};rr();Zt();ne();Jt();ie();Zt();Kl();ne();Vi();ui();var s8=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});rr();Oo();ve();ie();Zt();Kl();var Uu=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"},Ku=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"};ie();gt();function q(e,t,r){return e==="zh-CN"?r:t}var Ym={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function pE(e,t){return typeof e=="string"&&Ym[e]?q(t,Ym[e].en,Ym[e].zh):typeof e=="string"?e:""}function Xm(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 tB(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 hE(e,t){let r=[];e.failed>0&&r.push(q(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(q(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(q(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=q(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function fE(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 Qm(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function rB(e,t,r){return e==="done"?q(r,"complete","已完成"):e==="await-user"?q(r,"waiting for a user decision","等待用户决定"):e==="blocked"?q(r,"paused: needs attention","已暂停,需要处理"):t?q(r,"waiting for a user decision","等待用户决定"):q(r,"ready to continue","可继续推进")}function iB(e,t,r){let i=Qm(e),n=[];r&&n.push(r);let a=q(i,`Change ${e.change}`,`需求 ${e.change}`),o=pE(e.phase,i),s=rB(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(hE(t,i));let c=e.userCommunication,l=mE(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function mE(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:q(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:q(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:q(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function nB(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function aB(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=pE(e.phase,t),n=e.status==="await-user"?q(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?q(t,"paused","已暂停"):e.status==="done"?q(t,"complete","已完成"):q(t,"in progress","进行中"),a=Xm(e.acceptance)?`${q(t,", ",",")}${hE(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function oB(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 sB(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 cB(e){if(e.healthy){let i=e.repaired?q("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):q("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=lB(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:q("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:q("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function lB(e){return fE(e)?mE(e,Qm(e)):void 0}function vE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(sB(t))return cB(t);if(nB(t)){let i=oB(t.items);return{summary:[t.total===t.items.length?q(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):q(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>aB(a,i))].join(`
|
|
371
|
+
`)}}let r=t.continuation;if(fE(r)){let i=Qm(r),n=iB(r,uB(t),pB(t,i));return dB(t)==="unconfirmed"?{...n,summary:`${n.summary}${q(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:q(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 uB(e){if(Xm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Xm(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return tB(r.acceptance)}return null}function dB(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 pB(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return q(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?q(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function gE(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:q("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:q("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:q("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:q("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:q("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:q("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:q("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:q("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:q("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}mo();vo();var wE=["--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."],Zm=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:wE,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
|
|
294
372
|
comet native spec remove <change-name> <capability>
|
|
295
373
|
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>]
|
|
296
374
|
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>]
|
|
297
|
-
comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session
|
|
298
|
-
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
|
|
375
|
+
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>]
|
|
376
|
+
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 Yu(e,t){return`${e}:
|
|
299
377
|
${t.map(r=>` ${r}`).join(`
|
|
300
|
-
`)}`}function
|
|
301
|
-
${r.output}`),r.examples&&i.push("",
|
|
378
|
+
`)}`}function hB(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Zm[r]||t.length>1&&Zm[t[0]]?.subcommands?r:t[0]}function fB(e=[]){let t=hB(e),r=Zm[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",Yu("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",Yu("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...wE];return n&&n.length>0&&i.push("",Yu("Options",n)),i.push("",`Output:
|
|
379
|
+
${r.output}`),r.examples&&i.push("",Yu("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
302
380
|
`)}
|
|
303
|
-
`}}var
|
|
304
|
-
`}function
|
|
305
|
-
`}:e.error?{exitCode:e.exitCode,stderr:i?
|
|
306
|
-
${
|
|
381
|
+
`}}var mB=fB().usage;var v5=10*1024*1024,X=class extends Error{};function Vt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new X(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function dr(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new X(`${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 X(`${t} requires a value`);return e.splice(i,2),n}function bE(e){if(e.length>0)throw new X(`Unexpected argument: ${e[0]}`)}function NE(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new X(`${t} is required`);return r}function ev(e,t){let r=js.normalize(yE(e)),i=js.normalize(yE(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function yE(e){let t=js.resolve(e);try{return vB.native(t)}catch{return t}}function gB(e,t){let r=js.resolve(t,e),i=oe(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=oe(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!ev(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||ev(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:ev(t,i.currentWorktreeRoot)?js.resolve(t):i.currentWorktreeRoot}async function kE(e,t=process.cwd()){return e?gB(e,t):Qc(t)}function SE(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function EE(e){let t=await wy({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function xE(e){return JSON.stringify(e,null,2)+`
|
|
382
|
+
`}function et(e,t,r){return{command:e,exitCode:0,data:t,text:r??xE(t)}}function wB(e,t){if(t instanceof ca)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof In)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 fo)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof X)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Uu)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 Ku)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof _u)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 ys)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 ai)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Au)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 Ju)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof $s)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 on(e,t){let r=wB(e,t),i=r.error;if(!i)return r;let n=gE({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function yB(e,t,r=!1){let i=e.envelope??vE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:nE(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}})+`
|
|
383
|
+
`}:e.error?{exitCode:e.exitCode,stderr:i?sE(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:oE(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==xE(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
384
|
+
${jr.details}
|
|
307
385
|
${JSON.stringify(e.data,null,2)}
|
|
308
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function y0(e,t,r=!1){let i=w0(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 $k(e,t,r=!1){return y0(e,t,r).output}var N0=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function b0(e){let t=yr(e,"--expected-state-version"),r=yr(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new X("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new X("--expected-state-version must be a positive integer");if(!N0.has(r))throw new X("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Nr(e,t,r,i,n){let a=await ih({paths:e,name:t.name});a.local&&(r??=QN(t,a.local),i===void 0&&(i=Sb(a.local,a.local.workspace.projectRoot)));let o=await je({paths:e,state:t}),s=o?.confirmed?await O(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:f})=>f?[f.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:f})=>f==="interrupted").map(({id:f})=>f):void 0;return{...o?{childSummary:o.children.reduce((f,d)=>({...f,[d.status]:(f[d.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:K(t,o,{verifierExecutionRef:r,verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function k0(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function Ok(e){return{action:e.action,reason:e.reason,message:e.message}}async function Dk(e,t){let r=Ak(e,"change name"),i=yr(e,"--summary"),n=yr(e,"--runner-input"),a=jt(e,"--validate-only"),o=jt(e,"--confirmed"),s=jt(e,"--accept-result"),c=jt(e,"--revise-implementation"),l=jt(e,"--revise-requirements"),u=jt(e,"--retry-verifier"),f=jt(e,"--resolve-verifier-blocker"),d=yr(e,"--coordination-mode"),p=d;if(d!==void 0&&!Nc.includes(d))throw new X("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new X("--validate-only requires --runner-input");let m=yr(e,"--max-parallel"),h=m===void 0?2:Number(m);if(!Number.isSafeInteger(h)||h<1)throw new X("--max-parallel must be a positive integer");let g=b0(e);if([o,s,c,l,u,f].filter(Boolean).length>1)throw new X("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(p!==void 0&&(o||s||c||l||u||f||n!==void 0))throw new X("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");_k(e);let v=await Tk(t),w=await zb(v.paths,r);if(!await $n(v.paths,r)){if(w){let H={schema:"comet.native.continuation.v2",skill:"comet-native",change:r,phase:"archive",status:"blocked",disposition:"blocked",action:"archive",commandArgs:w.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0},userCommunication:{required:!0,message:w.result?.message??"Native Archive completed, but workspace finish is still pending.",suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the Git blocker; do not treat this change as complete until it succeeds."}};return{command:"next",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:w.result,continuation:H},error:{code:"conflict",message:w.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new X("--runner-input is only valid for portable Native changes");if(!i)throw new X("--summary is required");let C=await Zb({paths:v.paths,name:r});return Ze("next",{state:xe(C,v.paths),migration:{completed:!0,summary:i},continuation:K(C)})}let y=await $(v.paths,r);if(a){if(i||o||s||c||l||u||f||g||p!==void 0)throw new X("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let C;try{C=await Hh(n,t)}catch(H){return{...Wn("next",H),data:{state:xe(y,v.paths),continuation:K(y)}}}try{await Dh({paths:v.paths,name:r,state:y,input:C,projectRoot:t})}catch(H){return{...Wn("next",H),data:{state:xe(y,v.paths),continuation:K(y)}}}return Ze("next",{validation:{valid:!0,kind:C.kind},state:xe(y,v.paths),continuation:K(y)})}if(n!==void 0||!i||y.phase==="verify"||y.phase==="archive"||y.verification_result==="pass"){let C=Ah(v.paths,y);if(C)return Hk(v.paths,y,r,C)}if(n){if(i||o||s||c||l||u||f||p!==void 0||g)throw new X("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let C;try{C=await Hh(n,t),await Dh({paths:v.paths,name:r,state:y,input:C,projectRoot:t}),y.document_constraints_version===1&&await Gl({paths:v.paths,state:y})}catch(Ce){return{...Wn("next",Ce),data:{state:xe(y,v.paths),continuation:K(y)}}}let H=await ru({paths:v.paths,name:r});if(H.action==="rerun-final-verification")return Ze("next",{state:xe(H.state,v.paths),...await Nr(v.paths,H.state)});let P=await Ih({paths:v.paths,name:r,preserveRunningExecution:!0}),W=P.state;if(P.action==="await-user"||P.action==="done"||P.reason!=="available")return Ze("next",{state:xe(W,v.paths),recovery:Ok(P),...await Nr(v.paths,W)});if(W.phase==="build"){let Ce=await Bo({paths:v.paths,state:W});if(Ce.drifted){let zn=await Lo({paths:v.paths,name:r,reason:Ce.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return Ze("next",{state:xe(zn,v.paths),...await Nr(v.paths,zn)})}let Zt=await O(v.paths,r),et=await je({paths:v.paths,state:W});if(et&&!et.allDone&&!Zt)throw new X("Native parent Build advances child changes and does not accept a Builder handoff")}let ue=await fk({paths:v.paths,name:r,input:C,maxVerifyFailures:v.config.native.max_verify_failures}),$t="continuationCheckPlans"in ue?ue.continuationCheckPlans:void 0,ri="continuationRetryCheckIds"in ue?ue.continuationRetryCheckIds:void 0;return Ze("next",{...k0(ue),state:xe(ue.state,v.paths),...await Nr(v.paths,ue.state,ue.verifierDispatch?.verifierExecutionRef,$t,ri),coordination:Ne})}if(!i)throw new X("--summary is required");let S=await ru({paths:v.paths,name:r});if(S.action==="rerun-final-verification")return Ze("next",{state:xe(S.state,v.paths),...await Nr(v.paths,S.state)});let N=await Ih({paths:v.paths,name:r}),x=N.state;if(N.reason==="workspace-mismatch")return Hk(v.paths,x,r,N.message);if(p!==void 0&&x.phase!=="shape")throw new X("--coordination-mode is only valid when confirming Shape");let k,E=null;if(o)if(x.phase==="shape"&&x.status==="await-user"&&x.loop.next_action==="confirm-shape"){if(!g)throw new X("--expected-state-version and --expected-action are required for Shape confirmation");k=await wh({paths:v.paths,name:r,expectedContinuation:g})}else{if(x.phase==="shape")throw new X("--confirmed is only valid from the persisted Shape user confirmation boundary");if(x.phase==="verify"&&x.status==="await-user"&&x.loop.next_action==="confirm-verifier-unavailable")k=await xh({paths:v.paths,name:r,summary:i,expectedContinuation:g});else throw new X("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!g&&(x.phase!=="verify"||x.status!=="await-user"||x.loop.next_action!=="confirm-skill-coordinated-pass"))throw new X("--accept-result is only valid for a pending Verify pass decision");k=await Ph({paths:v.paths,name:r,expectedContinuation:g})}else if(c){if(x.phase!=="verify")throw new X("--revise-implementation is only valid from Verify");k=await Hi({paths:v.paths,name:r,reason:i,expectedContinuation:g})}else if(l){if(!g&&x.phase!=="verify"&&x.phase!=="archive")throw new X("--revise-requirements is only valid from Verify or Archive");k=await Lo({paths:v.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:g})}else if(u)k=await Rh({paths:v.paths,name:r,expectedContinuation:g});else if(f)k=await Ch({paths:v.paths,name:r,reason:i,expectedContinuation:g});else{if(N.reason!=="available"){let W=((await je({paths:v.paths,state:x}))?.confirmed?await O(v.paths,x.name,{diagnostics:!0}):null)?.children.flatMap(({task:ue})=>ue?[Lr(ue,x.name,v.paths.projectRoot)]:[])??[];return Ze("next",{state:xe(x,v.paths),recovery:Ok(N),...await Nr(v.paths,x),...W.length>0?{supervisorTasks:W}:{}})}if(x.phase==="build"){let H=await Bo({paths:v.paths,state:x});if(H.drifted)k=await Lo({paths:v.paths,name:r,reason:H.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let P=await je({paths:v.paths,state:x});if(P){let W=P,ue=[],$t=[],ri=null,Ce=await O(v.paths,r);if(Ce&&!P.allDone){let Zt=await Up({paths:v.paths,parent:r,maxParallel:x.coordination_mode==="single-session"?1:h});ue=Zt.state.children.flatMap(({task:et})=>et?[Lr(et,r,v.paths.projectRoot)]:[]),ri=Zt.tasks.map(({child:et})=>et),$t=Zt.state.children.flatMap(({name:et,blocker:zn})=>zn?[{child:et,message:zn}]:[]),(ue.length>0||Zt.state.stateVersion!==Ce.stateVersion)&&(W=await je({paths:v.paths,state:x})??W)}if(W.allDone&&!(x.loop.stage==="repairing"&&x.verification_result==="fail"))E=await Go({paths:v.paths,name:r,trigger:"recovery"}),k=E.state;else return Ze("next",{state:xe(x,v.paths),childSummary:W.children.reduce((Zt,et)=>({...Zt,[et.status]:(Zt[et.status]??0)+1}),{total:W.children.length}),readyChildren:ri??W.readyChildren,...ue.length>0?{supervisorTasks:ue}:{},...$t.length>0?{supervisorBlockers:$t}:{},continuation:K(x,W)})}}}if(x.phase==="shape"&&(k=await ph({paths:v.paths,name:r,enforceDocumentConstraints:!0,...p===void 0?{}:{coordinationMode:p},expectedContinuation:g})),k)return Ze("next",{state:xe(k,v.paths),...E?{parentAdvance:E.parentAdvance}:{},...await Nr(v.paths,k)});let C=x.phase==="shape"?await je({paths:v.paths,state:x}):null;return{command:"next",exitCode:65,data:{state:xe(x,v.paths),continuation:K(x,C)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return Ze("next",{state:xe(k,v.paths),...p===void 0?{}:{coordinationMode:p},...await Nr(v.paths,k)})}async function Hk(e,t,r,i){let n=K(t),a=t.language==="zh-CN"?`先恢复此需求绑定的工作区和分支,再运行 comet native status ${r} --json 获取下一步;当前操作未推进状态,不要重复请求验收确认。`:`Restore the workspace and branch bound to this change, then run comet native status ${r} --json for the next action. No transition occurred; do not request acceptance again.`;return Ze("next",{state:xe(t,e),...await Nr(e,t),recovery:{action:"await-user",reason:"workspace-mismatch",message:i},continuation:{...n,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...n.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${i}. ${a}`,suggestedReply:null,agentInstruction:a}}})}async function Bk(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{jt(n,"--json"),jt(n,"--verbose"),c=yr(n,"--project-root");let f=[...n,...a],d=await Ik(c);l={executionCwd:d,...await t(f,d)}}catch(f){l=Wn(e,f)}let u=$k(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
386
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function bB(e,t,r=!1){let i=yB(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 RE(e,t,r=!1){return bB(e,t,r).output}var NB=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function kB(e){let t=dr(e,"--expected-state-version"),r=dr(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new X("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new X("--expected-state-version must be a positive integer");if(!NB.has(r))throw new X("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function pr(e,t,r,i,n){let a=await Qf({paths:e,name:t.name});a.local&&(r??=Kf(t,a.local),i===void 0&&(i=lS(a.local,a.local.workspace.projectRoot)));let o=await Le({paths:e,state:t}),s=o?.confirmed?await D(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:d})=>d?[d.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:d})=>d==="interrupted").map(({id:d})=>d):void 0;return{...o?{childSummary:o.children.reduce((d,p)=>({...d,[p.status]:(d[p.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:Y(t,o,{verifierExecutionRef:r,verifierStartup:Sk(t,a.localStatus==="available"?a.local:null),verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function SB(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function CE(e){return{action:e.action,reason:e.reason,message:e.message}}async function _E(e,t){let r=NE(e,"change name"),i=dr(e,"--summary"),n=dr(e,"--runner-input"),a=Vt(e,"--validate-only"),o=Vt(e,"--confirmed"),s=Vt(e,"--accept-result"),c=dr(e,"--finish");if(c!==void 0&&(!s||!["keep","merge","push","pull-request"].includes(c)))throw new X("--finish requires --accept-result and must be keep, merge, push, or pull-request");let l=Vt(e,"--revise-implementation"),u=Vt(e,"--revise-requirements"),d=Vt(e,"--retry-verifier"),p=Vt(e,"--resolve-verifier-blocker"),h=dr(e,"--coordination-mode"),f=h;if(h!==void 0&&!il.includes(h))throw new X("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new X("--validate-only requires --runner-input");let m=dr(e,"--max-parallel"),v=m===void 0?2:Number(m);if(!Number.isSafeInteger(v)||v<1)throw new X("--max-parallel must be a positive integer");let g=kB(e);if([o,s,l,u,d,p].filter(Boolean).length>1)throw new X("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(f!==void 0&&(s||l||u||d||p||n!==void 0))throw new X("--coordination-mode is only valid when preparing or confirming a Supervisor Shape");bE(e);let w=await EE(t),N=await OS(w.paths,r);if(!await na(w.paths,r)){if(N){let _={schema:"comet.native.continuation.v2",skill:"comet-native",change:r,phase:"archive",status:"blocked",disposition:"blocked",requiresUserDecision:!1,action:"archive",commandArgs:N.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0},userCommunication:{required:!0,message:N.result?.message??"Native Archive completed, but workspace finish is still pending.",suggestedReply:null,agentInstruction:"Report the blocker and resolve it within the recorded delivery authorization, then retry the recorded command. Ask only if new information or authorization is needed; a retry of the same finish does not need another confirmation."}};return{command:"next",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:N.result,continuation:_},error:{code:"conflict",message:N.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new X("--runner-input is only valid for portable Native changes");if(!i)throw new X("--summary is required");let P=await VS({paths:w.paths,name:r});return et("next",{state:Pe(P,w.paths),migration:{completed:!0,summary:i},continuation:Y(P)})}let y=await H(w.paths,r);if(a){if(i||o||s||l||u||d||p||g||f!==void 0)throw new X("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let P;try{P=await Jm(n,t)}catch(_){let j=on("next",_);return{...j,data:{...j.data&&typeof j.data=="object"?j.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}try{await Km({paths:w.paths,name:r,state:y,input:P,projectRoot:t})}catch(_){let j=on("next",_);return{...j,data:{...j.data&&typeof j.data=="object"?j.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}return et("next",{validation:{valid:!0,kind:P.kind},state:Pe(y,w.paths),continuation:Y(y)})}if(n!==void 0||!i||y.phase==="verify"||y.phase==="archive"||y.verification_result==="pass"){let P=Fm(w.paths,y);if(P)return PE(w.paths,y,r,P)}if(n){if(i||o||s||l||u||d||p||f!==void 0||g)throw new X("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let P;try{P=await Jm(n,t),await Um({paths:w.paths,file:n,input:P}),await Km({paths:w.paths,name:r,state:y,input:P,projectRoot:t}),y.document_constraints_version===1&&await ju({paths:w.paths,state:y})}catch(hr){let _e=on("next",hr);return{..._e,data:{..._e.data&&typeof _e.data=="object"?_e.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}let _=await Mu({paths:w.paths,name:r});if(_.action==="rerun-final-verification")return et("next",{state:Pe(_.state,w.paths),...await pr(w.paths,_.state)});let j=await Mm({paths:w.paths,name:r,preserveRunningExecution:!0}),ue=j.state;if(j.action==="await-user"||j.action==="done"||j.reason!=="available")return et("next",{state:Pe(ue,w.paths),recovery:CE(j),...await pr(w.paths,ue)});if(ue.phase==="build"){let hr=await Ns({paths:w.paths,state:ue});if(hr.drifted){let ga=await ks({paths:w.paths,name:r,reason:hr.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return et("next",{state:Pe(ga,w.paths),...await pr(w.paths,ga)})}let _e=await D(w.paths,r),Ae=await Le({paths:w.paths,state:ue});if(Ae&&!Ae.allDone&&!_e)throw new X("Native parent Build advances child changes and does not accept a Builder handoff")}let de;try{de=await iE({paths:w.paths,name:r,input:P,inputFile:n,maxVerifyFailures:w.config.native.max_verify_failures})}catch(hr){let _e=await H(w.paths,r),Ae=on("next",hr);return{...Ae,data:{...Ae.data&&typeof Ae.data=="object"?Ae.data:{},state:Pe(_e,w.paths),...await pr(w.paths,_e)}}}let Or="continuationCheckPlans"in de?de.continuationCheckPlans:void 0,tt="continuationRetryCheckIds"in de?de.continuationRetryCheckIds:void 0;return et("next",{...SB(de),state:Pe(de.state,w.paths),...await pr(w.paths,de.state,de.verifierDispatch?.verifierExecutionRef,Or,tt),coordination:Se})}if(!i)throw new X("--summary is required");let b=await Mu({paths:w.paths,name:r});if(b.action==="rerun-final-verification")return et("next",{state:Pe(b.state,w.paths),...await pr(w.paths,b.state)});let x=await Mm({paths:w.paths,name:r}),k=x.state;if(x.reason==="workspace-mismatch")return PE(w.paths,k,r,x.message);if(f!==void 0&&k.phase!=="shape")throw new X("--coordination-mode is only valid when confirming Shape");let S,C=null;if(o)if(k.phase==="shape"&&k.status==="await-user"&&k.loop.next_action==="confirm-shape"){if(!g)throw new X("--expected-state-version and --expected-action are required for Shape confirmation");S=await _m({paths:w.paths,name:r,expectedContinuation:g,...f===void 0?{}:{coordinationMode:f}})}else{if(k.phase==="shape")throw new X("--confirmed is only valid from the persisted Shape user confirmation boundary");if(k.phase==="verify"&&k.status==="await-user"&&k.loop.next_action==="confirm-verifier-unavailable")S=await Hm({paths:w.paths,name:r,summary:i,expectedContinuation:g});else throw new X("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!g&&(k.phase!=="verify"||k.status!=="await-user"||k.loop.next_action!=="confirm-skill-coordinated-pass"))throw new X("--accept-result is only valid for a pending Verify pass decision");S=await Lm({paths:w.paths,name:r,expectedContinuation:g,finish:c})}else if(l){if(k.phase!=="verify")throw new X("--revise-implementation is only valid from Verify");S=await nn({paths:w.paths,name:r,reason:i,expectedContinuation:g})}else if(u){if(!g&&k.phase!=="verify"&&k.phase!=="archive")throw new X("--revise-requirements is only valid from Verify or Archive");S=await ks({paths:w.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:g})}else if(d)S=await Bm({paths:w.paths,name:r,expectedContinuation:g});else if(p)S=await Dm({paths:w.paths,name:r,reason:i,expectedContinuation:g});else{if(x.reason!=="available"){let ue=((await Le({paths:w.paths,state:k}))?.confirmed?await D(w.paths,k.name,{diagnostics:!0}):null)?.children.flatMap(({task:de})=>de?[ri(de,k.name,w.paths.projectRoot)]:[])??[];return et("next",{state:Pe(k,w.paths),recovery:CE(x),...await pr(w.paths,k),...ue.length>0?{supervisorTasks:ue}:{}})}if(k.phase==="build"){let _=await Ns({paths:w.paths,state:k});if(_.drifted)S=await ks({paths:w.paths,name:r,reason:_.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let j=await Le({paths:w.paths,state:k});if(j){let ue=j,de=[],Or=[],tt=null,hr=await D(w.paths,r);if(hr&&!j.allDone){let _e=await qf({paths:w.paths,parent:r,maxParallel:k.coordination_mode==="single-session"?1:v});de=_e.state.children.flatMap(({task:Ae})=>Ae?[ri(Ae,r,w.paths.projectRoot)]:[]),tt=_e.tasks.map(({child:Ae})=>Ae),Or=_e.state.children.flatMap(({name:Ae,blocker:ga})=>ga?[{child:Ae,message:ga}]:[]),(de.length>0||_e.state.stateVersion!==hr.stateVersion)&&(ue=await Le({paths:w.paths,state:k})??ue)}if(ue.allDone&&!(k.loop.stage==="repairing"&&k.verification_result==="fail"))C=await _s({paths:w.paths,name:r,trigger:"recovery"}),S=C.state;else return et("next",{state:Pe(k,w.paths),childSummary:ue.children.reduce((_e,Ae)=>({..._e,[Ae.status]:(_e[Ae.status]??0)+1}),{total:ue.children.length}),readyChildren:tt??ue.readyChildren,...de.length>0?{supervisorTasks:de}:{},...Or.length>0?{supervisorBlockers:Or}:{},continuation:Y(k,ue)})}}}if(k.phase==="shape"&&(S=await bm({paths:w.paths,name:r,enforceDocumentConstraints:!0,...f===void 0?{}:{coordinationMode:f},expectedContinuation:g})),S)return et("next",{state:Pe(S,w.paths),...C?{parentAdvance:C.parentAdvance}:{},...await pr(w.paths,S)});let P=k.phase==="shape"?await Le({paths:w.paths,state:k}):null;return et("next",{state:Pe(k,w.paths),continuation:Y(k,P)})}return et("next",{state:Pe(S,w.paths),...f===void 0?{}:{coordinationMode:f},...await pr(w.paths,S)})}async function PE(e,t,r,i){let n=Y(t),a=t.language==="zh-CN"?`先恢复此需求绑定的工作区和分支,再运行 comet native status ${r} --json 获取下一步;当前操作未推进状态,不要重复请求验收确认。`:`Restore the workspace and branch bound to this change, then run comet native status ${r} --json for the next action. No transition occurred; do not request acceptance again.`;return et("next",{state:Pe(t,e),...await pr(e,t),recovery:{action:"await-user",reason:"workspace-mismatch",message:i},continuation:{...n,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...n.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${i}. ${a}`,suggestedReply:null,agentInstruction:a}}})}async function AE(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{Vt(n,"--json"),Vt(n,"--verbose"),c=dr(n,"--project-root");let d=[...n,...a],p=async()=>{let h=await kE(c);return{executionCwd:h,...await t(d,h)}};l=SE(e,d)?await Uw(p):await p()}catch(d){l=on(e,d)}let u=RE(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
309
387
|
`)?"":`
|
|
310
|
-
`)),u.exitCode}process.exitCode=await
|
|
388
|
+
`)),u.exitCode}process.exitCode=await AE("next",_E);
|