@rpamis/comet 0.4.0-beta.17 → 0.4.0-beta.18
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 +49 -24
- package/assets/manifest.json +2 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +128 -128
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +78 -78
- package/assets/skills/comet/scripts/comet-guard.mjs +144 -144
- package/assets/skills/comet/scripts/comet-handoff.mjs +109 -109
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +130 -130
- package/assets/skills/comet/scripts/comet-hook-router.mjs +115 -115
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +85 -85
- package/assets/skills/comet/scripts/comet-runtime.mjs +188 -187
- package/assets/skills/comet/scripts/comet-state.mjs +117 -117
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +71 -71
- package/assets/skills/comet-build/SKILL.md +15 -56
- package/assets/skills/comet-classic/SKILL.md +14 -8
- package/assets/skills/comet-classic/reference/comet-yaml-fields.md +1 -1
- package/assets/skills/comet-classic/reference/scripts.md +3 -1
- package/assets/skills/comet-classic/reference/workspace.md +23 -0
- package/assets/skills/comet-native/SKILL.md +13 -10
- package/assets/skills/comet-native/reference/artifacts.md +3 -2
- package/assets/skills/comet-native/reference/commands.md +1 -1
- package/assets/skills/comet-native/reference/recovery.md +1 -1
- package/assets/skills/comet-native/reference/workspace.md +4 -4
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +97 -97
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +146 -146
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +100 -100
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +85 -85
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +115 -115
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +118 -118
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +107 -107
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +154 -154
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +133 -133
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +109 -109
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +87 -87
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +109 -109
- package/assets/skills/comet-open/SKILL.md +24 -5
- package/assets/skills-zh/comet-build/SKILL.md +15 -56
- package/assets/skills-zh/comet-classic/SKILL.md +14 -8
- package/assets/skills-zh/comet-classic/reference/comet-yaml-fields.md +1 -1
- package/assets/skills-zh/comet-classic/reference/scripts.md +3 -1
- package/assets/skills-zh/comet-classic/reference/workspace.md +23 -0
- package/assets/skills-zh/comet-native/SKILL.md +13 -10
- package/assets/skills-zh/comet-native/reference/artifacts.md +3 -2
- package/assets/skills-zh/comet-native/reference/commands.md +1 -1
- package/assets/skills-zh/comet-native/reference/recovery.md +1 -1
- package/assets/skills-zh/comet-native/reference/workspace.md +4 -4
- package/assets/skills-zh/comet-open/SKILL.md +24 -5
- package/dist/app/cli/index.js +20 -1
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/classic.d.ts.map +1 -1
- package/dist/app/commands/classic.js +2 -0
- package/dist/app/commands/classic.js.map +1 -1
- package/dist/app/commands/eval.d.ts +9 -2
- package/dist/app/commands/eval.d.ts.map +1 -1
- package/dist/app/commands/eval.js +293 -48
- package/dist/app/commands/eval.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +2 -1
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +4 -1
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/comet-classic/classic-cli.d.ts +1 -1
- package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-cli.js +3 -0
- package/dist/domains/comet-classic/classic-cli.js.map +1 -1
- package/dist/domains/comet-classic/classic-current-change.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-current-change.js +29 -3
- package/dist/domains/comet-classic/classic-current-change.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard.js +2 -2
- package/dist/domains/comet-classic/classic-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.js +14 -1
- package/dist/domains/comet-classic/classic-hook-guard.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 +31 -8
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-workspace-command.d.ts +3 -0
- package/dist/domains/comet-classic/classic-workspace-command.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-workspace-command.js +45 -0
- package/dist/domains/comet-classic/classic-workspace-command.js.map +1 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts +38 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-workspace.js +315 -0
- package/dist/domains/comet-classic/classic-workspace.js.map +1 -0
- package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-adapter.js +1 -0
- package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.d.ts +2 -0
- package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
- package/dist/domains/comet-entry/hook-router-entry.js +21 -1
- package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
- package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
- package/dist/domains/comet-entry/init-workflow.js +13 -5
- package/dist/domains/comet-entry/init-workflow.js.map +1 -1
- package/dist/domains/comet-native/index.d.ts +1 -0
- package/dist/domains/comet-native/index.d.ts.map +1 -1
- package/dist/domains/comet-native/index.js +1 -0
- package/dist/domains/comet-native/index.js.map +1 -1
- package/dist/domains/comet-native/native-children.d.ts +49 -0
- package/dist/domains/comet-native/native-children.d.ts.map +1 -0
- package/dist/domains/comet-native/native-children.js +388 -0
- package/dist/domains/comet-native/native-children.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 +3 -3
- package/dist/domains/comet-native/native-cli-help.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 +10 -5
- package/dist/domains/comet-native/native-doctor-command.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 +41 -2
- package/dist/domains/comet-native/native-hook-guard.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 +85 -5
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts +3 -2
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +63 -1
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts +5 -0
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +110 -4
- package/dist/domains/comet-native/native-portable-runtime.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 +13 -0
- package/dist/domains/comet-native/native-portable-state.js.map +1 -1
- package/dist/domains/comet-native/native-portable-status.d.ts +3 -0
- package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-status.js +9 -1
- package/dist/domains/comet-native/native-portable-status.js.map +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts +1 -0
- 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-show-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-show-command.js +2 -1
- package/dist/domains/comet-native/native-show-command.js.map +1 -1
- package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-workspace-preparation.js +192 -133
- package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -1
- package/dist/domains/dashboard/collector.d.ts +1 -1
- package/dist/domains/dashboard/collector.d.ts.map +1 -1
- package/dist/domains/dashboard/collector.js +102 -87
- package/dist/domains/dashboard/collector.js.map +1 -1
- package/dist/domains/dashboard/native-adapter.d.ts +20 -0
- package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-adapter.js +11 -0
- package/dist/domains/dashboard/native-adapter.js.map +1 -1
- package/dist/domains/dashboard/native-collector.d.ts +1 -0
- package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
- package/dist/domains/dashboard/native-collector.js +304 -55
- package/dist/domains/dashboard/native-collector.js.map +1 -1
- package/dist/domains/dashboard/native-legacy-adapter.d.ts +12 -5
- package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -1
- package/dist/domains/dashboard/native-legacy-adapter.js +12 -0
- package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -1
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +5 -3
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/types.d.ts +5 -0
- package/dist/domains/dashboard/types.d.ts.map +1 -1
- package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-B5cFR6hS.js +1 -0
- package/dist/domains/dashboard/web/assets/arc-CVQDtMsu.js +1 -0
- package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-C0v0kULK.js +36 -0
- package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-DpHLuxu4.js +132 -0
- package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-BL17BIb8.js → c4Diagram-5PPSVZJV-BHnFxUs1.js} +1 -1
- package/dist/domains/dashboard/web/assets/channel-eM0x3m1G.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-XWLMOyd4.js → chunk-2GRJ4B5K-CGC9gh5n.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-4drjXzHQ.js → chunk-2Q5K7J3B-l4puLU_O.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-ls9jQHZc.js +231 -0
- package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-CQXqBSqQ.js → chunk-5VM5RSS4-BVavmTEq.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-Dungt2g9.js +88 -0
- package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-pMreYMW7.js → chunk-GF5L2VYU-BidXO_ZP.js} +5 -5
- package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-vQyyh3eG.js → chunk-JWPE2WC7-57L5Up5X.js} +1 -1
- package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-B_DDS2IK.js → chunk-KBJHAD2P-C5u5vbwr.js} +1 -1
- package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-CvLz21I2.js +1 -0
- package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-Cug8J1Qa.js → chunk-XXDRQBXY-D5nJpckG.js} +1 -1
- package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-CEFhao2K.js +1 -0
- package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-CEFhao2K.js +1 -0
- package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-IQKP-hgj.js → cose-bilkent-JH36ORCC-Dp0JAGyE.js} +1 -1
- package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-CvvRO4J2.js → cynefin-VYW2F7L2-EjC54l1g.js} +2 -2
- package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-CpYrW3w3.js +62 -0
- package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-h5K39rCk.js +4 -0
- package/dist/domains/dashboard/web/assets/{demo-CeIDHUFJ.js → demo-BfLsKrIL.js} +26 -5
- package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-CKQj9O4H.js +30 -0
- package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-CN_LYqvT.js → diagram-B4RE2ZJO-DXRIYcnW.js} +3 -3
- package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-wWutQYmv.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-EgXLJQYi.js +24 -0
- package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-CsQRXDQZ.js +41 -0
- package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-gm328Eho.js +1 -0
- package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-BbbMVUx_.js +85 -0
- package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-1Y7scCns.js +156 -0
- package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-BAoBqczv.js +292 -0
- package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-CaWEk3PM.js → gitGraphDiagram-DS77QQ5N-CMUAyEzl.js} +3 -3
- package/dist/domains/dashboard/web/assets/{graph--OzhPTMs.js → graph-DOmOIIwC.js} +1 -1
- package/dist/domains/dashboard/web/assets/{index-BNyOfAhu.js → index-CCApJ0Yr.js} +1 -1
- package/dist/domains/dashboard/web/assets/index-DWdm_XBi.js +257 -0
- package/dist/domains/dashboard/web/assets/{index-BFwKBVTJ.css → index-DhhbseFJ.css} +1 -1
- package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-BK07mNG0.js → infoDiagram-6WML65LV-BaCdtYYC.js} +1 -1
- package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-mWnmaWfZ.js → ishikawaDiagram-WSZJBQD7-DQQlNnjU.js} +4 -4
- package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-BPy-P7xx.js → journeyDiagram-NVQOT4AX-DW9wUMqn.js} +1 -1
- package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-3Jq9c_lo.js → kanban-definition-27J2QSJJ-C_ITaZ0q.js} +7 -7
- package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +1 -0
- package/dist/domains/dashboard/web/assets/{linear-kQyEW-4G.js → linear-DXOo6ZRT.js} +1 -1
- package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +1 -0
- package/dist/domains/dashboard/web/assets/mermaid.core-ol-0NI97.js +306 -0
- package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-CyyurUpv.js → mindmap-definition-FAOFIHXS-CHF_HOLV.js} +1 -1
- package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-wQEvkNF8.js +1 -0
- package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-C3H3kiIP.js +39 -0
- package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +3 -0
- package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-CpayUMjH.js → quadrantDiagram-CIZ2JOQS-S0FdVzJb.js} +4 -4
- package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-DCDXDaVg.js +1 -0
- package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-Bi8YpfnA.js → requirementDiagram-LRYGKXZP-BW8J4gO_.js} +1 -1
- package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-DQQBmLoy.js +40 -0
- package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-2tDcli0Y.js +162 -0
- package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-4sEZLBKb.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-OgPb8pyR.js +1 -0
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-CiDNPr4P.js +1 -0
- package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-DR7lwtxd.js +2 -0
- package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-DggHFP9q.js +8 -0
- package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-aHrrtV-b.js → timeline-definition-Z64GVDOM-DNIJVlQV.js} +4 -4
- package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-CClhw4QZ.js +34 -0
- package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-RVQbcySh.js → wardleyDiagram-T6FBY63Y-DzR3aFPS.js} +3 -3
- package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DZhq0ZRj.js +7 -0
- package/dist/domains/dashboard/web/index.html +2 -2
- package/dist/domains/dashboard/workspace.d.ts +24 -0
- package/dist/domains/dashboard/workspace.d.ts.map +1 -0
- package/dist/domains/dashboard/workspace.js +87 -0
- package/dist/domains/dashboard/workspace.js.map +1 -0
- package/dist/domains/eval/index.d.ts +3 -0
- package/dist/domains/eval/index.d.ts.map +1 -1
- package/dist/domains/eval/index.js +3 -0
- package/dist/domains/eval/index.js.map +1 -1
- package/dist/domains/eval/standalone-context.d.ts +19 -0
- package/dist/domains/eval/standalone-context.d.ts.map +1 -0
- package/dist/domains/eval/standalone-context.js +107 -0
- package/dist/domains/eval/standalone-context.js.map +1 -0
- package/dist/domains/eval/standalone-static-collect.d.ts +22 -0
- package/dist/domains/eval/standalone-static-collect.d.ts.map +1 -0
- package/dist/domains/eval/standalone-static-collect.js +779 -0
- package/dist/domains/eval/standalone-static-collect.js.map +1 -0
- package/dist/domains/eval/user-environment.d.ts +6 -0
- package/dist/domains/eval/user-environment.d.ts.map +1 -0
- package/dist/domains/eval/user-environment.js +73 -0
- package/dist/domains/eval/user-environment.js.map +1 -0
- package/dist/domains/integrations/openspec.d.ts +1 -1
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +110 -26
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/integrations/superpowers.d.ts +5 -1
- package/dist/domains/integrations/superpowers.d.ts.map +1 -1
- package/dist/domains/integrations/superpowers.js +21 -2
- package/dist/domains/integrations/superpowers.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts +1 -1
- package/dist/domains/skill/platform-install.js +1 -1
- package/dist/domains/skill/project-instructions.d.ts.map +1 -1
- package/dist/domains/skill/project-instructions.js +5 -3
- package/dist/domains/skill/project-instructions.js.map +1 -1
- package/dist/domains/workflow-contract/hook-write-policy.d.ts +9 -0
- package/dist/domains/workflow-contract/hook-write-policy.d.ts.map +1 -0
- package/dist/domains/workflow-contract/hook-write-policy.js +52 -0
- package/dist/domains/workflow-contract/hook-write-policy.js.map +1 -0
- package/dist/domains/workflow-contract/index.d.ts +2 -0
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +1 -0
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +2 -2
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +42 -2
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.d.ts +13 -0
- package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
- package/dist/domains/workflow-contract/protected-project-path.js +83 -0
- package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
- package/dist/domains/workflow-contract/types.d.ts +4 -0
- package/dist/domains/workflow-contract/types.d.ts.map +1 -1
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +13 -2
- package/dist/platform/install/platforms.js.map +1 -1
- package/dist/platform/paths/git-worktree.d.ts +7 -1
- package/dist/platform/paths/git-worktree.d.ts.map +1 -1
- package/dist/platform/paths/git-worktree.js +28 -7
- package/dist/platform/paths/git-worktree.js.map +1 -1
- package/eval/.env.example +115 -0
- package/eval/README.md +237 -14
- package/eval/langfuse/.env.example +9 -0
- package/eval/langfuse/tests/conftest.py +146 -0
- package/eval/langfuse/tests/tasks/test_tasks.py +109 -0
- package/eval/langfuse/tests/test_adapter.py +272 -0
- package/eval/langsmith/.env.example +16 -0
- package/eval/langsmith/tests/conftest.py +10 -1
- package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +4 -2
- package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +2 -2
- package/eval/local/tests/conftest.py +701 -80
- package/eval/local/tests/scaffold/fixtures/custom-agent/adapter.yaml +19 -0
- package/eval/local/tests/scaffold/test_agents.py +76 -0
- package/eval/local/tests/scaffold/test_aligned_comparison.py +70 -0
- package/eval/local/tests/scaffold/test_auto_tasks.py +350 -0
- package/eval/local/tests/scaffold/test_conftest_helpers.py +267 -18
- package/eval/local/tests/scaffold/test_custom_agents.py +174 -0
- package/eval/local/tests/scaffold/test_eval_context.py +217 -0
- package/eval/local/tests/scaffold/test_execution.py +364 -0
- package/eval/local/tests/scaffold/test_inline_tasks.py +56 -0
- package/eval/local/tests/scaffold/test_langfuse_trajectory.py +263 -0
- package/eval/local/tests/scaffold/test_langsmith_conftest.py +63 -0
- package/eval/local/tests/scaffold/test_logging.py +162 -0
- package/eval/local/tests/scaffold/test_manifest_tasks.py +76 -0
- package/eval/local/tests/scaffold/test_manifests.py +396 -0
- package/eval/local/tests/scaffold/test_native_aligned_eval.py +17 -0
- package/eval/local/tests/scaffold/test_profiles.py +64 -6
- package/eval/local/tests/scaffold/test_task_resolution.py +212 -0
- package/eval/local/tests/scaffold/test_utils.py +480 -4
- package/eval/local/tests/tasks/test_tasks.py +216 -14
- package/eval/pyproject.toml +5 -0
- package/eval/scaffold/__init__.py +6 -0
- package/eval/scaffold/docker/agent-overlay.Dockerfile +41 -0
- package/eval/scaffold/python/__init__.py +128 -20
- package/eval/scaffold/python/agents.py +239 -0
- package/eval/scaffold/python/aligned_comparison.py +156 -27
- package/eval/scaffold/python/auto_tasks.py +700 -0
- package/eval/scaffold/python/custom_agents.py +172 -0
- package/eval/scaffold/python/eval_context.py +236 -0
- package/eval/scaffold/python/eval_schema.py +135 -0
- package/eval/scaffold/python/execution.py +544 -0
- package/eval/scaffold/python/generated_task_cache.py +230 -0
- package/eval/scaffold/python/generic_llm_judge.py +41 -14
- package/eval/scaffold/python/inline_tasks.py +118 -0
- package/eval/scaffold/python/judge_config.py +158 -37
- package/eval/scaffold/python/langfuse_adapter.py +1023 -0
- package/eval/scaffold/python/llm_judge.py +68 -11
- package/eval/scaffold/python/logging.py +157 -17
- package/eval/scaffold/python/manifest_tasks.py +69 -0
- package/eval/scaffold/python/manifests.py +443 -22
- package/eval/scaffold/python/paths.py +11 -1
- package/eval/scaffold/python/task_resolution.py +176 -0
- package/eval/scaffold/python/tasks.py +17 -4
- package/eval/scaffold/python/utils.py +167 -11
- package/eval/scaffold/python/validation/core.py +48 -2
- package/eval/scaffold/python/validation/generic_rubric.py +9 -0
- package/eval/scaffold/python/validation/native_workflow.py +6 -1
- package/eval/scaffold/python/validation/rubric.py +16 -1
- package/eval/scaffold/shell/agent-runtime-config.sh +88 -0
- package/eval/scaffold/shell/docker.sh +534 -33
- package/eval/scaffold/shell/run-agent-runtime.sh +49 -0
- package/eval/scaffold/shell/run-claude-loop.sh +153 -14
- package/eval/schemas/comet.eval/v1alpha1.schema.json +244 -0
- package/package.json +8 -3
- package/dist/domains/dashboard/web/assets/arc-CkuYweSh.js +0 -1
- package/dist/domains/dashboard/web/assets/architectureDiagram-3BPJPVTR--tTGrKam.js +0 -36
- package/dist/domains/dashboard/web/assets/blockDiagram-GPEHLZMM-DLKYOixs.js +0 -132
- package/dist/domains/dashboard/web/assets/channel-Cg__FSMr.js +0 -1
- package/dist/domains/dashboard/web/assets/chunk-AQP2D5EJ-BUkV_rb7.js +0 -231
- package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CsC-pvu9.js +0 -1
- package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CsC-pvu9.js +0 -1
- package/dist/domains/dashboard/web/assets/dagre-BM42HDAG-DeOQo7bP.js +0 -4
- package/dist/domains/dashboard/web/assets/diagram-2AECGRRQ-IQd_jQwB.js +0 -43
- package/dist/domains/dashboard/web/assets/diagram-5GNKFQAL-Dllkdt0m.js +0 -10
- package/dist/domains/dashboard/web/assets/diagram-LMA3HP47-DK36WkNN.js +0 -24
- package/dist/domains/dashboard/web/assets/diagram-OG6HWLK6-iqUnMYEh.js +0 -24
- package/dist/domains/dashboard/web/assets/erDiagram-TEJ5UH35-Bc64lzy8.js +0 -85
- package/dist/domains/dashboard/web/assets/flowDiagram-I6XJVG4X-UfOqef9j.js +0 -162
- package/dist/domains/dashboard/web/assets/ganttDiagram-6RSMTGT7-D-u6Aauc.js +0 -292
- package/dist/domains/dashboard/web/assets/index-COZ_03uK.js +0 -257
- package/dist/domains/dashboard/web/assets/layout-SsrduOYp.js +0 -1
- package/dist/domains/dashboard/web/assets/mermaid.core-COBBjtVH.js +0 -301
- package/dist/domains/dashboard/web/assets/pieDiagram-4H26LBE5-CJro_XKk.js +0 -30
- package/dist/domains/dashboard/web/assets/purify.es-VaSPOPhr.js +0 -3
- package/dist/domains/dashboard/web/assets/sankeyDiagram-5OEKKPKP-Wx60WwHe.js +0 -40
- package/dist/domains/dashboard/web/assets/sequenceDiagram-3UESZ5HK-BiMsRFbc.js +0 -162
- package/dist/domains/dashboard/web/assets/stateDiagram-AJRCARHV-BrURMY0R.js +0 -1
- package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-BpEE-yEg.js +0 -1
- package/dist/domains/dashboard/web/assets/vennDiagram-CIIHVFJN-DGB16bvR.js +0 -34
- package/dist/domains/dashboard/web/assets/xychartDiagram-2RQKCTM6-DMzzwDVX.js +0 -7
|
@@ -1,147 +1,147 @@
|
|
|
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 jC=Object.create;var cg=Object.defineProperty;var $C=Object.getOwnPropertyDescriptor;var OC=Object.getOwnPropertyNames;var HC=Object.getPrototypeOf,DC=Object.prototype.hasOwnProperty;var zc=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var FC=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of OC(t))!DC.call(e,n)&&n!==i&&cg(e,n,{get:()=>t[n],enumerable:!(r=$C(t,n))||r.enumerable});return e};var ma=(e,t,i)=>(i=e!=null?jC(HC(e)):{},FC(t||!e||!e.__esModule?cg(i,"default",{value:e,enumerable:!0}):i,e));var Q=C(Xe=>{"use strict";var vf=Symbol.for("yaml.alias"),pg=Symbol.for("yaml.document"),Uc=Symbol.for("yaml.map"),mg=Symbol.for("yaml.pair"),gf=Symbol.for("yaml.scalar"),Kc=Symbol.for("yaml.seq"),ar=Symbol.for("yaml.node.type"),ex=e=>!!e&&typeof e=="object"&&e[ar]===vf,tx=e=>!!e&&typeof e=="object"&&e[ar]===pg,ix=e=>!!e&&typeof e=="object"&&e[ar]===Uc,rx=e=>!!e&&typeof e=="object"&&e[ar]===mg,vg=e=>!!e&&typeof e=="object"&&e[ar]===gf,nx=e=>!!e&&typeof e=="object"&&e[ar]===Kc;function gg(e){if(e&&typeof e=="object")switch(e[ar]){case Uc:case Kc:return!0}return!1}function ax(e){if(e&&typeof e=="object")switch(e[ar]){case vf:case Uc:case gf:case Kc:return!0}return!1}var ox=e=>(vg(e)||gg(e))&&!!e.anchor;Xe.ALIAS=vf;Xe.DOC=pg;Xe.MAP=Uc;Xe.NODE_TYPE=ar;Xe.PAIR=mg;Xe.SCALAR=gf;Xe.SEQ=Kc;Xe.hasAnchor=ox;Xe.isAlias=ex;Xe.isCollection=gg;Xe.isDocument=tx;Xe.isMap=ix;Xe.isNode=ax;Xe.isPair=rx;Xe.isScalar=vg;Xe.isSeq=nx});var Oo=C(wf=>{"use strict";var qe=Q(),xt=Symbol("break visit"),wg=Symbol("skip children"),Di=Symbol("remove node");function Yc(e,t){let i=yg(t);qe.isDocument(e)?va(null,e.contents,i,Object.freeze([e]))===Di&&(e.contents=null):va(null,e,i,Object.freeze([]))}Yc.BREAK=xt;Yc.SKIP=wg;Yc.REMOVE=Di;function va(e,t,i,r){let n=Ng(e,t,i,r);if(qe.isNode(n)||qe.isPair(n))return bg(e,r,n),va(e,n,i,r);if(typeof n!="symbol"){if(qe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=va(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===xt)return xt;o===Di&&(t.items.splice(a,1),a-=1)}}}else if(qe.isPair(t)){r=Object.freeze(r.concat(t));let a=va("key",t.key,i,r);if(a===xt)return xt;a===Di&&(t.key=null);let o=va("value",t.value,i,r);if(o===xt)return xt;o===Di&&(t.value=null)}}return n}async function Xc(e,t){let i=yg(t);qe.isDocument(e)?await ga(null,e.contents,i,Object.freeze([e]))===Di&&(e.contents=null):await ga(null,e,i,Object.freeze([]))}Xc.BREAK=xt;Xc.SKIP=wg;Xc.REMOVE=Di;async function ga(e,t,i,r){let n=await Ng(e,t,i,r);if(qe.isNode(n)||qe.isPair(n))return bg(e,r,n),ga(e,n,i,r);if(typeof n!="symbol"){if(qe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await ga(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===xt)return xt;o===Di&&(t.items.splice(a,1),a-=1)}}}else if(qe.isPair(t)){r=Object.freeze(r.concat(t));let a=await ga("key",t.key,i,r);if(a===xt)return xt;a===Di&&(t.key=null);let o=await ga("value",t.value,i,r);if(o===xt)return xt;o===Di&&(t.value=null)}}return n}function yg(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 Ng(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(qe.isMap(t))return i.Map?.(e,t,r);if(qe.isSeq(t))return i.Seq?.(e,t,r);if(qe.isPair(t))return i.Pair?.(e,t,r);if(qe.isScalar(t))return i.Scalar?.(e,t,r);if(qe.isAlias(t))return i.Alias?.(e,t,r)}function bg(e,t,i){let r=t[t.length-1];if(qe.isCollection(r))r.items[e]=i;else if(qe.isPair(r))e==="key"?r.key=i:r.value=i;else if(qe.isDocument(r))r.contents=i;else{let n=qe.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}wf.visit=Yc;wf.visitAsync=Xc});var yf=C(Sg=>{"use strict";var kg=Q(),sx=Oo(),cx={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},lx=e=>e.replace(/[!,[\]{}]/g,t=>cx[t]),Ho=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}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,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+lx(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&kg.isNode(t.contents)){let a={};sx.visit(t.contents,(o,s)=>{kg.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};Ho.defaultYaml={explicit:!1,version:"1.2"};Ho.defaultTags={"!!":"tag:yaml.org,2002:"};Sg.Directives=Ho});var Qc=C(Do=>{"use strict";var Eg=Q(),ux=Oo();function dx(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function Pg(e){let t=new Set;return ux.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Rg(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function fx(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Pg(e));let o=Rg(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Eg.isScalar(o.node)||Eg.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:r}}Do.anchorIsValid=dx;Do.anchorNames=Pg;Do.createNodeAnchors=fx;Do.findNewAnchor=Rg});var Nf=C(Cg=>{"use strict";function Fo(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Fo(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Fo(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Fo(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Fo(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}Cg.applyReviver=Fo});var Ar=C(Ag=>{"use strict";var hx=Q();function xg(e,t,i){if(Array.isArray(e))return e.map((r,n)=>xg(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!hx.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}Ag.toJS=xg});var Zc=C(Tg=>{"use strict";var px=Nf(),_g=Q(),mx=Ar(),bf=class{constructor(t){Object.defineProperty(this,_g.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:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!_g.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=mx.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?px.applyReviver(a,{"":s},"",s):s}};Tg.NodeBase=bf});var Mo=C(Ig=>{"use strict";var vx=Qc(),gx=Oo(),wa=Q(),wx=Zc(),yx=Ar(),kf=class extends wx.NodeBase{constructor(t){super(wa.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],gx.visit(t,{Node:(a,o)=>{(wa.isAlias(o)||wa.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(yx.toJS(o,null,i),s=r.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=el(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(vx.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 el(e,t,i){if(wa.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(wa.isCollection(t)){let r=0;for(let n of t.items){let a=el(e,n,i);a>r&&(r=a)}return r}else if(wa.isPair(t)){let r=el(e,t.key,i),n=el(e,t.value,i);return Math.max(r,n)}return 1}Ig.Alias=kf});var De=C(Sf=>{"use strict";var Nx=Q(),bx=Zc(),kx=Ar(),Sx=e=>!e||typeof e!="function"&&typeof e!="object",_r=class extends bx.NodeBase{constructor(t){super(Nx.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:kx.toJS(this.value,t,i)}toString(){return String(this.value)}};_r.BLOCK_FOLDED="BLOCK_FOLDED";_r.BLOCK_LITERAL="BLOCK_LITERAL";_r.PLAIN="PLAIN";_r.QUOTE_DOUBLE="QUOTE_DOUBLE";_r.QUOTE_SINGLE="QUOTE_SINGLE";Sf.Scalar=_r;Sf.isScalarValue=Sx});var Bo=C($g=>{"use strict";var Ex=Mo(),En=Q(),jg=De(),Px="tag:yaml.org,2002:";function Rx(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function Cx(e,t,i){if(En.isDocument(e)&&(e=e.contents),En.isNode(e))return e;if(En.isPair(e)){let d=i.schema[En.MAP].createNode?.(i.schema,null,i);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:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Ex.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Px+t.slice(2));let l=Rx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new jg.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[En.MAP]:Symbol.iterator in Object(e)?o[En.SEQ]:o[En.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new jg.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}$g.createNode=Cx});var il=C(tl=>{"use strict";var xx=Bo(),Fi=Q(),Ax=Zc();function Ef(e,t,i){let r=i;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]=r,r=o}else r=new Map([[a,r]])}return xx.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Og=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Pf=class extends Ax.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>Fi.isNode(r)||Fi.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Og(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(Fi.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ef(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(Fi.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&Fi.isScalar(a)?a.value:a:Fi.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Fi.isPair(i))return!1;let r=i.value;return r==null||t&&Fi.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return Fi.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(Fi.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Ef(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};tl.Collection=Pf;tl.collectionFromPath=Ef;tl.isEmptyPath=Og});var Lo=C(rl=>{"use strict";var _x=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Rf(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Tx=(e,t,i)=>e.endsWith(`
|
|
6
|
+
`)?Rf(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
10
|
-
`&&h!==" "){let
|
|
11
|
-
`&&
|
|
12
|
-
${t}${e.slice(0,k)}`:(i===
|
|
13
|
-
${t}${e.slice(
|
|
14
|
-
`);r=t,n=t+1,a=e[n]}return r}
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function
|
|
8
|
+
`+Rf(i,t):(e.endsWith(" ")?"":" ")+i;rl.indentComment=Rf;rl.lineComment=Tx;rl.stringifyComment=_x});var Dg=C(qo=>{"use strict";var Ix="flow",Cf="block",nl="quoted";function jx(e,t,i="flow",{indentAtStart:r,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 r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,h,m=!1,p=-1,v=-1,g=-1;i===Cf&&(p=Hg(e,p,t.length),p!==-1&&(d=p+c));for(let E;E=e[p+=1];){if(i===nl&&E==="\\"){switch(v=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(E===`
|
|
9
|
+
`)i===Cf&&(p=Hg(e,p,t.length)),d=p+t.length+c,f=void 0;else{if(E===" "&&h&&h!==" "&&h!==`
|
|
10
|
+
`&&h!==" "){let S=e[p+1];S&&S!==" "&&S!==`
|
|
11
|
+
`&&S!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===nl){for(;h===" "||h===" ";)h=E,E=e[p+=1],m=!0;let S=p>g+1?p-2:v-1;if(u[S])return e;l.push(S),u[S]=!0,d=S+c,f=void 0}else m=!0}h=E}if(m&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let E=0;E<l.length;++E){let S=l[E],k=l[E+1]||e.length;S===0?y=`
|
|
12
|
+
${t}${e.slice(0,k)}`:(i===nl&&u[S]&&(y+=`${e[S]}\\`),y+=`
|
|
13
|
+
${t}${e.slice(S+1,k)}`)}return y}function Hg(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}qo.FOLD_BLOCK=Cf;qo.FOLD_FLOW=Ix;qo.FOLD_QUOTED=nl;qo.foldFlowLines=jx});var Wo=C(Fg=>{"use strict";var yi=De(),Tr=Dg(),ol=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),sl=e=>/^(%|---|\.\.\.)/m.test(e);function $x(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Vo(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(sl(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.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+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${i}`)+"'";return t.implicitKey?r:
|
|
18
|
+
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Tr.foldFlowLines(o,a,Tr.FOLD_QUOTED,ol(t,!1))}function xf(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Vo(e,t);let i=t.indent||(sl(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:Tr.foldFlowLines(r,i,Tr.FOLD_FLOW,ol(t,!1))}function ya(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Vo;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=xf:a&&!n?r=Vo:r=i?xf:Vo}return r(e,t)}var Af;try{Af=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Af=/\n+(?!\n|$)/g}function al({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return ya(i,r);let l=r.indent||(r.forceBlockIndent||sl(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===yi.Scalar.BLOCK_FOLDED?!1:t===yi.Scalar.BLOCK_LITERAL?!0:!$x(i,c,l.length);if(!i)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=i.length;f>0;--f){let k=i[f-1];if(k!==`
|
|
26
26
|
`&&k!==" "&&k!==" ")break}let h=i.substring(f),m=h.indexOf(`
|
|
27
27
|
`);m===-1?d="-":i===h||m!==h.length-1?(d="+",a&&a()):d="",h&&(i=i.slice(0,-h.length),h[h.length-1]===`
|
|
28
|
-
`&&(h=h.slice(0,-1)),h=h.replace(
|
|
29
|
-
`)
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,R=
|
|
31
|
-
${l}${
|
|
32
|
-
${l}${y}${i}${h}`}function
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(v=`${v}:`,f&&(v+=
|
|
28
|
+
`&&(h=h.slice(0,-1)),h=h.replace(Af,`$&${l}`));let p=!1,v,g=-1;for(v=0;v<i.length;++v){let k=i[v];if(k===" ")p=!0;else if(k===`
|
|
29
|
+
`)g=v;else break}let y=i.substring(0,g<v?g+1:v);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let S=(p?l?"2":"1":"")+d;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let k=i.replace(/\n+/g,`
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,R=ol(r,!0);o!=="folded"&&t!==yi.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{b=!0});let N=Tr.foldFlowLines(`${y}${k}${h}`,l,Tr.FOLD_BLOCK,R);if(!b)return`>${S}
|
|
31
|
+
${l}${N}`}return i=i.replace(/\n+/g,`$&${l}`),`|${S}
|
|
32
|
+
${l}${y}${i}${h}`}function Ox(e,t,i,r){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 ya(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?ya(a,t):al(e,t,i,r);if(!s&&!u&&n!==yi.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return al(e,t,i,r);if(sl(a)){if(c==="")return t.forceBlockIndent=!0,al(e,t,i,r);if(s&&c===l)return ya(a,t)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return ya(a,t)}return s?d:Tr.foldFlowLines(d,c,Tr.FOLD_FLOW,ol(t,!1))}function Hx(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==yi.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=yi.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case yi.Scalar.BLOCK_FOLDED:case yi.Scalar.BLOCK_LITERAL:return n||a?ya(o.value,t):al(o,t,i,r);case yi.Scalar.QUOTE_DOUBLE:return Vo(o.value,t);case yi.Scalar.QUOTE_SINGLE:return xf(o.value,t);case yi.Scalar.PLAIN:return Ox(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Fg.stringifyString=Hx});var zo=C(_f=>{"use strict";var Dx=Qc(),Ir=Q(),Fx=Lo(),Mx=Wo();function Bx(e,t){let i=Object.assign({blockQuote:!0,commentString:Fx.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),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function Lx(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 i,r;if(Ir.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function qx(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Ir.isScalar(e)||Ir.isCollection(e))&&e.anchor;a&&Dx.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function Vx(e,t,i,r){if(Ir.isPair(e))return e.toString(t,i,r);if(Ir.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=Ir.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Lx(t.doc.schema.tags,a));let o=qx(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Ir.isScalar(a)?Mx.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Ir.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}_f.createStringifyContext=Bx;_f.stringify=Vx});var qg=C(Lg=>{"use strict";var or=Q(),Mg=De(),Bg=zo(),Jo=Lo();function Wx({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=or.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(or.isCollection(e)||!or.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||or.isCollection(e)||(or.isScalar(e)?e.type===Mg.Scalar.BLOCK_FOLDED||e.type===Mg.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let m=!1,p=!1,v=Bg.stringify(e,i,()=>m=!0,()=>p=!0);if(!h&&!i.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(i.inFlow){if(a||t==null)return m&&r&&r(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||t==null&&h)return v=`? ${v}`,f&&!m?v+=Jo.lineComment(v,i.indent,l(f)):p&&n&&n(),v;m&&(f=null),h?(f&&(v+=Jo.lineComment(v,i.indent,l(f))),v=`? ${v}
|
|
38
|
+
${s}:`):(v=`${v}:`,f&&(v+=Jo.lineComment(v,i.indent,l(f))));let g,y,E;or.isNode(t)?(g=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(g=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&or.isScalar(t)&&(i.indentAtStart=v.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&or.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,k=Bg.stringify(t,i,()=>S=!0,()=>p=!0),b=" ";if(f||g||y){if(b=g?`
|
|
39
39
|
`:"",y){let R=l(y);b+=`
|
|
40
|
-
${
|
|
41
|
-
`&&
|
|
40
|
+
${Jo.indentComment(R,i.indent)}`}k===""&&!i.inFlow?b===`
|
|
41
|
+
`&&E&&(b=`
|
|
42
42
|
|
|
43
43
|
`):b+=`
|
|
44
|
-
${i.indent}`}else if(!h&&
|
|
45
|
-
`),
|
|
44
|
+
${i.indent}`}else if(!h&&or.isCollection(t)){let R=k[0],N=k.indexOf(`
|
|
45
|
+
`),w=N!==-1,P=i.inFlow??t.flow??t.items.length===0;if(w||!P){let L=!1;if(w&&(R==="&"||R==="!")){let H=k.indexOf(" ");R==="&"&&H!==-1&&H<N&&k[H+1]==="!"&&(H=k.indexOf(" ",H+1)),(H===-1||N<H)&&(L=!0)}L||(b=`
|
|
46
46
|
${i.indent}`)}}else(k===""||k[0]===`
|
|
47
|
-
`)&&(b="");return v+=b+k,i.inFlow?
|
|
47
|
+
`)&&(b="");return v+=b+k,i.inFlow?S&&r&&r():E&&!S?v+=Jo.lineComment(v,i.indent,l(E)):p&&n&&n(),v}Lg.stringifyPair=Wx});var If=C(Tf=>{"use strict";var Vg=zc("process");function zx(e,...t){e==="debug"&&console.log(...t)}function Jx(e,t){(e==="debug"||e==="warn")&&(typeof Vg.emitWarning=="function"?Vg.emitWarning(t):console.warn(t))}Tf.debug=zx;Tf.warn=Jx});var fl=C(dl=>{"use strict";var ul=Q(),Wg=De(),cl="<<",ll={identify:e=>e===cl||typeof e=="symbol"&&e.description===cl,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Wg.Scalar(Symbol(cl)),{addToJSMap:zg}),stringify:()=>cl},Gx=(e,t)=>(ll.identify(t)||ul.isScalar(t)&&(!t.type||t.type===Wg.Scalar.PLAIN)&&ll.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===ll.tag&&i.default);function zg(e,t,i){let r=Jg(e,i);if(ul.isSeq(r))for(let n of r.items)jf(e,t,n);else if(Array.isArray(r))for(let n of r)jf(e,t,n);else jf(e,t,r)}function jf(e,t,i){let r=Jg(e,i);if(!ul.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.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 Jg(e,t){return e&&ul.isAlias(t)?t.resolve(e.doc,e):t}dl.addMergeToJSMap=zg;dl.isMergeKey=Gx;dl.merge=ll});var Of=C(Kg=>{"use strict";var Ux=If(),Gg=fl(),Kx=zo(),Ug=Q(),$f=Ar();function Yx(e,t,{key:i,value:r}){if(Ug.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Gg.isMergeKey(e,i))Gg.addMergeToJSMap(e,t,r);else{let n=$f.toJS(i,"",e);if(t instanceof Map)t.set(n,$f.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=Xx(i,n,e),o=$f.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Xx(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Ug.isNode(e)&&i?.doc){let r=Kx.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),Ux.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Kg.addPairToJSMap=Yx});var jr=C(Hf=>{"use strict";var Yg=Bo(),Qx=qg(),Zx=Of(),hl=Q();function eA(e,t,i){let r=Yg.createNode(e,void 0,i),n=Yg.createNode(t,void 0,i);return new pl(r,n)}var pl=class e{constructor(t,i=null){Object.defineProperty(this,hl.NODE_TYPE,{value:hl.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return hl.isNode(i)&&(i=i.clone(t)),hl.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return Zx.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?Qx.stringifyPair(this,t,i,r):JSON.stringify(this)}};Hf.Pair=pl;Hf.createPair=eA});var Df=C(Qg=>{"use strict";var Pn=Q(),Xg=zo(),ml=Lo();function tA(e,t,i){return(t.inFlow??e.flow?rA:iA)(e,t,i)}function iA({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let m=0;m<t.length;++m){let p=t[m],v=null;if(Pn.isNode(p))!d&&p.spaceBefore&&f.push(""),vl(i,f,p.commentBefore,d),p.comment&&(v=p.comment);else if(Pn.isPair(p)){let y=Pn.isNode(p.key)?p.key:null;y&&(!d&&y.spaceBefore&&f.push(""),vl(i,f,y.commentBefore,d))}d=!1;let g=Xg.stringify(p,u,()=>v=null,()=>d=!0);v&&(g+=ml.lineComment(g,a,l(v))),d&&v&&(d=!1),f.push(r+g)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let m=1;m<f.length;++m){let p=f[m];h+=p?`
|
|
48
48
|
${c}${p}`:`
|
|
49
49
|
`}}return e?(h+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),m<e.length-1?
|
|
50
|
+
`+ml.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function rA({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let p=e[m],v=null;if(Pn.isNode(p))p.spaceBefore&&d.push(""),vl(t,d,p.commentBefore,!1),p.comment&&(v=p.comment);else if(Pn.isPair(p)){let y=Pn.isNode(p.key)?p.key:null;y&&(y.spaceBefore&&d.push(""),vl(t,d,y.commentBefore,!1),y.comment&&(l=!0));let E=Pn.isNode(p.value)?p.value:null;E?(E.comment&&(v=E.comment),E.commentBefore&&(l=!0)):p.value==null&&y?.comment&&(v=y.comment)}v&&(l=!0);let g=Xg.stringify(p,c,()=>v=null);l||(l=d.length>u||g.includes(`
|
|
51
|
+
`)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,E)=>y+E.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=ml.lineComment(g,r,s(v))),d.push(g),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let m=d.reduce((p,v)=>p+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let p of d)m+=p?`
|
|
52
52
|
${a}${n}${p}`:`
|
|
53
53
|
`;return`${m}
|
|
54
|
-
${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function vl({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=ml.indentComment(t(r),e);i.push(a.trimStart())}}Qg.stringifyCollection=tA});var Or=C(Mf=>{"use strict";var nA=Df(),aA=Of(),oA=il(),$r=Q(),gl=jr(),sA=De();function Go(e,t){let i=$r.isScalar(t)?t.value:t;for(let r of e)if($r.isPair(r)&&(r.key===t||r.key===i||$r.isScalar(r.key)&&r.key.value===i))return r}var Ff=class extends oA.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super($r.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(gl.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;$r.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new gl.Pair(t,t?.value):r=new gl.Pair(t.key,t.value);let n=Go(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);$r.isScalar(n.value)&&sA.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=Go(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Go(this.items,t)?.value;return(!i&&$r.isScalar(n)?n.value:n)??void 0}has(t){return!!Go(this.items,t)}set(t,i){this.add(new gl.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)aA.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!$r.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})),nA.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Mf.YAMLMap=Ff;Mf.findPair=Go});var Na=C(ew=>{"use strict";var cA=Q(),Zg=Or(),lA={collection:"map",default:!0,nodeClass:Zg.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return cA.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Zg.YAMLMap.from(e,t,i)};ew.map=lA});var Hr=C(tw=>{"use strict";var uA=Bo(),dA=Df(),fA=il(),yl=Q(),hA=De(),pA=Ar(),Bf=class extends fA.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(yl.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=wl(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=wl(t);if(typeof r!="number")return;let n=this.items[r];return!i&&yl.isScalar(n)?n.value:n}has(t){let i=wl(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=wl(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];yl.isScalar(n)&&hA.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(pA.toJS(a,String(n++),i));return r}toString(t,i,r){return t?dA.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(uA.createNode(s,void 0,r))}}return a}};function wl(e){let t=yl.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}tw.YAMLSeq=Bf});var ba=C(rw=>{"use strict";var mA=Q(),iw=Hr(),vA={collection:"seq",default:!0,nodeClass:iw.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return mA.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>iw.YAMLSeq.from(e,t,i)};rw.seq=vA});var Uo=C(nw=>{"use strict";var gA=Wo(),wA={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),gA.stringifyString(e,t,i,r)}};nw.string=wA});var Nl=C(sw=>{"use strict";var aw=De(),ow={identify:e=>e==null,createNode:()=>new aw.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new aw.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&ow.test.test(e)?e:t.options.nullStr};sw.nullTag=ow});var Lf=C(lw=>{"use strict";var yA=De(),cw={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new yA.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&cw.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};lw.boolTag=cw});var ka=C(uw=>{"use strict";function NA({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="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}uw.stringifyNumber=NA});var Vf=C(bl=>{"use strict";var bA=De(),qf=ka(),kA={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:qf.stringifyNumber},SA={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():qf.stringifyNumber(e)}},EA={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 bA.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:qf.stringifyNumber};bl.float=EA;bl.floatExp=SA;bl.floatNaN=kA});var zf=C(Sl=>{"use strict";var dw=ka(),kl=e=>typeof e=="bigint"||Number.isInteger(e),Wf=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function fw(e,t,i){let{value:r}=e;return kl(r)&&r>=0?i+r.toString(t):dw.stringifyNumber(e)}var PA={identify:e=>kl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Wf(e,2,8,i),stringify:e=>fw(e,8,"0o")},RA={identify:kl,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Wf(e,0,10,i),stringify:dw.stringifyNumber},CA={identify:e=>kl(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Wf(e,2,16,i),stringify:e=>fw(e,16,"0x")};Sl.int=RA;Sl.intHex=CA;Sl.intOct=PA});var pw=C(hw=>{"use strict";var xA=Na(),AA=Nl(),_A=ba(),TA=Uo(),IA=Lf(),Jf=Vf(),Gf=zf(),jA=[xA.map,_A.seq,TA.string,AA.nullTag,IA.boolTag,Gf.intOct,Gf.int,Gf.intHex,Jf.floatNaN,Jf.floatExp,Jf.float];hw.schema=jA});var gw=C(vw=>{"use strict";var $A=De(),OA=Na(),HA=ba();function mw(e){return typeof e=="bigint"||Number.isInteger(e)}var El=({value:e})=>JSON.stringify(e),DA=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:El},{identify:e=>e==null,createNode:()=>new $A.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:El},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:El},{identify:mw,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>mw(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:El}],FA={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},MA=[OA.map,HA.seq].concat(DA,FA);vw.schema=MA});var Kf=C(ww=>{"use strict";var Ko=zc("buffer"),Uf=De(),BA=Wo(),LA={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ko.Buffer=="function")return Ko.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Ko.Buffer=="function")s=o instanceof Ko.Buffer?o.toString("base64"):Ko.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=Uf.Scalar.BLOCK_LITERAL),t!==Uf.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===Uf.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return BA.stringifyString({comment:e,type:t,value:s},r,n,a)}};ww.binary=LA});var Cl=C(Rl=>{"use strict";var Pl=Q(),Yf=jr(),qA=De(),VA=Hr();function yw(e,t){if(Pl.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Pl.isPair(r)){if(Pl.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Yf.Pair(new qA.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
-
${a.comment}`:r.comment}r=n}e.items[i]=pl.isPair(r)?r:new $f.Pair(r)}}else t("Expected a sequence for this tag");return e}function rw(e,t,i){let{replacer:r}=i,n=new NA.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 r=="function"&&(o=r.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($f.createPair(s,c,i))}return n}var bA={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:iw,createNode:rw};ml.createPairs=rw;ml.pairs=bA;ml.resolvePairs=iw});var Df=x(Hf=>{"use strict";var nw=Q(),Of=Pr(),qo=Tr(),kA=Ir(),aw=vl(),kn=class e extends kA.YAMLSeq{constructor(){super(),this.add=qo.YAMLMap.prototype.add.bind(this),this.delete=qo.YAMLMap.prototype.delete.bind(this),this.get=qo.YAMLMap.prototype.get.bind(this),this.has=qo.YAMLMap.prototype.has.bind(this),this.set=qo.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(nw.isPair(n)?(a=Of.toJS(n.key,"",i),o=Of.toJS(n.value,a,i)):a=Of.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=aw.createPairs(t,i,r),a=new this;return a.items=n.items,a}};kn.tag="tag:yaml.org,2002:omap";var SA={collection:"seq",identify:e=>e instanceof Map,nodeClass:kn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=aw.resolvePairs(e,t),r=[];for(let{key:n}of i.items)nw.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new kn,i)},createNode:(e,t,i)=>kn.from(e,t,i)};Hf.YAMLOMap=kn;Hf.omap=SA});var uw=x(Ff=>{"use strict";var ow=De();function sw({value:e,source:t},i){return t&&(e?cw:lw).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var cw={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 ow.Scalar(!0),stringify:sw},lw={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 ow.Scalar(!1),stringify:sw};Ff.falseTag=lw;Ff.trueTag=cw});var dw=x(gl=>{"use strict";var EA=De(),Mf=ma(),PA={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:Mf.stringifyNumber},RA={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():Mf.stringifyNumber(e)}},xA={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 EA.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Mf.stringifyNumber};gl.float=xA;gl.floatExp=RA;gl.floatNaN=PA});var hw=x(Wo=>{"use strict";var fw=ma(),Vo=e=>typeof e=="bigint"||Number.isInteger(e);function wl(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){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,i);return n==="-"?-1*a:a}function Bf(e,t,i){let{value:r}=e;if(Vo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return fw.stringifyNumber(e)}var CA={identify:Vo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>wl(e,2,2,i),stringify:e=>Bf(e,2,"0b")},AA={identify:Vo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>wl(e,1,8,i),stringify:e=>Bf(e,8,"0")},_A={identify:Vo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>wl(e,0,10,i),stringify:fw.stringifyNumber},TA={identify:Vo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>wl(e,2,16,i),stringify:e=>Bf(e,16,"0x")};Wo.int=_A;Wo.intBin=CA;Wo.intHex=TA;Wo.intOct=AA});var qf=x(Lf=>{"use strict";var bl=Q(),yl=Ar(),Nl=Tr(),Sn=class e extends Nl.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;bl.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new yl.Pair(t.key,null):i=new yl.Pair(t,null),Nl.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Nl.findPair(this.items,t);return!i&&bl.isPair(r)?bl.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Nl.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new yl.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(yl.createPair(o,null,r));return a}};Sn.tag="tag:yaml.org,2002:set";var IA={collection:"map",identify:e=>e instanceof Set,nodeClass:Sn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Sn.from(e,t,i),resolve(e,t){if(bl.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Sn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Lf.YAMLSet=Sn;Lf.set=IA});var Wf=x(kl=>{"use strict";var jA=ma();function Vf(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function pw(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return jA.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(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))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var $A={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:i})=>Vf(e,i),stringify:pw},OA={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=>Vf(e,!1),stringify:pw},mw={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(mw.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Vf(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$/,"")??""};kl.floatTime=OA;kl.intTime=$A;kl.timestamp=mw});var ww=x(gw=>{"use strict";var HA=ha(),DA=ll(),FA=pa(),MA=Bo(),BA=jf(),vw=uw(),zf=dw(),Sl=hw(),LA=tl(),qA=Df(),VA=vl(),WA=qf(),Jf=Wf(),zA=[HA.map,FA.seq,MA.string,DA.nullTag,vw.trueTag,vw.falseTag,Sl.intBin,Sl.intOct,Sl.int,Sl.intHex,zf.floatNaN,zf.floatExp,zf.float,BA.binary,LA.merge,qA.omap,VA.pairs,WA.set,Jf.intTime,Jf.floatTime,Jf.timestamp];gw.schema=zA});var Cw=x(Kf=>{"use strict";var kw=ha(),JA=ll(),Sw=pa(),GA=Bo(),UA=Pf(),Gf=xf(),Uf=Af(),KA=Xg(),YA=ew(),Ew=jf(),zo=tl(),Pw=Df(),Rw=vl(),yw=ww(),xw=qf(),El=Wf(),Nw=new Map([["core",KA.schema],["failsafe",[kw.map,Sw.seq,GA.string]],["json",YA.schema],["yaml11",yw.schema],["yaml-1.1",yw.schema]]),bw={binary:Ew.binary,bool:UA.boolTag,float:Gf.float,floatExp:Gf.floatExp,floatNaN:Gf.floatNaN,floatTime:El.floatTime,int:Uf.int,intHex:Uf.intHex,intOct:Uf.intOct,intTime:El.intTime,map:kw.map,merge:zo.merge,null:JA.nullTag,omap:Pw.omap,pairs:Rw.pairs,seq:Sw.seq,set:xw.set,timestamp:El.timestamp},XA={"tag:yaml.org,2002:binary":Ew.binary,"tag:yaml.org,2002:merge":zo.merge,"tag:yaml.org,2002:omap":Pw.omap,"tag:yaml.org,2002:pairs":Rw.pairs,"tag:yaml.org,2002:set":xw.set,"tag:yaml.org,2002:timestamp":El.timestamp};function QA(e,t,i){let r=Nw.get(t);if(r&&!e)return i&&!r.includes(zo.merge)?r.concat(zo.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Nw.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 i&&(n=n.concat(zo.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?bw[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(bw).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},[])}Kf.coreKnownTags=XA;Kf.getTags=QA});var Qf=x(Aw=>{"use strict";var Yf=Q(),ZA=ha(),e_=pa(),t_=Bo(),Pl=Cw(),i_=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Xf=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Pl.getTags(t,"compat"):t?Pl.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Pl.coreKnownTags:{},this.tags=Pl.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Yf.MAP,{value:ZA.map}),Object.defineProperty(this,Yf.SCALAR,{value:t_.string}),Object.defineProperty(this,Yf.SEQ,{value:e_.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?i_:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Aw.Schema=Xf});var Tw=x(_w=>{"use strict";var r_=Q(),Zf=Do(),Jo=jo();function n_(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=Zf.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Jo.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(r_.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Jo.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Zf.stringify(e.contents,n,()=>s=null,c);s&&(l+=Jo.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Zf.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
57
|
+
${a.comment}`:r.comment}r=n}e.items[i]=Pl.isPair(r)?r:new Yf.Pair(r)}}else t("Expected a sequence for this tag");return e}function Nw(e,t,i){let{replacer:r}=i,n=new VA.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 r=="function"&&(o=r.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(Yf.createPair(s,c,i))}return n}var WA={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:yw,createNode:Nw};Rl.createPairs=Nw;Rl.pairs=WA;Rl.resolvePairs=yw});var Zf=C(Qf=>{"use strict";var bw=Q(),Xf=Ar(),Yo=Or(),zA=Hr(),kw=Cl(),Rn=class e extends zA.YAMLSeq{constructor(){super(),this.add=Yo.YAMLMap.prototype.add.bind(this),this.delete=Yo.YAMLMap.prototype.delete.bind(this),this.get=Yo.YAMLMap.prototype.get.bind(this),this.has=Yo.YAMLMap.prototype.has.bind(this),this.set=Yo.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(bw.isPair(n)?(a=Xf.toJS(n.key,"",i),o=Xf.toJS(n.value,a,i)):a=Xf.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=kw.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Rn.tag="tag:yaml.org,2002:omap";var JA={collection:"seq",identify:e=>e instanceof Map,nodeClass:Rn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=kw.resolvePairs(e,t),r=[];for(let{key:n}of i.items)bw.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Rn,i)},createNode:(e,t,i)=>Rn.from(e,t,i)};Qf.YAMLOMap=Rn;Qf.omap=JA});var Cw=C(eh=>{"use strict";var Sw=De();function Ew({value:e,source:t},i){return t&&(e?Pw:Rw).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Pw={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 Sw.Scalar(!0),stringify:Ew},Rw={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 Sw.Scalar(!1),stringify:Ew};eh.falseTag=Rw;eh.trueTag=Pw});var xw=C(xl=>{"use strict";var GA=De(),th=ka(),UA={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:th.stringifyNumber},KA={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():th.stringifyNumber(e)}},YA={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 GA.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:th.stringifyNumber};xl.float=YA;xl.floatExp=KA;xl.floatNaN=UA});var _w=C(Qo=>{"use strict";var Aw=ka(),Xo=e=>typeof e=="bigint"||Number.isInteger(e);function Al(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){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,i);return n==="-"?-1*a:a}function ih(e,t,i){let{value:r}=e;if(Xo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Aw.stringifyNumber(e)}var XA={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Al(e,2,2,i),stringify:e=>ih(e,2,"0b")},QA={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Al(e,1,8,i),stringify:e=>ih(e,8,"0")},ZA={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Al(e,0,10,i),stringify:Aw.stringifyNumber},e_={identify:Xo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Al(e,2,16,i),stringify:e=>ih(e,16,"0x")};Qo.int=ZA;Qo.intBin=XA;Qo.intHex=e_;Qo.intOct=QA});var nh=C(rh=>{"use strict";var Il=Q(),_l=jr(),Tl=Or(),Cn=class e extends Tl.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Il.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new _l.Pair(t.key,null):i=new _l.Pair(t,null),Tl.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Tl.findPair(this.items,t);return!i&&Il.isPair(r)?Il.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Tl.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new _l.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(_l.createPair(o,null,r));return a}};Cn.tag="tag:yaml.org,2002:set";var t_={collection:"map",identify:e=>e instanceof Set,nodeClass:Cn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Cn.from(e,t,i),resolve(e,t){if(Il.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Cn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};rh.YAMLSet=Cn;rh.set=t_});var oh=C(jl=>{"use strict";var i_=ka();function ah(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Tw(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return i_.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(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))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var r_={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:i})=>ah(e,i),stringify:Tw},n_={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=>ah(e,!1),stringify:Tw},Iw={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(Iw.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=ah(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$/,"")??""};jl.floatTime=n_;jl.intTime=r_;jl.timestamp=Iw});var Ow=C($w=>{"use strict";var a_=Na(),o_=Nl(),s_=ba(),c_=Uo(),l_=Kf(),jw=Cw(),sh=xw(),$l=_w(),u_=fl(),d_=Zf(),f_=Cl(),h_=nh(),ch=oh(),p_=[a_.map,s_.seq,c_.string,o_.nullTag,jw.trueTag,jw.falseTag,$l.intBin,$l.intOct,$l.int,$l.intHex,sh.floatNaN,sh.floatExp,sh.float,l_.binary,u_.merge,d_.omap,f_.pairs,h_.set,ch.intTime,ch.floatTime,ch.timestamp];$w.schema=p_});var zw=C(dh=>{"use strict";var Mw=Na(),m_=Nl(),Bw=ba(),v_=Uo(),g_=Lf(),lh=Vf(),uh=zf(),w_=pw(),y_=gw(),Lw=Kf(),Zo=fl(),qw=Zf(),Vw=Cl(),Hw=Ow(),Ww=nh(),Ol=oh(),Dw=new Map([["core",w_.schema],["failsafe",[Mw.map,Bw.seq,v_.string]],["json",y_.schema],["yaml11",Hw.schema],["yaml-1.1",Hw.schema]]),Fw={binary:Lw.binary,bool:g_.boolTag,float:lh.float,floatExp:lh.floatExp,floatNaN:lh.floatNaN,floatTime:Ol.floatTime,int:uh.int,intHex:uh.intHex,intOct:uh.intOct,intTime:Ol.intTime,map:Mw.map,merge:Zo.merge,null:m_.nullTag,omap:qw.omap,pairs:Vw.pairs,seq:Bw.seq,set:Ww.set,timestamp:Ol.timestamp},N_={"tag:yaml.org,2002:binary":Lw.binary,"tag:yaml.org,2002:merge":Zo.merge,"tag:yaml.org,2002:omap":qw.omap,"tag:yaml.org,2002:pairs":Vw.pairs,"tag:yaml.org,2002:set":Ww.set,"tag:yaml.org,2002:timestamp":Ol.timestamp};function b_(e,t,i){let r=Dw.get(t);if(r&&!e)return i&&!r.includes(Zo.merge)?r.concat(Zo.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Dw.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 i&&(n=n.concat(Zo.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Fw[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Fw).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},[])}dh.coreKnownTags=N_;dh.getTags=b_});var ph=C(Jw=>{"use strict";var fh=Q(),k_=Na(),S_=ba(),E_=Uo(),Hl=zw(),P_=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,hh=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Hl.getTags(t,"compat"):t?Hl.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Hl.coreKnownTags:{},this.tags=Hl.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,fh.MAP,{value:k_.map}),Object.defineProperty(this,fh.SCALAR,{value:E_.string}),Object.defineProperty(this,fh.SEQ,{value:S_.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?P_:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Jw.Schema=hh});var Uw=C(Gw=>{"use strict";var R_=Q(),mh=zo(),es=Lo();function C_(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=mh.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(es.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(R_.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(es.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=mh.stringify(e.contents,n,()=>s=null,c);s&&(l+=es.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(mh.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(es.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(es.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}Gw.stringifyDocument=C_});var ts=C(Kw=>{"use strict";var x_=Mo(),Sa=il(),ti=Q(),A_=jr(),__=Ar(),T_=ph(),I_=Uw(),vh=Qc(),j_=Nf(),$_=Bo(),gh=yf(),wh=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ti.NODE_TYPE,{value:ti.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new gh.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[ti.NODE_TYPE]:{value:ti.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=ti.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ea(this.contents)&&this.contents.add(t)}addIn(t,i){Ea(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=vh.anchorNames(this);t.anchor=!i||r.has(i)?vh.findNewAnchor(i||"a",r):i}return new x_.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let v=y=>typeof y=="number"||y instanceof String||y instanceof Number,g=i.filter(v).map(String);g.length>0&&(i=i.concat(g)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=vh.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=$_.createNode(t,u,m);return s&&ti.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new A_.Pair(n,a)}delete(t){return Ea(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Sa.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ea(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return ti.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Sa.isEmptyPath(t)?!i&&ti.isScalar(this.contents)?this.contents.value:this.contents:ti.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return ti.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Sa.isEmptyPath(t)?this.contents!==void 0:ti.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Sa.collectionFromPath(this.schema,[t],i):Ea(this.contents)&&this.contents.set(t,i)}setIn(t,i){Sa.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Sa.collectionFromPath(this.schema,Array.from(t),i):Ea(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new gh.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new gh.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=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(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new T_.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=__.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?j_.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}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 i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return I_.stringifyDocument(this,t)}};function Ea(e){if(ti.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Kw.Document=wh});var ns=C(rs=>{"use strict";var is=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},yh=class extends is{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Nh=class extends is{constructor(t,i,r){super("YAMLWarning",t,i,r)}},O_=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).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)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.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 i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(
|
|
67
|
-
`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||
|
|
68
|
-
`+
|
|
69
|
-
`+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&
|
|
70
|
-
`+R:
|
|
71
|
-
`+
|
|
72
|
-
`+v.comment:l.comment=v.comment),l.range=[r.offset,p,v.offset]}else l.range=[r.offset,p,p];return l}
|
|
73
|
-
`.repeat(Math.max(1,o.length-1)):"",v=r+n.length;return t.source&&(v+=t.source.length),{value:p,type:a,comment:n.comment,range:[r,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let p=0;p<s;++p){let[v,
|
|
74
|
-
`;for(let p=u;p<s;++p){let[v,
|
|
75
|
-
`):v.length>c||
|
|
65
|
+
`}};rs.YAMLError=is;rs.YAMLParseError=yh;rs.YAMLWarning=Nh;rs.prettifyError=O_});var as=C(Yw=>{"use strict";function H_(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,m=!1,p=null,v=null,g=null,y=null,E=null,S=null,k=null;for(let N of e)switch(m&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),p&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),N.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(p=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=N.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=N.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=N.source,l=!0,h=!0,(v||g)&&(y=N),u=!0;break;case"anchor":v&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=N,k??(k=N.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),g=N,k??(k=N.offset),l=!1,u=!1,m=!0;break}case i:(v||g)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),S&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),S=N,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){E&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let b=e[e.length-1],R=b?b.offset+b.source.length:n;return m&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:S,spaceBefore:c,comment:d,hasNewline:h,anchor:v,tag:g,newlineAfterProp:y,end:R,start:k??R}}Yw.resolveProps=H_});var Dl=C(Xw=>{"use strict";function bh(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 i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(bh(t.key)||bh(t.value))return!0}return!1;default:return!0}}Xw.containsNewline=bh});var kh=C(Qw=>{"use strict";var D_=Dl();function F_(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&D_.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Qw.flowIndentCheck=F_});var Sh=C(ey=>{"use strict";var Zw=Q();function M_(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Zw.isScalar(a)&&Zw.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}ey.mapIncludes=M_});var oy=C(ay=>{"use strict";var ty=jr(),B_=Or(),iy=as(),L_=Dl(),ry=kh(),q_=Sh(),ny="All mapping items must start at the same column";function V_({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??B_.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:h,value:m}=u,p=iy.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),v=!p.found;if(v){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",ny)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||L_.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==r.indent&&n(c,"BAD_INDENT",ny);i.atKey=!0;let g=p.end,y=f?e(i,f,p,n):t(i,g,d,null,p,n);i.schema.compat&&ry.flowIndentCheck(r.indent,f,n),i.atKey=!1,q_.mapIncludes(i,s.items,y)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let E=iy.resolveProps(h??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=E.end,E.found){v&&(m?.type==="block-map"&&!E.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&p.start<E.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=m?e(i,m,E,n):t(i,c,h,null,E,n);i.schema.compat&&ry.flowIndentCheck(r.indent,m,n),c=S.range[2];let k=new ty.Pair(y,S);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{v&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),E.comment&&(y.comment?y.comment+=`
|
|
68
|
+
`+E.comment:y.comment=E.comment);let S=new ty.Pair(y);i.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}ay.resolveBlockMap=V_});var cy=C(sy=>{"use strict";var W_=Hr(),z_=as(),J_=kh();function G_({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??W_.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=z_.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&J_.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}sy.resolveBlockSeq=G_});var Pa=C(ly=>{"use strict";function U_(e,t,i,r){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":{i&&!a&&r(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:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}ly.resolveEnd=U_});var hy=C(fy=>{"use strict";var K_=Q(),Y_=jr(),uy=Or(),X_=Hr(),Q_=Pa(),dy=as(),Z_=Dl(),eT=Sh(),Eh="Block collections are not allowed within flow collections",Ph=e=>e&&(e.type==="block-map"||e.type==="block-seq");function tT({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?uy.YAMLMap:X_.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let v=0;v<r.items.length;++v){let g=r.items[v],{start:y,key:E,sep:S,value:k}=g,b=dy.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:E??S?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!S&&!k){v===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<r.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&&i.options.strict&&Z_.containsNewline(E)&&n(E,"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 R="";e:for(let N of y)switch(N.type){case"comma":case"space":break;case"comment":R=N.source.substring(1);break e;default:break e}if(R){let N=l.items[l.items.length-1];K_.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
|
|
70
|
+
`+R:N.comment=R,b.comment=b.comment.substring(R.length+1)}}if(!o&&!S&&!b.found){let R=k?e(i,k,b,n):t(i,b.end,S,null,b,n);l.items.push(R),d=R.range[2],Ph(k)&&n(R.range,"BLOCK_IN_FLOW",Eh)}else{i.atKey=!0;let R=b.end,N=E?e(i,E,b,n):t(i,R,y,null,b,n);Ph(E)&&n(N.range,"BLOCK_IN_FLOW",Eh),i.atKey=!1;let w=dy.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:k,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!b.found&&i.options.strict){if(S)for(let H of S){if(H===w.found)break;if(H.type==="newline"){n(H,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<w.found.offset-1024&&n(w.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,w,n):w.found?t(i,w.end,S,null,w,n):null;P?Ph(k)&&n(P.range,"BLOCK_IN_FLOW",Eh):w.comment&&(N.comment?N.comment+=`
|
|
71
|
+
`+w.comment:N.comment=w.comment);let L=new Y_.Pair(N,P);if(i.options.keepSourceTokens&&(L.srcToken=g),o){let H=l;eT.mapIncludes(i,H.items,N)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),H.items.push(L)}else{let H=new uy.YAMLMap(i.schema);H.flow=!0,H.items.push(L);let nt=(P??N).range;H.range=[N.range[0],nt[1],nt[2]],l.items.push(H)}d=P?P.range[2]:w.end}}let f=o?"}":"]",[h,...m]=r.end,p=d;if(h?.source===f)p=h.offset+h.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${f}`:`${v} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",g),h&&h.source.length!==1&&m.unshift(h)}if(m.length>0){let v=Q_.resolveEnd(m,p,i.options.strict,n);v.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+v.comment:l.comment=v.comment),l.range=[r.offset,p,v.offset]}else l.range=[r.offset,p,p];return l}fy.resolveFlowCollection=tT});var my=C(py=>{"use strict";var iT=Q(),rT=De(),nT=Or(),aT=Hr(),oT=oy(),sT=cy(),cT=hy();function Rh(e,t,i,r,n,a){let o=i.type==="block-map"?oT.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?sT.resolveBlockSeq(e,t,i,r,a):cT.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function lT(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!h||h.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===nT.YAMLMap.tagName&&s==="map"||o===aT.YAMLSeq.tagName&&s==="seq")return Rh(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Rh(e,t,i,n,o)}let l=Rh(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=iT.isNode(u)?u:new rT.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}py.composeCollection=lT});var xh=C(vy=>{"use strict";var Ch=De();function uT(e,t,i){let r=t.offset,n=dT(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Ch.Scalar.BLOCK_FOLDED:Ch.Scalar.BLOCK_LITERAL,o=t.source?fT(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let v=o[p][1];if(v===""||v==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
|
|
73
|
+
`.repeat(Math.max(1,o.length-1)):"",v=r+n.length;return t.source&&(v+=t.source.length),{value:p,type:a,comment:n.comment,range:[r,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let p=0;p<s;++p){let[v,g]=o[p];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&i(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=p,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let d="",f="",h=!1;for(let p=0;p<u;++p)d+=o[p][0].slice(c)+`
|
|
74
|
+
`;for(let p=u;p<s;++p){let[v,g]=o[p];l+=v.length+g.length+1;let y=g[g.length-1]==="\r";if(y&&(g=g.slice(0,-1)),g&&v.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-g.length-(y?2:1),"BAD_INDENT",S),v=""}a===Ch.Scalar.BLOCK_LITERAL?(d+=f+v.slice(c)+g,f=`
|
|
75
|
+
`):v.length>c||g[0]===" "?(f===" "?f=`
|
|
76
76
|
`:!h&&f===`
|
|
77
77
|
`&&(f=`
|
|
78
78
|
|
|
79
|
-
`),d+=f+v.slice(c)+
|
|
80
|
-
`,h=!0):
|
|
79
|
+
`),d+=f+v.slice(c)+g,f=`
|
|
80
|
+
`,h=!0):g===""?f===`
|
|
81
81
|
`?d+=`
|
|
82
82
|
`:f=`
|
|
83
|
-
`:(d+=f+
|
|
83
|
+
`:(d+=f+g,f=" ",h=!1)}switch(n.chomp){case"-":break;case"+":for(let p=s;p<o.length;++p)d+=`
|
|
84
84
|
`+o[p][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let m=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,m,m]}}function
|
|
87
|
+
`}let m=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,m,m]}}function dT({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let m=Number(h);!o&&m?o=m:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(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":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let m=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",m);let p=h.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function fT(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}vy.resolveBlockScalar=uT});var _h=C(wy=>{"use strict";var Ah=De(),hT=Pa();function pT(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,m)=>i(r+f,h,m);switch(n){case"scalar":s=Ah.Scalar.PLAIN,c=mT(a,l);break;case"single-quoted-scalar":s=Ah.Scalar.QUOTE_SINGLE,c=vT(a,l);break;case"double-quoted-scalar":s=Ah.Scalar.QUOTE_DOUBLE,c=gT(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=hT.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function mT(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),gy(e)}function vT(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),gy(e.slice(1,-1)).replace(/''/g,"'")}function gy(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function
|
|
91
|
+
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function gT(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=wT(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=yT[a];if(o)i+=o;else if(a===`
|
|
94
94
|
`)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
|
|
95
|
-
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=
|
|
95
|
+
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=NT(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&e[r+2]===`
|
|
97
|
-
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function
|
|
97
|
+
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function wT(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
98
98
|
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
|
-
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var yT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function NT(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}wy.resolveFlowScalar=pT});var by=C(Ny=>{"use strict";var xn=Q(),yy=De(),bT=xh(),kT=_h();function ST(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?bT.resolveBlockScalar(e,t,r):kT.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[xn.SCALAR]:c?l=ET(e.schema,n,c,i,r):t.type==="scalar"?l=PT(e,n,t,r):l=e.schema[xn.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=xn.isScalar(d)?d:new yy.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new yy.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 ET(e,t,i,r,n){if(i==="!")return e[xn.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)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[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[xn.SCALAR])}function PT({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[xn.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[xn.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}Ny.composeScalar=ST});var Sy=C(ky=>{"use strict";function RT(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}ky.emptyScalarPosition=RT});var Ry=C(Ih=>{"use strict";var CT=Mo(),xT=Q(),AT=my(),Ey=by(),_T=Pa(),TT=Sy(),IT={composeNode:Py,composeEmptyNode:Th};function Py(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=jT(e,t,r),(s||c)&&r(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=Ey.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=AT.composeCollection(IT,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Th(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!xT.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(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 Th(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:TT.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Ey.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 jT({options:e},{offset:t,source:i,end:r},n){let a=new CT.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=_T.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ih.composeEmptyNode=Th;Ih.composeNode=Py});var Ay=C(xy=>{"use strict";var $T=ts(),Cy=Ry(),OT=Pa(),HT=as();function DT(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new $T.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=HT.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,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?Cy.composeNode(l,n,u,o):Cy.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=OT.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}xy.composeDoc=DT});var $h=C(Iy=>{"use strict";var FT=zc("process"),MT=yf(),BT=ts(),os=ns(),_y=Q(),LT=Ay(),qT=Pa();function ss(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:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function Ty(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var
|
|
106
|
-
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var jh=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ss(i);a?this.warnings.push(new os.YAMLWarning(o,r,n)):this.errors.push(new os.YAMLParseError(o,r,n))},this.directives=new MT.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Ty(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(_y.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];_y.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
107
|
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
|
-
${o}`:r}}if(i){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
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:r}}if(i){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:Ty(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(FT.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=ss(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=LT.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new os.YAMLParseError(ss(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new os.YAMLParseError(ss(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=qT.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new os.YAMLParseError(ss(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new BT.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};Iy.Composer=jh});var Oy=C(Fl=>{"use strict";var VT=xh(),WT=_h(),zT=ns(),jy=Wo();function JT(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new zT.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return WT.resolveFlowScalar(e,t,r);case"block-scalar":return VT.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function GT(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=jy.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return $y(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function UT(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&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=jy.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">":KT(e,c);break;case'"':Oh(e,c,"double-quoted-scalar");break;case"'":Oh(e,c,"single-quoted-scalar");break;default:Oh(e,c,"scalar")}}function KT(e,t){let i=t.indexOf(`
|
|
114
114
|
`),r=t.substring(0,i),n=t.substring(i+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=r,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:r}]
|
|
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:i,source:t,end:[n]});break}default:{let r="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:i,indent:r,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=r,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:r}];$y(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 $y(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Oh(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});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:i,source:t,end:[n]});break}default:{let r="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:i,indent:r,source:t,end:n})}}}Fl.createScalarToken=GT;Fl.resolveAsScalar=JT;Fl.setScalarValue=UT});var Dy=C(Hy=>{"use strict";var YT=e=>"type"in e?Bl(e):Ml(e);function Bl(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Bl(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ml(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ml(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ml(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Ml({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Bl(t)),i)for(let a of i)n+=a.source;return r&&(n+=Bl(r)),n}Hy.stringify=YT});var Ly=C(By=>{"use strict";var Hh=Symbol("break visit"),XT=Symbol("skip children"),Fy=Symbol("remove item");function An(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),My(Object.freeze([]),e,t)}An.BREAK=Hh;An.SKIP=XT;An.REMOVE=Fy;An.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};An.parentCollection=(e,t)=>{let i=An.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function My(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;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=My(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Hh)return Hh;s===Fy&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}By.visit=An});var Ll=C(At=>{"use strict";var Dh=Oy(),QT=Dy(),ZT=Ly(),Fh="\uFEFF",Mh="",Bh="",Lh="",eI=e=>!!e&&"items"in e,tI=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function iI(e){switch(e){case Fh:return"<BOM>";case Mh:return"<DOC>";case Bh:return"<FLOW_END>";case Lh:return"<SCALAR>";default:return JSON.stringify(e)}}function rI(e){switch(e){case Fh:return"byte-order-mark";case Mh:return"doc-mode";case Bh:return"flow-error-end";case Lh: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}At.createScalarToken=Dh.createScalarToken;At.resolveAsScalar=Dh.resolveAsScalar;At.setScalarValue=Dh.setScalarValue;At.stringify=QT.stringify;At.visit=ZT.visit;At.BOM=Fh;At.DOCUMENT=Mh;At.FLOW_END=Bh;At.SCALAR=Lh;At.isCollection=eI;At.isScalar=tI;At.prettyToken=iI;At.tokenType=rI});var Wh=C(Vy=>{"use strict";var cs=Ll();function Ni(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var qy=new Set("0123456789ABCDEFabcdef"),nI=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ql=new Set(",[]{}"),aI=new Set(` ,[]{}
|
|
121
|
+
\r `),qh=e=>!e||aI.has(e),Vh=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,i=!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=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+r+1}return i===`
|
|
125
|
-
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&
|
|
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
|
+
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Ni(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]===cs.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield cs.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 i=this.peek(3);if((i==="---"||i==="...")&&Ni(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ni(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ni(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);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(qh),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&Ni(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield cs.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(qh),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ni(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),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
|
|
128
|
-
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>
|
|
128
|
+
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>Ni(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
|
|
129
129
|
`:t=a,i=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(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i: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(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=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+i>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield cs.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(Ni(a)||t&&ql.has(a))break;i=r}else if(Ni(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
|
-
`,a=this.buffer[r+1]):i=r),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||t&&ql.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&ql.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield cs.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(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(qh),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ni(r)||i&&ql.has(r)){i?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,i=this.buffer[t];for(;!Ni(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(nI.has(i))i=this.buffer[++t];else if(i==="%"&&qy.has(this.buffer[t+1])&&qy.has(this.buffer[t+2]))i=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 i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Vy.Lexer=Vh});var Jh=C(Wy=>{"use strict";var zh=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Wy.LineCounter=zh});var Uh=C(Ky=>{"use strict";var oI=zc("process"),zy=Ll(),sI=Wh();function Dr(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Jy(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 Uy(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 Vl(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 Ra(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 Wl(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function Gy(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Dr(t.start,"explicit-key-ind")&&!Dr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Uy(t.value)?t.value.end?Wl(t.value.end,t.sep):t.value.end=t.sep:Wl(t.start,t.sep),delete t.sep)}var Gh=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 sI.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,oI.env.LOG_TOKENS&&console.log("|",zy.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=zy.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){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 r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,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 i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Gy(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Jy(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.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":{Jy(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 i=this.startBlockValue(t);i?this.stack.push(i):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 i=Vl(this.peek(2)),r=Ra(i),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:r,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 i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Wl(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.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=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.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(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Dr(i.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(Uy(i.key)&&!Dr(i.sep,"newline")){let o=Ra(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Dr(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ra(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Dr(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{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||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Dr(i.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 r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Wl(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Dr(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Vl(r),a=Ra(n);Gy(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 i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+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 i=
|
|
143
|
-
`,i)}import{createHash as
|
|
144
|
-
# ambient_resume: true | false`,native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
|
|
142
|
+
`,i)+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 i=Vl(t),r=Ra(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Vl(t),r=Ra(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.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())}}};Ky.Parser=Gh});var eN=C(us=>{"use strict";var Yy=$h(),cI=ts(),ls=ns(),lI=If(),uI=Q(),dI=Jh(),Xy=Uh();function Qy(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new dI.LineCounter||null,prettyErrors:t}}function fI(e,t={}){let{lineCounter:i,prettyErrors:r}=Qy(t),n=new Xy.Parser(i?.addNewLine),a=new Yy.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(ls.prettifyError(e,i)),s.warnings.forEach(ls.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Zy(e,t={}){let{lineCounter:i,prettyErrors:r}=Qy(t),n=new Xy.Parser(i?.addNewLine),a=new Yy.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 ls.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(ls.prettifyError(e,i)),o.warnings.forEach(ls.prettifyError(e,i))),o}function hI(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Zy(e,i);if(!n)return null;if(n.warnings.forEach(a=>lI.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:r},i))}function pI(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return uI.isDocument(e)&&!r?e.toString(i):new cI.Document(e,r,i).toString(i)}us.parse=hI;us.parseAllDocuments=fI;us.parseDocument=Zy;us.stringify=pI});var _n=C(oe=>{"use strict";var mI=$h(),vI=ts(),gI=ph(),Kh=ns(),wI=Mo(),Fr=Q(),yI=jr(),NI=De(),bI=Or(),kI=Hr(),SI=Ll(),EI=Wh(),PI=Jh(),RI=Uh(),zl=eN(),tN=Oo();oe.Composer=mI.Composer;oe.Document=vI.Document;oe.Schema=gI.Schema;oe.YAMLError=Kh.YAMLError;oe.YAMLParseError=Kh.YAMLParseError;oe.YAMLWarning=Kh.YAMLWarning;oe.Alias=wI.Alias;oe.isAlias=Fr.isAlias;oe.isCollection=Fr.isCollection;oe.isDocument=Fr.isDocument;oe.isMap=Fr.isMap;oe.isNode=Fr.isNode;oe.isPair=Fr.isPair;oe.isScalar=Fr.isScalar;oe.isSeq=Fr.isSeq;oe.Pair=yI.Pair;oe.Scalar=NI.Scalar;oe.YAMLMap=bI.YAMLMap;oe.YAMLSeq=kI.YAMLSeq;oe.CST=SI;oe.Lexer=EI.Lexer;oe.LineCounter=PI.LineCounter;oe.Parser=RI.Parser;oe.parse=zl.parse;oe.parseAllDocuments=zl.parseAllDocuments;oe.parseDocument=zl.parseDocument;oe.stringify=zl.stringify;oe.visit=tN.visit;oe.visitAsync=tN.visitAsync});import{pathToFileURL as b1}from"url";import{randomUUID as nD}from"node:crypto";import{promises as tt}from"node:fs";import Pt from"node:path";import{execFileSync as MC}from"child_process";import To from"path";function Cr(e,t){return MC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function BC(e,t){let i=To.normalize(e),r=To.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function me(e){try{let t=To.resolve(Cr(e,["rev-parse","--show-toplevel"])),r=Cr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?To.resolve(r.slice(9)):t,a=null;try{a=Cr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!BC(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Jc(e){try{Cr(e,["rev-parse","--is-inside-work-tree"]);let t=Cr(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:To.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Zt(e){return Jc(e).map(t=>t.root)}function Io(e,t){try{return Cr(e,["check-ref-format","--branch",t]),Cr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function uf(e,t){try{let i=Cr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{randomUUID as LC}from"crypto";import{promises as ot}from"fs";import gi from"path";function xr(e){return e!==0&&e!==0n&&e!=="0"}function Ye(e,t){return xr(e.dev)&&xr(t.dev)&&xr(e.ino)&&xr(t.ino)}function q(e,t){let i=xr(e.dev)&&xr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=xr(e.ino)&&xr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}function ff(e,t){let i=gi.relative(e,t);return i===""||!gi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${gi.sep}`)}function qC(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function df(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function lg(e){let t=await ot.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 ot.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function jo(e){for(let t of e){let i=await ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!qC(t,i)||await ot.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function VC(e,t){let i=gi.resolve(e),r=gi.resolve(t);if(!ff(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await lg(i)],a=gi.relative(i,r).split(gi.sep).filter(Boolean),o=i;for(let s of a){await jo(n),o=gi.join(o,s);try{await ot.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await lg(o);if(!ff(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await jo(n),n}async function WC(e){let t;try{t=await ot.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function ug(e,t,i={}){let r=gi.dirname(e),n=i.containedRoot?await VC(i.containedRoot,r):null;n||await ot.mkdir(r,{recursive:!0});let a=gi.join(r,`.${gi.basename(e)}.${LC()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await ot.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([ot.lstat(a),ot.realpath(a)]);if(await jo(n),!c.isFile()||c.isSymbolicLink()||!df(s,c)||!ff(n[0].realPath,l))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(),!df(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await jo(n);let c=await ot.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!df(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await ot.link(a,e),await ot.unlink(a)):await ot.rename(a,e),await WC(r)}catch(c){if(await o?.close(),!n)await ot.rm(a,{force:!0});else try{await jo(n),await ot.rm(a,{force:!0})}catch{}throw c}}async function Ne(e,t,i={}){await ug(e,t,i)}async function dg(e,t,i={}){await ug(e,t,i)}async function ve(e,t,i={}){await Ne(e,JSON.stringify(t,null,2)+`
|
|
143
|
+
`,i)}import{createHash as UC}from"node:crypto";import{promises as wi}from"node:fs";import ei from"node:path";import{TextDecoder as KC}from"node:util";import hf from"path";var zC=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),JC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function GC(e){return e.toLowerCase().startsWith(".env")}function Hi(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>GC(r))?"environment-file":i.some(r=>JC.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>zC.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function pf(e,t){let i=Hi(t);if(i)return i;let r=hf.resolve(e.projectRoot,...t.split("/")),n=hf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===hf.resolve(e.configFile)?"native-runtime":null}var $o=1024*1024;function mf(e,t){let i=ei.relative(e,t);return i===""||!ei.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ei.sep}`)}function YC(e){let t=ei.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})||ei.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 i=e.toLowerCase(),r=Hi(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function XC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function QC(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function fg(e){let t=await wi.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await wi.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ZC(e,t){let i=ei.resolve(e),r=ei.resolve(t);if(!mf(i,r))throw new Error("Native artifact path is outside its root");let n=[await fg(i)],a=i;for(let o of ei.relative(i,r).split(ei.sep).filter(Boolean)){a=ei.join(a,o);let s=await fg(a);if(!mf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function hg(e){for(let t of e){let i=await wi.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!QC(t,i)||await wi.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ee(e){let t=YC(e.ref),i=e.maxBytes===null?null:XC(e.maxBytes??$o),r=ei.resolve(e.root,...t.split("/")),n=await ZC(e.root,ei.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await wi.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await wi.realpath(r);if(!mf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await wi.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),wi.lstat(r),wi.realpath(r)]);if(await hg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Gc(a,c)||!Gc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let E=i===null?h.length:i+1-f,S=await s.read(h,0,Math.min(h.length,E),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([s.stat(),wi.lstat(r),wi.realpath(r)]);if(await hg(n),!p.isFile()||p.isSymbolicLink()||v!==o||!Gc(c,m)||!Gc(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),y;try{y=new KC("utf-8",{fatal:!0}).decode(g)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:UC("sha256").update(g).digest("hex"),text:y}}finally{await s.close()}}var Xu=ma(_n(),1);import{promises as Ls}from"fs";import ut from"path";import ZI from"path";var ds=ma(_n(),1);import Gl from"path";var fs=64*1024,Ul=1024,Kl=64,Xh=5,CI=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],xI=["**/.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"],rN=[...CI,...xI].sort((e,t)=>e.localeCompare(t,"en"));function nN(e){let t=[...e],i=new Set(e);for(let r of rN)i.has(r)||(i.add(r),t.push(r));return t}var _t={include:["**/*"],exclude:[...rN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Jl={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.
|
|
144
|
+
# ambient_resume: true | false`,hook:"# Hook write policy shared by Native and Classic. Paths are project-relative.","hook.allow_paths":"# Project-relative directories allowed during guarded phases. Use one path per list item; empty by default.",native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
|
|
145
145
|
# language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time.
|
|
146
146
|
# clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
|
|
147
147
|
# archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed acceptance target before Native stops the completion loop.","native.snapshot":"# Controls the auditable project scope and bounded work used by Native content snapshots.","native.snapshot.include":"# Selects the project-relative paths included in Native snapshots. Patterns use / and support *, **, and ?.","native.snapshot.exclude":"# Removes paths from the included scope. Exclusions are bound into each new change baseline.","native.snapshot.max_files":"# Bounds the number of files captured by one snapshot. Increase it for large monorepos.","native.snapshot.max_total_bytes":"# Bounds the total file content hashed by one snapshot. Content is streamed and does not depend on Git hashes.","native.snapshot.max_duration_ms":"# Bounds snapshot capture time in milliseconds. Increase it together with the byte budget on slower or larger repositories.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
|
|
@@ -150,7 +150,7 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
150
150
|
# context_compression: off | beta`,"classic.review_mode":`# Sets the default review depth for new Classic changes.
|
|
151
151
|
# review_mode: off | standard | thorough`,"classic.auto_transition":`# Automatically enters the next Classic phase after a phase passes.
|
|
152
152
|
# auto_transition: true | false`},"zh-CN":{schema:"# Comet 使用的配置格式版本,请勿修改此值。",default_workflow:"# `/comet` 默认进入的工作流;该值也必须出现在 workflows 中。",workflows:"# 此项目启用的工作流,可填写 native、classic 或同时启用两者。",ambient_resume:`# 是否启用只读的环境感知恢复探针,同时作用于 Native 和 Classic;设为 false 可关闭自动工作流恢复。
|
|
153
|
-
# ambient_resume: true | false`,native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
|
|
153
|
+
# ambient_resume: true | false`,hook:"# Native 和 Classic 共享的 Hook 写入策略;路径必须是项目相对路径。","hook.allow_paths":"# 在受保护阶段允许写入的项目相对目录;每项填写一个目录,默认为空。",native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
|
|
154
154
|
# 可选值:en | zh-CN`,"native.clarification_mode":`# Native 提问澄清问题的方式:batch 每轮一次提出当前所有可回答的问题(默认),sequential 每轮只问一个。
|
|
155
155
|
# 可选值:batch | sequential`,"native.archive_confirmation":`# Native 归档检查成功后自动归档,或等待用户明确确认。
|
|
156
156
|
# 可选值:automatic | required`,"native.max_verify_failures":"# 同一个已确认验收目标最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.snapshot":"# Native 内容快照使用的可审计项目范围与有界工作预算。","native.snapshot.include":"# Native 快照纳入的项目相对路径;模式使用 /,支持 *、** 和 ?。","native.snapshot.exclude":"# 从纳入范围中排除路径;新 change 会把排除策略绑定到 baseline。","native.snapshot.max_files":"# 单次快照最多捕获的文件数;大型 monorepo 可按需提高。","native.snapshot.max_total_bytes":"# 单次快照最多哈希的文件内容总字节数;内容采用流式读取,不依赖 Git hash。","native.snapshot.max_duration_ms":"# 单次快照的最长执行时间(毫秒);较慢或更大的仓库应与字节预算一并提高。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
|
|
@@ -158,47 +158,47 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
158
158
|
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
159
159
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
160
160
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
161
|
-
# 可选值:true | false`}};function
|
|
162
|
-
`)){let o=
|
|
163
|
-
`))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?r="native":a.startsWith("classic:")?r="classic":r=null,n=null):/^ {2}[a-z_]+:/u.test(a)&&r==="native"&&(n=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(`
|
|
164
|
-
`)}function sI(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Hl.posix.isAbsolute(i)||Hl.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Rn(e){let t=sI(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Vy(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Hh(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Hl.posix.isAbsolute(r)||Hl.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.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(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function ns(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Wy(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Ml(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>Dl)throw new Error(`${t} exceeds ${Dl} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>Fl)throw new Error(`${t} contains more than ${Fl} wildcard tokens`);return e}function My(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Ml(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function $h(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function cI(e){if(e===void 0)return{...xt,include:[...xt.include],exclude:[...xt.exclude]};let t=ns(e,"native.snapshot");return{include:My(t.include,"native.snapshot.include",xt.include),exclude:My(t.exclude,"native.snapshot.exclude",xt.exclude),max_files:$h(t.max_files,xt.max_files,"native.snapshot.max_files"),max_total_bytes:$h(t.max_total_bytes,xt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:$h(t.max_duration_ms,xt.max_duration_ms,"native.snapshot.max_duration_ms")}}function lI(e){if(e===void 0)return;let t=ns(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="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=ns(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:i,fromArtifactRoot:Rn(r),toArtifactRoot:Rn(n),stage:a,...o?{cleanup:o}:{}}}function uI(e,t={}){let i=ns(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Oh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=lI(i.pending_root_move);return{artifact_root:Rn(r),language:Wy(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:cI(i.snapshot),...s?{pending_root_move:s}:{}}}function dI(e){let t=ns(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="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");return{artifact_layout:Vy(t.artifact_layout),language:Wy(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function fI(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function hI(e,t,i,r,n){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!n.allowPartialProject&&e.native!==void 0)||n.allowPartialProject&&!a)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 s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:r,...t?{native:t}:{},...i?{classic:i}:{}}}function ba(e,t={}){let i=(0,as.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=fI(n.ambient_resume),o=n.native===void 0?void 0:uI(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=n.classic===void 0?void 0:dI(n.classic),c=hI(n,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function zy(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 Jy(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...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.pending_root_move?{pending_root_move:zy(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}}:{}}}function rs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function cs(e,t){let i=Jy(t),r=ba((0,as.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.native){let a=rs(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=rs(a.pending_root_move),c=zy(r.native.pending_root_move),l=rs(s.cleanup),u=rs(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...rs(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}function Bl(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Rn(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Oh,snapshot:{...xt,include:[...xt.include],exclude:[...xt.exclude]}}}}import{createHash as mI}from"crypto";import{promises as Vl}from"fs";import Or from"path";import{constants as Ll,promises as xn}from"fs";var gi=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Dh(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Gy(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ls(e){return{dev:e.dev,ino:e.ino,birthtime:Dh(e)}}function ql(e,t){let i=ls(e),r=ls(t);return Ye(i,r)?L(i,r):L(i,r)&&Dh(e)===Dh(t)&&Gy(e)===Gy(t)&&e.size===t.size}async function Cn(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await xn.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new gi("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new gi("too-large",`${r} exceeds ${t} bytes`);let o=await xn.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:ls(a)});let s=process.platform==="win32"?Ll.O_RDONLY:Ll.O_RDONLY|Ll.O_NOFOLLOW|Ll.O_NONBLOCK,c;try{c=await xn.open(e,s)}catch(l){throw l.code==="ELOOP"?new gi("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),xn.lstat(e,{bigint:n}),xn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ql(a,l)||!ql(a,u))throw new gi("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:ls(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:S}=await c.read(m,0,Math.min(m.length,y),null);if(S===0)break;if(h+=S,h>t)throw new gi("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,S)))}await i.hooks?.beforeFinalCheck?.();let[p,v,N]=await Promise.all([c.stat({bigint:n}),xn.lstat(e,{bigint:n}),xn.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||N!==o||!ql(a,p)||!ql(a,v))throw new gi("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:ls(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:N}}finally{await c.close()}}function pI(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Fh(e,t){let i=Or.relative(e,t);return i===""||!Or.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Or.sep}`)}async function Uy(e,t){let i=Or.resolve(e),r=await Vl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Vl.realpath(i)}async function Ky(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Or.join(n,i[a]);let o;try{o=await Vl.lstat(n)}catch(u){if(pI(u))return{exists:!1,kind:"missing"};throw u}let s=Or.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Vl.realpath(n);if(!Fh(t,l))throw new Error(`${r.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 rr(e,t,i){let r=Hh(t,i.label),n=Or.resolve(e),a=await Uy(n,i.label),o=r.split("/"),s=Or.resolve(n,...o);if(!Fh(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Ky(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Oi(e,t,i,r){let n=await rr(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await Uy(n.projectRoot,r.label);return Cn(n.target,i,{...r,verify:async(o,s)=>{if(!Fh(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Ky(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var us=".comet/config.yaml";function Mh(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function vI(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Bh(e,t={}){return(await ds(e,t)).document}async function Yy(e){try{return(await Oi(e,us,os,{label:us})).bytes}catch(t){if(vI(t))return null;throw t}}function Xy(e){return e?{exists:!0,sha256:mI("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Wl(e){return Xy(await Yy(e))}async function ds(e,t={}){let i=await Yy(e);return{document:i?ba(i.toString("utf8"),t):null,identity:Xy(i)}}import{randomUUID as gI}from"crypto";import{constants as wI,promises as mt}from"fs";import wi from"path";async function Vh(e,t){try{return await mt.link(e,t),{linked:!0}}catch(i){let r=i.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw i}return await mt.copyFile(e,t,wI.COPYFILE_EXCL),{linked:!1}}function qh(e,t){let i=wi.relative(e,t);return i===""||!wi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${wi.sep}`)}function zl(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function yI(e,t){return L(e,zl(t))}function Lh(e,t){let i=zl(e),r=zl(t);return Ye(i,r)?L(i,r):L(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Qy(e){let t=await mt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await mt.realpath(e),...zl(t)}}async function fs(e){for(let t of e){let i=await mt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!yI(t,i)||await mt.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function NI(e,t){let i=wi.resolve(e),r=wi.resolve(t);if(!qh(i,r))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await Qy(i)],a=wi.relative(i,r).split(wi.sep).filter(Boolean),o=i;for(let s of a){await fs(n),o=wi.join(o,s);try{await mt.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Qy(o);if(!qh(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await fs(n),n}async function bI(e){let t;try{t=await mt.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function kI(e,t,i){let r=wi.dirname(e),n=await NI(i.containedRoot,r),a=wi.join(r,`.${wi.basename(e)}.${gI()}.tmp`),o,s;try{await i.beforeTemporaryOpen?.(),o=await mt.open(a,"wx"),s=await o.stat();let[c,l]=await Promise.all([mt.lstat(a),mt.realpath(a)]);if(await fs(n),!c.isFile()||c.isSymbolicLink()||!Lh(s,c)||!qh(n[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Lh(s,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await i.beforeCommit?.(),await fs(n);let u=await mt.lstat(a);if(!u.isFile()||u.isSymbolicLink()||!Lh(u,s))throw new Error("Contained atomic write temporary file changed before commit");i.exclusive?(await Vh(a,e),await mt.unlink(a)):await mt.rename(a,e),await bI(r)}catch(c){await o?.close();try{await fs(n),await mt.rm(a,{force:!0})}catch{}throw c}}async function An(e,t,i){await kI(e,t,i)}var zV=16*1024;async function Wh(e,t){if(!t)return;let i=await Wl(e);if(!Mh(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as Zy,promises as Hi}from"fs";import te from"path";import PI from"os";var hs=".comet/config.yaml",RI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function zh(e){try{return await Hi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xI(e){try{let t=await Hi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Sa(e,t){let i=te.relative(e,t);return i===""||!te.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${te.sep}`)}async function ka(e){let t=[],i=e;for(;!await zh(i);){let n=te.dirname(i);if(n===i)break;t.push(te.basename(i)),i=n}let r=await Hi.realpath(i);return te.resolve(r,...t.reverse())}async function Jh(e){try{return(await Hi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Jl(e){let t=te.resolve(e);try{(await Hi.stat(t)).isDirectory()||(t=te.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=te.resolve(PI.homedir());for(;;){if(!(t===r&&i!==r)){let o=te.join(t,...hs.split("/")),s=t===i||await xI(o);if(await zh(o)&&s)return t}if(await zh(te.join(t,".git")))return t;let a=te.dirname(t);if(a===t)return i;t=a}}function Hr(e){return Rn(e)}async function CI(e,t){let i=Hr(t),r=te.resolve(e,...i.split("/")),n=await Hi.realpath(e),a=await ka(r);if(!Sa(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function ce(e,t){let i=Hr(t),r=await CI(e,i),n=te.join(r,"comet");if(await Jh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([ka(r),ka(n)]);if(!Sa(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=te.resolve(e),c=te.join(s,".comet","runtime","native");if(await Jh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Hi.realpath(s),ka(c)]);if(!Sa(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:te.join(e,...hs.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:te.join(n,"specs"),changesDir:te.join(n,"changes"),archiveDir:te.join(n,"archive"),runtimeDir:c,changesRuntimeDir:te.join(c,"changes"),locksDir:te.join(c,"locks"),transactionsDir:te.join(c,"transactions")}}async function Gl(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await T(e.nativeRoot,t),await Hi.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await T(e.projectRoot,t),await Hi.mkdir(t,{recursive:!0})}))}function tN(e){if(!RI.test(e))throw new Error(`Invalid Native change name: ${e}`)}function We(e,t){tN(t);let i=te.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function _n(e,t){tN(t);let i=te.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function D(e,t){let i=We(e,t);if(Zy(i))return i;let r=_n(e,t);return Zy(r)?r:i}async function eN(e){try{let t=await Hi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function ps(e,t){let i=We(e,t),r=_n(e,t),[n,a]=await Promise.all([eN(i),eN(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function Dr(e,t){if(!t.startsWith("runtime/")||te.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=te.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=te.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return Sa(te.resolve(e),te.resolve(t))}async function T(e,t){let i=te.resolve(e),r=te.resolve(t);if(!Sa(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Jh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([ka(i),ka(r)]);if(!Sa(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Gh=xt;var Ul=Ml,iN=Ly;function Tn(e="docs",t="en"){return Bl(e,t)}async function Y(e){let t=(await Bh(e))?.config??null;return t?.native?t:null}async function Ea(e){let t=await Y(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 Bt(e,t,i={}){let r=await ds(e,{allowPartialProject:!0}),n=cs(r.document?.value??{},t),a=AI.join(e,...hs.split("/"));await we(a,ss(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Wh(e,r.identity)}})}async function rN(e){let t=await Jl(e.startPath),i=await Y(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${hs} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?Hr(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??Tn(r??"docs"),a=await ce(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as E$}from"fs";import P$ from"path";import{AsyncLocalStorage as _I}from"async_hooks";import{randomUUID as oN}from"crypto";import{promises as Qt}from"fs";import sN from"os";import Pe from"path";var nN=16*1024,Uh=".coordinator",TI=5e3,aN=new _I,Kl=new Map;function II(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function jI(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function cN(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 Kh(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ye(i,r)?L(i,r):L(i,r)&&e.size===t.size}function Yl(e,t){return Kh(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function $I(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&&Yl(e.identity,t.identity)}async function Di(e){let t,i;try{let r=await Cn(e,nN,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof gi?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${nN} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:jI(JSON.parse(t.toString("utf8")),e),identity:cN(i)}}async function OI(e){return(await Di(e))?.owner??null}function Yh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==sN.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=LI(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function HI(e,t){try{await Qt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Qt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Xl(e,t){let i=await Di(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Yl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Qt.mkdir(t,{recursive:!0});let r=Pe.join(t,`${Pe.basename(e.file)}.${e.owner.id}.${oN()}.removed`);try{await Qt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Di(r);if(!n||n.owner.id!==e.owner.id||!Kh(n.identity,e.identity))throw await HI(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Qt.rm(r,{force:!0}),"removed"}function lN(e){return{id:oN(),pid:process.pid,hostname:sN.hostname(),createdAt:new Date().toISOString(),operation:e}}async function uN(e,t){let i;try{i=await Qt.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await OI(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
165
|
-
`,"utf8"),await i.sync(),
|
|
166
|
-
${
|
|
161
|
+
# 可选值:true | false`}};function aN(e,t){return Jl[t][e]}function AI(e,t,i){let r=/^(\s*)([a-z_]+):/u.exec(e);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Jl.en)return a;if(n===2&&t){let o=`${t}.${a}`;if(o in Jl.en)return o}if(n===2&&t===null&&a==="hook")return"hook";if(n===2&&t==="hook"&&a==="allow_paths")return"hook.allow_paths";if(n===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Jl.en)return o}return null}function hs(e,t){let i=[],r=null,n=null;for(let a of(0,ds.stringify)(e).trimEnd().split(`
|
|
162
|
+
`)){let o=AI(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of aN(o,t).split(`
|
|
163
|
+
`))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?r="native":a.startsWith("classic:")?r="classic":a.startsWith("hook:")?r="hook":r=null,n=null):/^ {2}[a-z_]+:/u.test(a)&&r==="native"&&(n=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(`
|
|
164
|
+
`)}function _I(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Gl.posix.isAbsolute(i)||Gl.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Tn(e){let t=_I(e,"native.artifact_root");return t.length===0?".":t.join("/")}function oN(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Yl(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Gl.posix.isAbsolute(r)||Gl.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.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(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function xa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function sN(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Xl(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>Ul)throw new Error(`${t} exceeds ${Ul} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>Kl)throw new Error(`${t} contains more than ${Kl} wildcard tokens`);return e}function iN(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Xl(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Yh(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function TI(e){if(e===void 0)return{..._t,include:[..._t.include],exclude:[..._t.exclude]};let t=xa(e,"native.snapshot");return{include:iN(t.include,"native.snapshot.include",_t.include),exclude:iN(t.exclude,"native.snapshot.exclude",_t.exclude),max_files:Yh(t.max_files,_t.max_files,"native.snapshot.max_files"),max_total_bytes:Yh(t.max_total_bytes,_t.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Yh(t.max_duration_ms,_t.max_duration_ms,"native.snapshot.max_duration_ms")}}function II(e){if(e===void 0)return;let t=xa(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="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=xa(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:i,fromArtifactRoot:Tn(r),toArtifactRoot:Tn(n),stage:a,...o?{cleanup:o}:{}}}function jI(e,t={}){let i=xa(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Xh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=II(i.pending_root_move);return{artifact_root:Tn(r),language:sN(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:TI(i.snapshot),...s?{pending_root_move:s}:{}}}function $I(e){let t=xa(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="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");return{artifact_layout:oN(t.artifact_layout),language:sN(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function OI(e){let i=xa(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Yl(r,`hook.allow_paths[${n}]`)))]}}function HI(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function DI(e,t,i,r,n,a){let o=e.schema!==void 0;if(!(o||e.default_workflow!==void 0||e.workflows!==void 0||!a.allowPartialProject&&e.native!==void 0)||a.allowPartialProject&&!o)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 c=e.workflows??[e.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:l,ambient_resume:n,...t?{hook:t}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function Aa(e,t={}){let i=(0,ds.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=HI(n.ambient_resume),o=n.hook===void 0?void 0:OI(n.hook),s=n.native===void 0?void 0:jI(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:$I(n.classic),l=DI(n,o,s,c,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function cN(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 lN(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...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.pending_root_move?{pending_root_move:cN(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}}:{}}}function Ca(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ps(e,t){let i=lN(t),r=Aa((0,ds.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...Ca(e.hook),allow_paths:[...r.hook.allow_paths]}),r.native){let a=Ca(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=Ca(a.pending_root_move),c=cN(r.native.pending_root_move),l=Ca(s.cleanup),u=Ca(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...Ca(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}function Ql(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Tn(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Xh,snapshot:{..._t,include:[..._t.include],exclude:[..._t.exclude]}}}}import{createHash as MI}from"crypto";import{promises as tu}from"fs";import Mr from"path";import{constants as Zl,promises as In}from"fs";var bi=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Qh(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function uN(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ms(e){return{dev:e.dev,ino:e.ino,birthtime:Qh(e)}}function eu(e,t){let i=ms(e),r=ms(t);return Ye(i,r)?q(i,r):q(i,r)&&Qh(e)===Qh(t)&&uN(e)===uN(t)&&e.size===t.size}async function jn(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await In.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new bi("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new bi("too-large",`${r} exceeds ${t} bytes`);let o=await In.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:ms(a)});let s=process.platform==="win32"?Zl.O_RDONLY:Zl.O_RDONLY|Zl.O_NOFOLLOW|Zl.O_NONBLOCK,c;try{c=await In.open(e,s)}catch(l){throw l.code==="ELOOP"?new bi("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),In.lstat(e,{bigint:n}),In.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!eu(a,l)||!eu(a,u))throw new bi("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:ms(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:E}=await c.read(m,0,Math.min(m.length,y),null);if(E===0)break;if(h+=E,h>t)throw new bi("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([c.stat({bigint:n}),In.lstat(e,{bigint:n}),In.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!eu(a,p)||!eu(a,v))throw new bi("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:ms(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:g}}finally{await c.close()}}function FI(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Zh(e,t){let i=Mr.relative(e,t);return i===""||!Mr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Mr.sep}`)}async function dN(e,t){let i=Mr.resolve(e),r=await tu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return tu.realpath(i)}async function fN(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Mr.join(n,i[a]);let o;try{o=await tu.lstat(n)}catch(u){if(FI(u))return{exists:!1,kind:"missing"};throw u}let s=Mr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await tu.realpath(n);if(!Zh(t,l))throw new Error(`${r.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 sr(e,t,i){let r=Yl(t,i.label),n=Mr.resolve(e),a=await dN(n,i.label),o=r.split("/"),s=Mr.resolve(n,...o);if(!Zh(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await fN(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Mi(e,t,i,r){let n=await sr(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await dN(n.projectRoot,r.label);return jn(n.target,i,{...r,verify:async(o,s)=>{if(!Zh(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await fN(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var vs=".comet/config.yaml";function ep(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function BI(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function iu(e,t={}){return(await gs(e,t)).document}async function hN(e){try{return(await Mi(e,vs,fs,{label:vs})).bytes}catch(t){if(BI(t))return null;throw t}}function pN(e){return e?{exists:!0,sha256:MI("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ru(e){return pN(await hN(e))}async function gs(e,t={}){let i=await hN(e);return{document:i?Aa(i.toString("utf8"),t):null,identity:pN(i)}}async function tp(e){return(await iu(e))?.config??null}import{randomUUID as LI}from"crypto";import{constants as qI,promises as gt}from"fs";import ki from"path";async function np(e,t){try{return await gt.link(e,t),{linked:!0}}catch(i){let r=i.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw i}return await gt.copyFile(e,t,qI.COPYFILE_EXCL),{linked:!1}}function rp(e,t){let i=ki.relative(e,t);return i===""||!ki.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ki.sep}`)}function nu(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function VI(e,t){return q(e,nu(t))}function ip(e,t){let i=nu(e),r=nu(t);return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mN(e){let t=await gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await gt.realpath(e),...nu(t)}}async function ws(e){for(let t of e){let i=await gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!VI(t,i)||await gt.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function WI(e,t){let i=ki.resolve(e),r=ki.resolve(t);if(!rp(i,r))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await mN(i)],a=ki.relative(i,r).split(ki.sep).filter(Boolean),o=i;for(let s of a){await ws(n),o=ki.join(o,s);try{await gt.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await mN(o);if(!rp(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ws(n),n}async function zI(e){let t;try{t=await gt.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function JI(e,t,i){let r=ki.dirname(e),n=await WI(i.containedRoot,r),a=ki.join(r,`.${ki.basename(e)}.${LI()}.tmp`),o,s;try{await i.beforeTemporaryOpen?.(),o=await gt.open(a,"wx"),s=await o.stat();let[c,l]=await Promise.all([gt.lstat(a),gt.realpath(a)]);if(await ws(n),!c.isFile()||c.isSymbolicLink()||!ip(s,c)||!rp(n[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!ip(s,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await i.beforeCommit?.(),await ws(n);let u=await gt.lstat(a);if(!u.isFile()||u.isSymbolicLink()||!ip(u,s))throw new Error("Contained atomic write temporary file changed before commit");i.exclusive?(await np(a,e),await gt.unlink(a)):await gt.rename(a,e),await zI(r)}catch(c){await o?.close();try{await ws(n),await gt.rm(a,{force:!0})}catch{}throw c}}async function $n(e,t,i){await JI(e,t,i)}var _W=16*1024;async function ap(e,t){if(!t)return;let i=await ru(e);if(!ep(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as vN,promises as Bi}from"fs";import ie from"path";import KI from"os";var ys=".comet/config.yaml",YI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function op(e){try{return await Bi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function XI(e){try{let t=await Bi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ta(e,t){let i=ie.relative(e,t);return i===""||!ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ie.sep}`)}async function _a(e){let t=[],i=e;for(;!await op(i);){let n=ie.dirname(i);if(n===i)break;t.push(ie.basename(i)),i=n}let r=await Bi.realpath(i);return ie.resolve(r,...t.reverse())}async function sp(e){try{return(await Bi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function au(e){let t=ie.resolve(e);try{(await Bi.stat(t)).isDirectory()||(t=ie.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=ie.resolve(KI.homedir());for(;;){if(!(t===r&&i!==r)){let o=ie.join(t,...ys.split("/")),s=t===i||await XI(o);if(await op(o)&&s)return t}if(await op(ie.join(t,".git")))return t;let a=ie.dirname(t);if(a===t)return i;t=a}}function Br(e){return Tn(e)}async function QI(e,t){let i=Br(t),r=ie.resolve(e,...i.split("/")),n=await Bi.realpath(e),a=await _a(r);if(!Ta(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function re(e,t){let i=Br(t),r=await QI(e,i),n=ie.join(r,"comet");if(await sp(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_a(r),_a(n)]);if(!Ta(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=ie.resolve(e),c=ie.join(s,".comet","runtime","native");if(await sp(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Bi.realpath(s),_a(c)]);if(!Ta(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:ie.join(e,...ys.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:ie.join(n,"specs"),changesDir:ie.join(n,"changes"),archiveDir:ie.join(n,"archive"),runtimeDir:c,changesRuntimeDir:ie.join(c,"changes"),locksDir:ie.join(c,"locks"),transactionsDir:ie.join(c,"transactions")}}async function ou(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await T(e.nativeRoot,t),await Bi.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await T(e.projectRoot,t),await Bi.mkdir(t,{recursive:!0})}))}function wN(e){if(!YI.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ze(e,t){wN(t);let i=ie.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function On(e,t){wN(t);let i=ie.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function M(e,t){let i=ze(e,t);if(vN(i))return i;let r=On(e,t);return vN(r)?r:i}async function gN(e){try{let t=await Bi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ns(e,t){let i=ze(e,t),r=On(e,t),[n,a]=await Promise.all([gN(i),gN(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function Lr(e,t){if(!t.startsWith("runtime/")||ie.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=ie.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=ie.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return Ta(ie.resolve(e),ie.resolve(t))}async function T(e,t){let i=ie.resolve(e),r=ie.resolve(t);if(!Ta(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await sp(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_a(i),_a(r)]);if(!Ta(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var cp=_t;var su=Xl,yN=nN;function Hn(e="docs",t="en"){return Ql(e,t)}async function Y(e){let t=(await iu(e))?.config??null;return t?.native?t:null}async function Ia(e){let t=await Y(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 Vt(e,t,i={}){let r=await gs(e,{allowPartialProject:!0}),n=ps(r.document?.value??{},t),a=ZI.join(e,...ys.split("/"));await Ne(a,hs(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ap(e,r.identity)}})}async function NN(e){let t=await au(e.startPath),i=await Y(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${ys} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?Br(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??Hn(r??"docs"),a=await re(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Y$}from"fs";import X$ from"path";import{AsyncLocalStorage as ej}from"async_hooks";import{randomUUID as SN}from"crypto";import{promises as ii}from"fs";import EN from"os";import Ce from"path";var bN=16*1024,lp=".coordinator",tj=5e3,kN=new ej,cu=new Map;function ij(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function rj(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function PN(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 up(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ye(i,r)?q(i,r):q(i,r)&&e.size===t.size}function lu(e,t){return up(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function nj(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&&lu(e.identity,t.identity)}async function Li(e){let t,i;try{let r=await jn(e,bN,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof bi?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${bN} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:rj(JSON.parse(t.toString("utf8")),e),identity:PN(i)}}async function aj(e){return(await Li(e))?.owner??null}function dp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==EN.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=dj(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function oj(e,t){try{await ii.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ii.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function uu(e,t){let i=await Li(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lu(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ii.mkdir(t,{recursive:!0});let r=Ce.join(t,`${Ce.basename(e.file)}.${e.owner.id}.${SN()}.removed`);try{await ii.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Li(r);if(!n||n.owner.id!==e.owner.id||!up(n.identity,e.identity))throw await oj(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ii.rm(r,{force:!0}),"removed"}function RN(e){return{id:SN(),pid:process.pid,hostname:EN.hostname(),createdAt:new Date().toISOString(),operation:e}}async function CN(e,t){let i;try{i=await ii.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await aj(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
165
|
+
`,"utf8"),await i.sync(),PN(await i.stat({bigint:!0}))}finally{await i.close()}}async function sj(e,t){let i=await T(e.runtimeDir,e.locksDir);await ii.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,Ce.join(i,lp));await ii.mkdir(r,{recursive:!0});let n=RN(t),a=Ce.join(r,`.${n.id}.tmp`),o=Ce.join(r,`${n.id}.claim`);try{let s=await CN(a,n);await ii.rename(a,o);let c=await Li(o);if(!c||!up(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await ii.rm(a,{force:!0})}}async function cj(e){let t=Ce.dirname(e.file),i=!1,r=Ce.basename(e.file);for(let n of await ii.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 Li(a),s=dp(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await uu(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function xN(e){let t=await Li(e.file);if(t){if(t.owner.id!==e.owner.id||!lu(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await uu(t,Ce.dirname(e.file))}}async function lj(e,t){let i=Date.now()+tj;for(;;){let r=await sj(e,t);if(!await cj(r))return r;if(await xN(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function uj(e){let t=cu.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return cu.set(e,n),await t,()=>{i(),cu.get(e)===n&&cu.delete(e)}}async function du(e,t,i){let r=Ce.resolve(e.locksDir),n=kN.getStore();if(n?.has(r))return i();let a=await uj(r);try{let o=await lj(e,t),s=new Map(n??[]);return s.set(r,o),await kN.run(s,async()=>{try{return await i()}finally{await xN(o)}})}finally{a()}}async function Dn(e,t,i){let r=[...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=r[a];return o?du(o,t,()=>n(a+1)):i()};return n(0)}async function cr(e,t,i){return du(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await ii.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,Ce.join(r,ij(t))),a=RN(i),o=await CN(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function lr(e){await Li(e.file)&&await du({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Ce.basename(e.file)}`,async()=>{let t=await Li(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!lu(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=Ce.join(e.locksDir,lp);await uu(t,i)})}function dj(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function bs(e){return dp(await Li(e))}async function fp(e,t,i){return du(e,`take over ${Ce.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(Ce.resolve(Ce.dirname(n))!==Ce.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await Li(n),o=dp(a);if(o.status==="missing")return{status:"missing"};if(i&&!nj(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=Ce.join(r,lp);return await uu(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as g$}from"node:fs";import kp from"node:path";import i$ from"node:path";import FN from"node:path";import AN from"node:path";import{createHash as fj}from"crypto";function Si(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function hj(e,t){t.has(e)&&Si("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||Si("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Si("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Si("symbol properties are not supported"),`[${e.map(r=>hp(r,t)).join(",")}]`}finally{t.delete(e)}}function pj(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Si("only plain objects are supported"),t.has(e)&&Si("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Si("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Si("accessor properties are not supported"),`${JSON.stringify(o)}:${hp(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function hp(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)||Si("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?hj(e,t):pj(e,t);case"bigint":case"function":case"symbol":case"undefined":return Si(`${typeof e} values are not supported`)}return Si("unsupported value type")}function ks(e){return hp(e,new Set)}function D(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return fj("sha256").update(`${e}
|
|
166
|
+
${ks(t)}`).digest("hex")}var mj="comet.native.acceptance.v1",vj=/^acceptance-[a-f0-9]{64}$/u,gj=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),wj=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,yj=/^[a-f0-9]{64}$/u,Nj=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function bj(e,t){return e<t?-1:e>t?1:0}var ur=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Es=Object.freeze({maxCriteria:1024}),_N="<!-- comet-native:acceptance-evidence:start -->",TN="<!-- comet-native:acceptance-evidence:end -->";function IN(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function jN(e,t){let i=t.toString(36),r=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function kj(e){if(!yj.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=Nj.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function Sj(e,t){let i=IN(e.text,ur.maxTextBytes),r=e.context.slice(0,ur.maxContextItems).map(n=>IN(n,ur.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function ON(e){let t=kj({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(bj),n=r.slice(0,ur.maxFailedCheckIds),a=e.criteria.slice(t,t+ur.maxItems);for(let c of a){let l=[...i,Sj(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?jN(e.acceptanceHash,u):null,limits:{...ur}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ur.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?jN(e.acceptanceHash,o):null,limits:{...ur}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>ur.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function mp(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 pp(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function $N(e){return e.includes("-->")||e.includes("--!>")}function*ja(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
167
167
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
168
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=
|
|
169
|
-
`),[],r)),"Brief",r)}function
|
|
170
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of
|
|
171
|
-
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=yN(o),c=aj(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function aj(e){let t=yN([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var oj=/^A[1-9]\d*$/u;function kN(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||bN.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||bN.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function sj(e,t){return e.localeCompare(t,"en")}function iu(e){let t=kN(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>sj(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=Zl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=kN(a.source,`Native spec source for ${a.capability}`);r.push(...eu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...tu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=ws(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function SN(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!oj.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function EN(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var ou=ko(Na(),1);import{promises as cj}from"node:fs";var In="comet.native.v4",Ns="comet.native.local-execution.v4";function ru(){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 lj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dj=/^A[1-9][0-9]*$/u,fj=new Set(["schema","name","language","phase","status","state_version","brief","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),au=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Ct(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function At(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ot(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function np(e,t){return e===null?null:ot(e,t)}function Ra(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Re(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function hj(e,t){return e===null?null:Re(e,t,Number.MIN_SAFE_INTEGER)}function Qe(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Fi(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function su(e,t){return Fi(e,t,(i,r)=>ot(i,`${t}[${r}]`))}function jn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function xa(e,t){let i=ot(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function ap(e,t,i=!1){let r=ot(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Ni(e,t){let i=Ct(e,t);return At(i,new Set(["text","truncated"]),t),{text:ot(i.text,`${t}.text`,{empty:!0}),truncated:Ra(i.truncated,`${t}.truncated`)}}function pj(e,t){let i=`Native spec_changes[${t}]`,r=Ct(e,i);At(r,new Set(["capability","operation","source"]),i);let n=ot(r.capability,`${i}.capability`);if(!uj.test(n))throw new Error(`${i}.capability is invalid`);let a=Qe(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:ap(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function mj(e){let t="Native workspace",i=Ct(e,t);At(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Qe(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=np(i.change_branch,`${t}.change_branch`),a=np(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Qe(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function vj(e){let t="Native loop",i=Ct(e,t);At(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=su(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return jn(r,`${t}.previous_unresolved_ids`),{stage:Qe(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:Re(i.goal_cycle,`${t}.goal_cycle`,1),iteration:Re(i.iteration,`${t}.iteration`),attempt:Re(i.attempt,`${t}.attempt`),retry_epoch:Re(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:Re(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:Re(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:Re(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:np(i.next_action,`${t}.next_action`)}}function gj(e,t){let i=`Native acceptance[${t}]`,r=Ct(e,i);At(r,new Set(["id","source","text","result","reason"]),i);let n=ot(r.id,`${i}.id`);if(!dj.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:ap(r.source,`${i}.source`),text:ot(r.text,`${i}.text`),result:Qe(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ni(r.reason,`${i}.reason`)}}function wj(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Ct(e,i);return At(r,new Set(["name","result","note"]),i),{name:Ni(r.name,`${i}.name`),result:Qe(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ni(r.note,`${i}.note`)}}function yj(e){let t="Native builder_handoff",i=Ct(e,t);At(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),t);let r=su(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return jn(r,`${t}.addressed_acceptance_ids`),{candidate_id:ot(i.candidate_id,`${t}.candidate_id`),identity_provider:ot(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:ot(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:Re(i.iteration,`${t}.iteration`,1),summary:Ni(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Fi(i.checks,`${t}.checks`,wj),checks_truncated:Ra(i.checks_truncated,`${t}.checks_truncated`),known_limits:Fi(i.known_limits,`${t}.known_limits`,(n,a)=>Ni(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Ra(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:xa(i.submitted_at,`${t}.submitted_at`)}}function Nj(e,t){let i=`Native blockers[${t}]`,r=Ct(e,i);At(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=su(r.acceptance_ids,`${i}.acceptance_ids`);return jn(n,`${i}.acceptance_ids`),{owner:Qe(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ni(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Qe(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function bj(e,t){let i=`Native verification.checks[${t}]`,r=Ct(e,i);return At(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:ot(r.id,`${i}.id`),name:Ni(r.name,`${i}.name`),argv_display:Fi(r.argv_display,`${i}.argv_display`,(n,a)=>Ni(n,`${i}.argv_display[${a}]`)),argv_truncated:Ra(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:ap(r.cwd_ref,`${i}.cwd_ref`,!0),status:Qe(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:hj(r.exit_code,`${i}.exit_code`),duration_ms:Re(r.duration_ms,`${i}.duration_ms`)}}function kj(e){let t="Native verification",i=Ct(e,t);At(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Fi(i.checks,`${t}.checks`,bj);jn(r.map(a=>a.id),`${t}.checks IDs`);let n=ot(i.identity_provider,`${t}.identity_provider`);return{candidate_id:ot(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ot(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:Re(i.iteration,`${t}.iteration`,1),attempt:Re(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Qe(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Qe(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ni(i.summary,`${t}.summary`),risks:Fi(i.risks,`${t}.risks`,(a,o)=>Ni(a,`${t}.risks[${o}]`)),risks_truncated:Ra(i.risks_truncated,`${t}.risks_truncated`),completed_at:xa(i.completed_at,`${t}.completed_at`)}}function PN(e,t){let i=`Native history[${t}]`,r=Ct(e,i);At(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=su(r.unresolved_ids,`${i}.unresolved_ids`);return jn(n,`${i}.unresolved_ids`),{goal_cycle:Re(r.goal_cycle,`${i}.goal_cycle`,1),iteration:Re(r.iteration,`${i}.iteration`),attempt:Re(r.attempt,`${i}.attempt`),outcome:Qe(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ni(r.summary,`${i}.summary`),completed_at:xa(r.completed_at,`${i}.completed_at`)}}function Sj(e){let t="Native history_overflow.outcome_counts",i=Ct(e,t),r=["pass","fail","blocked","execution-error","recovery"];return At(i,new Set(r),t),{pass:Re(i.pass,`${t}.pass`),fail:Re(i.fail,`${t}.fail`),blocked:Re(i.blocked,`${t}.blocked`),"execution-error":Re(i["execution-error"],`${t}.execution-error`),recovery:Re(i.recovery,`${t}.recovery`)}}function Ej(e){let t="Native history_overflow",i=Ct(e,t);At(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=Re(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:xa(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:xa(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Sj(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Pj(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(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.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 r=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(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Rj(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 i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);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(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.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 X(e){let t=Ct(e,"Native portable state");if(At(t,fj,"Native portable state"),t.schema!==In)throw new Error(`Native portable state schema must be ${In}`);let i=ot(t.name,"Native state name");if(!lj.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=Fi(t.spec_changes,"Native spec_changes",pj);jn(r.map(s=>s.capability),"Native spec change capabilities");let n=Fi(t.acceptance,"Native acceptance",gj);jn(n.map(s=>s.id),"Native acceptance IDs");let a=Fi(t.history,"Native history",PN);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:In,name:i,language:Qe(t.language,["en","zh-CN"],"Native state language"),phase:Qe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Qe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:Re(t.state_version,"Native state_version",1),brief:"brief.md",spec_changes:r,workspace:mj(t.workspace),loop:vj(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:yj(t.builder_handoff),blockers:Fi(t.blockers,"Native blockers",Nj),verification:t.verification===null?null:kj(t.verification),history:a,history_overflow:Ej(t.history_overflow),verification_result:Qe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Qe(t.verification_report,["verification.md"],"Native verification_report"),archived:Ra(t.archived,"Native archived"),created_at:xa(t.created_at,"Native created_at")};return Pj(o),Rj(o),o}function RN(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return X({schema:In,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:ru(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ei(e,t){let i=X(e),r=PN(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.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 X({...i,history:n,history_overflow:a})}function xj(e,t){let i=(0,ou.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Zt(e){let t=await cj.readFile(e,"utf8");return X(xj(t,"Native portable state"))}async function bs(e,t,i={}){let r=X(t);await we(e,(0,ou.stringify)(r),i)}var nu=new Map;async function Cj(e,t){let i=nu.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);nu.set(e,a),await i;try{return await t()}finally{r(),nu.get(e)===a&&nu.delete(e)}}async function $n(e){return Cj(e.file,async()=>{let t=Re(e.expectedStateVersion,"Native expected state version",1),i=X(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Zt(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new au(t,r.state_version);return await bs(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Zt(e.file);if(n.state_version!==t)throw new au(t,n.state_version)}}),i})}function Aj(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ue(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(Aj(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var $e="comet.native.v3",Oe="comet.native.v2",vt="comet.native.v1",Fr="comet.native.transition.v3",sr="comet.native.transition.v2",On="comet.native.transition.v1";var cu="comet.native.portable-migration.v1",Tj=new Set(["schema","id","change","fromSchema","status","createdAt"]),Ij=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jj=/^[a-z0-9][a-z0-9-]{7,127}$/u,$j=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Oj=new Set([vt,Oe,$e]);function Hj(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Dj(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function Fj(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Mj(e){return e.schema===vt?Hn(e):e.schema===Oe?Mi(e):_t(e)}function Bj(e){return _j.posix.normalize(e.replaceAll("\\","/"))}function Lj(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:Bj(t.source)})}function qj(e){return e==="shape"?"shape":"build"}function Vj(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Wj(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function xN(e){let t=Mj(e.state);SN(e.acceptance);let i=qj(t.phase),r=i==="shape"?0:1,n=Dj(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 X({schema:In,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:Lj(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:Vj(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:ue(Wj(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:ru(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function op(e){let t=Hj(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!Tj.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==cu)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!jj.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Ij.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Oj.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!$j.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:cu,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Fj(t.createdAt,"Native portable migration transaction createdAt")}}function CN(e){switch(op(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 lu="comet.native.archive-transaction.v4",AN="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Jj=new RegExp(`^portable-archive-(${AN})\\.json$`,"u"),Gj=new RegExp(`^portable-migration-(${AN})\\.json$`,"u"),Uj=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Kj=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Yj=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Xj=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Qj=new Set(["capability","operation","source","content"]),_N=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function TN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function IN(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function Zj(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=TN(e,i);if(IN(r,Qj,i),typeof r.capability!="string"||!_N.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function e$(e){let t=TN(e,"Native portable Archive transaction");if(IN(t,Xj,"Native portable Archive transaction"),t.schema!==lu)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Uj.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!_N.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"||!Kj.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"||!Yj.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 i=t.spec_changes.map(Zj);if(new Set(i.map(({capability:n})=>n)).size!==i.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)>i.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 r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:lu,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:i,created_at:t.created_at}}function Dn(e){let t=Jj.exec(e);if(t)return{kind:"archive",change:t[1]};let i=Gj.exec(e);return i?{kind:"migration",change:i[1]}:null}function Mr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Dn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return sp.join(e.transactionsDir,i)}async function ks(e,t){let i=Dn(t);if(!i)return null;let r=await ne({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=sp.join(e.transactionsDir,t);if(i.kind==="archive"){let s=e$(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=op(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function Ca(e,t){let i=Mr(e,t);try{return await ks(e,sp.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function jN(e){let t;try{t=await zj.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Dn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function $N(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Ss}from"fs";import ti from"path";import{TextDecoder as a$}from"util";import{createHash as t$}from"node:crypto";import{constants as uu,promises as G}from"node:fs";import ie from"node:path";import{TextDecoder as i$}from"node:util";function st(e,t){let i=ie.relative(e,t);return i===""||!ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ie.sep}`)}function ON(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function _a(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function HN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Aa(e,t){return L({...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 Br(e,t){let i=await G.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await G.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Lr(e,t,i){let r=ie.resolve(e),n=ie.resolve(t);if(!st(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Br(r,i)],o=r;for(let s of ie.relative(r,n).split(ie.sep).filter(Boolean)){await Te(a,i),o=ie.join(o,s);let c=await Br(o,i);if(!st(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Te(a,i),a}async function Te(e,t){for(let i of e){let r=await G.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!_a(i,r)||await G.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function r$(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ve(e){let t=ON(e.maxBytes),i=ie.resolve(e.file),r=await Lr(e.root,ie.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Br(ie.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Te(r,e.label);let a=await G.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=HN(a),s=await G.realpath(i);if(!st(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>st(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?uu.O_RDONLY:uu.O_RDONLY|uu.O_NOFOLLOW|uu.O_NONBLOCK,l=await G.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([G.lstat(i),G.realpath(i)]);if(await Te(r,e.label),await Te(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Aa(o,u)||!Aa(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await r$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([l.stat(),G.lstat(i),G.realpath(i)]);if(await Te(r,e.label),await Te(n,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Aa(o,m)||!Aa(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:t$("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function du(e){let t=await ve(e),i;try{i=new i$("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function Tt(e){let t=await Lr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await G.readdir(e.directory,{withFileTypes:!0});else{let r=ON(e.maxEntries);i=[];let n=await G.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Te(t,e.label),{entries:i,verify:()=>Te(t,e.label)}}async function Lt(e){let t=await Lr(e.root,e.directory,e.label);return{verify:()=>Te(t,e.label)}}async function n$(e){let t=ie.resolve(e.directory),i=ie.resolve(e.quarantine);if(ie.dirname(i)!==ie.dirname(t)||!st(ie.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await Lr(e.root,ie.dirname(t),e.label),n=await Br(t,e.label);if(!st(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await Te(r,e.label);let a=await G.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!_a(n,a)||await G.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await G.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await G.rename(t,i),await Te(r,e.label);let o=await G.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!_a(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await G.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function DN(e){await n$(e)}async function fu(e){let t=ie.resolve(e.file),i=await Lr(e.root,ie.dirname(t),e.label),r=await G.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=HN(r),a=await G.realpath(t);if(!st(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ve({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([G.lstat(t),G.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Aa(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await Te(i,e.label);let[l,u]=await Promise.all([G.lstat(t),G.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Aa(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await G.rm(t),await Te(i,e.label)}async function cp(e){let t=ie.resolve(e.directory),i=await Lr(e.root,ie.dirname(t),e.label),r=await Br(t,e.label);if(!st(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await Te(i,e.label);let n=await G.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!_a(r,n)||await G.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await G.rmdir(t),await Te(i,e.label)}async function Bi(e){let t=ie.resolve(e.root),i=ie.resolve(e.directory);if(!st(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await Br(t,e.label)],n=t;for(let a of ie.relative(t,i).split(ie.sep).filter(Boolean)){await Te(r,e.label),n=ie.join(n,a);try{await G.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Br(n,e.label);if(!st(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await Te(r,e.label)}async function lp(e){let t=ie.resolve(e.root),i=ie.resolve(e.source),r=ie.resolve(e.target);if(i===r||!st(t,i)||!st(t,r)||st(i,r)||st(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Bi({root:t,directory:ie.dirname(r),label:`${e.label} target parent`});let n=await Lr(t,ie.dirname(i),e.label),a=await Lr(t,ie.dirname(r),e.label),o=await Br(i,e.label);if(!st(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await G.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([Te(n,e.label),Te(a,e.label)]);let s=await G.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!_a(o,s)||await G.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await G.rename(i,r),await Promise.all([Te(n,e.label),Te(a,e.label)]);let c=await G.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!_a(o,c)||!st(n[0].realPath,await G.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await G.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function qr(e){let t=await ve({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Uv(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await G.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ve({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ve({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var o$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),s$=new Set(["id","type","source","target","staged","backup"]),c$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),l$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),u$=new Set(["sequence","timestamp","type","operationId"]),LN=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),qN=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),d$=256*1024,f$=1024*1024,VN=16*1024,pu=1024,fp=64*1024*1024,h$=2e4,WN=new a$("utf-8",{fatal:!0});function Es(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ps(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ia(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function up(e,t){if(typeof e!="string"||e.length===0||ti.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function hu(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function FN(e,t){if(up(e,t),e.includes("\\")||e!==ti.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 p$(e,t){let i=Es(e,`transaction operations[${t}]`);if(Ps(i,s$,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);up(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&up(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function vu(e){let t=Es(e,"Native Archive transaction journal");if(Ps(t,c$,"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"||!LN.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(!Ia(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(hu(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 i=t.operations.map((s,c)=>{let l=Es(s,`Archive transaction operations[${c}]`);if(Ps(l,l$,`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`);FN(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&FN(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&hu(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(hu(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`);hu(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.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)||i.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 i.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:i}}function hp(e){let t=Es(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return vu(t);if(Ps(t,o$,"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"||!LN.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ti.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ti.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(!Ia(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 i=t.operations.map(p$),r=i.map(n=>n.id);if(new Set(r).size!==r.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:i}}function zN(e,t){let i=Es(e,`Native transaction event at line ${t}`);if(Ps(i,u$,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Ia(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!qN.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function m$(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Ia(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Ia(e)}function Ta(e,t){return e.length<t.length&&t.startsWith(e)}function v$(e){let t='","operationId":"';if(Ta(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Ta(i.slice(r),'"}'):!1}function g$(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>VN)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Ta(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!m$(n))return!1;if(r.length<24)return!0;if(!Ia(n))return!1;let a='","type":"',o=r.slice(24);if(Ta(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of qN){if(Ta(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(v$(l))return!0}else if(Ta(l,'"}'))return!0}return!1}function w$(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>VN)throw new Error(`Native transaction event at line ${t} is too large`);return zN(JSON.parse(e),t)}function y$(e){let t=e.split(`
|
|
172
|
-
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>
|
|
168
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=pp(l,t);else if(i)$N(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=pp(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!$N(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function Ej(e){return[...ja(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Ss(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Pj(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function vp(e,t,i,r=[],n="content-hash"){let a=Ss(i),o=t.replaceAll("\\","/").trim(),s=r.map(Ss);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${D(mj,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function gp(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function Rj(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of ja(e)){n=s+1;let c=o?mp(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function fu(e,t="brief.md",i=Es.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=Rj(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of ja(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of ja(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),gp(o.map(l=>vp("brief-example",t,l.join(`
|
|
169
|
+
`),[],r)),"Brief",r)}function hu(e,t="spec.md",i=Es.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(vp("spec-scenario",t,[o.title,...o.body].join(`
|
|
170
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of ja(e)){let u=l?mp(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=Ss(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(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(),gp(n,"Specification",r)}function pu(e,t="spec.md",i=Es.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(vp("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of ja(e)){let f=d?mp(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let h=u.trim();if(!d||o!==null||l()){c();continue}if(h.length===0||pp(u,null)!==null||h.startsWith("<!--")||h==="-->"||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(p=>p.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(p=>p.text)},c();continue}s===null?s={parts:[h],context:a.map(p=>p.text)}:s.parts.push(h)}return c(),gp(n,"Specification mandatory requirements",r)}function Cj(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||Pj(i)||AN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=AN.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!wj.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function xj(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!gj.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function HN(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=xj(i,r),a=n.acceptance_id;if(typeof a!="string"||!vj.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return Cj(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function DN(e){let t=Ej(e);if(t.some(({line:l,body:u})=>!u&&(l===_N||l===TN)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===_N?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===TN?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
|
|
171
|
+
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=HN(o),c=Aj(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function Aj(e){let t=HN([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var _j=/^A[1-9]\d*$/u;function MN(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||FN.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||FN.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Tj(e,t){return e.localeCompare(t,"en")}function mu(e){let t=MN(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>Tj(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=fu(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=MN(a.source,`Native spec source for ${a.capability}`);r.push(...hu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...pu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Ss(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function BN(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!_j.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function LN(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var yu=ma(_n(),1);import{promises as Ij}from"node:fs";var Fn="comet.native.v4",Ps="comet.native.local-execution.v4";function vu(){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 jj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$j=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Oj=/^A[1-9][0-9]*$/u,Hj=/^[a-f0-9]{64}$/u,Dj=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),wu=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Tt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function It(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ze(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function yp(e,t){return e===null?null:Ze(e,t)}function Fj(e,t){let i=Ze(e,t);if(!Hj.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function $a(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function xe(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Mj(e,t){return e===null?null:xe(e,t,Number.MIN_SAFE_INTEGER)}function Qe(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function qi(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Nu(e,t){return qi(e,t,(i,r)=>Ze(i,`${t}[${r}]`))}function Mn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Oa(e,t){let i=Ze(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Np(e,t,i=!1){let r=Ze(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Ei(e,t){let i=Tt(e,t);return It(i,new Set(["text","truncated"]),t),{text:Ze(i.text,`${t}.text`,{empty:!0}),truncated:$a(i.truncated,`${t}.truncated`)}}function Bj(e,t){let i=`Native spec_changes[${t}]`,r=Tt(e,i);It(r,new Set(["capability","operation","source"]),i);let n=Ze(r.capability,`${i}.capability`);if(!$j.test(n))throw new Error(`${i}.capability is invalid`);let a=Qe(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Np(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function Lj(e){let t="Native workspace",i=Tt(e,t);It(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Qe(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=yp(i.change_branch,`${t}.change_branch`),a=yp(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Qe(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function qj(e){let t="Native loop",i=Tt(e,t);It(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Nu(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Mn(r,`${t}.previous_unresolved_ids`),{stage:Qe(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:xe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:xe(i.iteration,`${t}.iteration`),attempt:xe(i.attempt,`${t}.attempt`),retry_epoch:xe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:xe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:xe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:xe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:yp(i.next_action,`${t}.next_action`)}}function Vj(e,t){let i=`Native acceptance[${t}]`,r=Tt(e,i);It(r,new Set(["id","source","text","result","reason"]),i);let n=Ze(r.id,`${i}.id`);if(!Oj.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Np(r.source,`${i}.source`),text:Ze(r.text,`${i}.text`),result:Qe(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ei(r.reason,`${i}.reason`)}}function Wj(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Tt(e,i);return It(r,new Set(["name","result","note"]),i),{name:Ei(r.name,`${i}.name`),result:Qe(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ei(r.note,`${i}.note`)}}function zj(e){let t="Native builder_handoff",i=Tt(e,t);It(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),t);let r=Nu(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Mn(r,`${t}.addressed_acceptance_ids`),{candidate_id:Ze(i.candidate_id,`${t}.candidate_id`),identity_provider:Ze(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Ze(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:xe(i.iteration,`${t}.iteration`,1),summary:Ei(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:qi(i.checks,`${t}.checks`,Wj),checks_truncated:$a(i.checks_truncated,`${t}.checks_truncated`),known_limits:qi(i.known_limits,`${t}.known_limits`,(n,a)=>Ei(n,`${t}.known_limits[${a}]`)),known_limits_truncated:$a(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Oa(i.submitted_at,`${t}.submitted_at`)}}function Jj(e,t){let i=`Native blockers[${t}]`,r=Tt(e,i);It(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Nu(r.acceptance_ids,`${i}.acceptance_ids`);return Mn(n,`${i}.acceptance_ids`),{owner:Qe(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ei(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Qe(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Gj(e,t){let i=`Native verification.checks[${t}]`,r=Tt(e,i);return It(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Ze(r.id,`${i}.id`),name:Ei(r.name,`${i}.name`),argv_display:qi(r.argv_display,`${i}.argv_display`,(n,a)=>Ei(n,`${i}.argv_display[${a}]`)),argv_truncated:$a(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Np(r.cwd_ref,`${i}.cwd_ref`,!0),status:Qe(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Mj(r.exit_code,`${i}.exit_code`),duration_ms:xe(r.duration_ms,`${i}.duration_ms`)}}function Uj(e){let t="Native verification",i=Tt(e,t);It(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=qi(i.checks,`${t}.checks`,Gj);Mn(r.map(a=>a.id),`${t}.checks IDs`);let n=Ze(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Ze(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Ze(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:xe(i.iteration,`${t}.iteration`,1),attempt:xe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Qe(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Qe(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Ei(i.summary,`${t}.summary`),risks:qi(i.risks,`${t}.risks`,(a,o)=>Ei(a,`${t}.risks[${o}]`)),risks_truncated:$a(i.risks_truncated,`${t}.risks_truncated`),completed_at:Oa(i.completed_at,`${t}.completed_at`)}}function qN(e,t){let i=`Native history[${t}]`,r=Tt(e,i);It(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Nu(r.unresolved_ids,`${i}.unresolved_ids`);return Mn(n,`${i}.unresolved_ids`),{goal_cycle:xe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:xe(r.iteration,`${i}.iteration`),attempt:xe(r.attempt,`${i}.attempt`),outcome:Qe(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Ei(r.summary,`${i}.summary`),completed_at:Oa(r.completed_at,`${i}.completed_at`)}}function Kj(e){let t="Native history_overflow.outcome_counts",i=Tt(e,t),r=["pass","fail","blocked","execution-error","recovery"];return It(i,new Set(r),t),{pass:xe(i.pass,`${t}.pass`),fail:xe(i.fail,`${t}.fail`),blocked:xe(i.blocked,`${t}.blocked`),"execution-error":xe(i["execution-error"],`${t}.execution-error`),recovery:xe(i.recovery,`${t}.recovery`)}}function Yj(e){let t="Native history_overflow",i=Tt(e,t);It(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=xe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Oa(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Oa(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Kj(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Xj(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(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.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 r=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(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Qj(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 i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);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(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.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 X(e){let t=Tt(e,"Native portable state");if(It(t,Dj,"Native portable state"),t.schema!==Fn)throw new Error(`Native portable state schema must be ${Fn}`);let i=Ze(t.name,"Native state name");if(!jj.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=qi(t.spec_changes,"Native spec_changes",Bj);Mn(r.map(s=>s.capability),"Native spec change capabilities");let n=qi(t.acceptance,"Native acceptance",Vj);Mn(n.map(s=>s.id),"Native acceptance IDs");let a=qi(t.history,"Native history",qN);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Fn,name:i,language:Qe(t.language,["en","zh-CN"],"Native state language"),phase:Qe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Qe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:xe(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Fj(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:Lj(t.workspace),loop:qj(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:zj(t.builder_handoff),blockers:qi(t.blockers,"Native blockers",Jj),verification:t.verification===null?null:Uj(t.verification),history:a,history_overflow:Yj(t.history_overflow),verification_result:Qe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Qe(t.verification_report,["verification.md"],"Native verification_report"),archived:$a(t.archived,"Native archived"),created_at:Oa(t.created_at,"Native created_at")};return Xj(o),Qj(o),o}function VN(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return X({schema:Fn,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:vu(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ri(e,t){let i=X(e),r=qN(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.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 X({...i,history:n,history_overflow:a})}function Zj(e,t){let i=(0,yu.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function wt(e){let t=await Ij.readFile(e,"utf8");return X(Zj(t,"Native portable state"))}async function Rs(e,t,i={}){let r=X(t);await Ne(e,(0,yu.stringify)(r),i)}var gu=new Map;async function e$(e,t){let i=gu.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);gu.set(e,a),await i;try{return await t()}finally{r(),gu.get(e)===a&&gu.delete(e)}}async function Bn(e){return e$(e.file,async()=>{let t=xe(e.expectedStateVersion,"Native expected state version",1),i=X(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await wt(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new wu(t,r.state_version);return await Rs(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await wt(e.file);if(n.state_version!==t)throw new wu(t,n.state_version)}}),i})}function t$(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ue(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(t$(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var $e="comet.native.v3",Oe="comet.native.v2",yt="comet.native.v1",qr="comet.native.transition.v3",dr="comet.native.transition.v2",Ln="comet.native.transition.v1";var bu="comet.native.portable-migration.v1",r$=new Set(["schema","id","change","fromSchema","status","createdAt"]),n$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,a$=/^[a-z0-9][a-z0-9-]{7,127}$/u,o$=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),s$=new Set([yt,Oe,$e]);function c$(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function l$(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function u$(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function d$(e){return e.schema===yt?qn(e):e.schema===Oe?Vi(e):jt(e)}function f$(e){return i$.posix.normalize(e.replaceAll("\\","/"))}function h$(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:f$(t.source)})}function p$(e){return e==="shape"?"shape":"build"}function m$(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function v$(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function WN(e){let t=d$(e.state);BN(e.acceptance);let i=p$(t.phase),r=i==="shape"?0:1,n=l$(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 X({schema:Fn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:h$(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:m$(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:ue(v$(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:vu(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function bp(e){let t=c$(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!r$.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==bu)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!a$.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!n$.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!s$.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!o$.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:bu,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:u$(t.createdAt,"Native portable migration transaction createdAt")}}function zN(e){switch(bp(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 ku="comet.native.archive-transaction.v4",JN="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",w$=new RegExp(`^portable-archive-(${JN})\\.json$`,"u"),y$=new RegExp(`^portable-migration-(${JN})\\.json$`,"u"),N$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,b$=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,k$=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),S$=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),E$=new Set(["capability","operation","source","content"]),GN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function UN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function KN(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function P$(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=UN(e,i);if(KN(r,E$,i),typeof r.capability!="string"||!GN.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function R$(e){let t=UN(e,"Native portable Archive transaction");if(KN(t,S$,"Native portable Archive transaction"),t.schema!==ku)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!N$.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!GN.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"||!b$.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"||!k$.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 i=t.spec_changes.map(P$);if(new Set(i.map(({capability:n})=>n)).size!==i.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)>i.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 r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:ku,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:i,created_at:t.created_at}}function Vn(e){let t=w$.exec(e);if(t)return{kind:"archive",change:t[1]};let i=y$.exec(e);return i?{kind:"migration",change:i[1]}:null}function Vr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Vn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return kp.join(e.transactionsDir,i)}async function Cs(e,t){let i=Vn(t);if(!i)return null;let r=await ee({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=kp.join(e.transactionsDir,t);if(i.kind==="archive"){let s=R$(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=bp(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function Ha(e,t){let i=Vr(e,t);try{return await Cs(e,kp.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function YN(e){let t;try{t=await g$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Vn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function XN(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as xs}from"fs";import ni from"path";import{TextDecoder as T$}from"util";import{createHash as C$}from"node:crypto";import{constants as Su,promises as U}from"node:fs";import ne from"node:path";import{TextDecoder as x$}from"node:util";function st(e,t){let i=ne.relative(e,t);return i===""||!ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ne.sep}`)}function QN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Fa(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ZN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Da(e,t){return q({...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 Wr(e,t){let i=await U.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await U.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function zr(e,t,i){let r=ne.resolve(e),n=ne.resolve(t);if(!st(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Wr(r,i)],o=r;for(let s of ne.relative(r,n).split(ne.sep).filter(Boolean)){await Ie(a,i),o=ne.join(o,s);let c=await Wr(o,i);if(!st(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ie(a,i),a}async function Ie(e,t){for(let i of e){let r=await U.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Fa(i,r)||await U.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function A$(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ge(e){let t=QN(e.maxBytes),i=ne.resolve(e.file),r=await zr(e.root,ne.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Wr(ne.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ie(r,e.label);let a=await U.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=ZN(a),s=await U.realpath(i);if(!st(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>st(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Su.O_RDONLY:Su.O_RDONLY|Su.O_NOFOLLOW|Su.O_NONBLOCK,l=await U.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([U.lstat(i),U.realpath(i)]);if(await Ie(r,e.label),await Ie(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Da(o,u)||!Da(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await A$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([l.stat(),U.lstat(i),U.realpath(i)]);if(await Ie(r,e.label),await Ie(n,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Da(o,m)||!Da(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:C$("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Eu(e){let t=await ge(e),i;try{i=new x$("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function $t(e){let t=await zr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await U.readdir(e.directory,{withFileTypes:!0});else{let r=QN(e.maxEntries);i=[];let n=await U.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Ie(t,e.label),{entries:i,verify:()=>Ie(t,e.label)}}async function Wt(e){let t=await zr(e.root,e.directory,e.label);return{verify:()=>Ie(t,e.label)}}async function _$(e){let t=ne.resolve(e.directory),i=ne.resolve(e.quarantine);if(ne.dirname(i)!==ne.dirname(t)||!st(ne.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await zr(e.root,ne.dirname(t),e.label),n=await Wr(t,e.label);if(!st(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await Ie(r,e.label);let a=await U.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Fa(n,a)||await U.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await U.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await U.rename(t,i),await Ie(r,e.label);let o=await U.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Fa(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await U.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function eb(e){await _$(e)}async function Pu(e){let t=ne.resolve(e.file),i=await zr(e.root,ne.dirname(t),e.label),r=await U.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=ZN(r),a=await U.realpath(t);if(!st(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ge({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([U.lstat(t),U.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Da(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await Ie(i,e.label);let[l,u]=await Promise.all([U.lstat(t),U.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Da(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await U.rm(t),await Ie(i,e.label)}async function Sp(e){let t=ne.resolve(e.directory),i=await zr(e.root,ne.dirname(t),e.label),r=await Wr(t,e.label);if(!st(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await Ie(i,e.label);let n=await U.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Fa(r,n)||await U.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await U.rmdir(t),await Ie(i,e.label)}async function Wi(e){let t=ne.resolve(e.root),i=ne.resolve(e.directory);if(!st(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await Wr(t,e.label)],n=t;for(let a of ne.relative(t,i).split(ne.sep).filter(Boolean)){await Ie(r,e.label),n=ne.join(n,a);try{await U.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Wr(n,e.label);if(!st(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await Ie(r,e.label)}async function Ep(e){let t=ne.resolve(e.root),i=ne.resolve(e.source),r=ne.resolve(e.target);if(i===r||!st(t,i)||!st(t,r)||st(i,r)||st(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Wi({root:t,directory:ne.dirname(r),label:`${e.label} target parent`});let n=await zr(t,ne.dirname(i),e.label),a=await zr(t,ne.dirname(r),e.label),o=await Wr(i,e.label);if(!st(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await U.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([Ie(n,e.label),Ie(a,e.label)]);let s=await U.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Fa(o,s)||await U.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await U.rename(i,r),await Promise.all([Ie(n,e.label),Ie(a,e.label)]);let c=await U.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Fa(o,c)||!st(n[0].realPath,await U.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await U.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Jr(e){let t=await ge({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await dg(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await U.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ge({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ge({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var I$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),j$=new Set(["id","type","source","target","staged","backup"]),$$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),O$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),H$=new Set(["sequence","timestamp","type","operationId"]),nb=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),ab=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),D$=256*1024,F$=1024*1024,ob=16*1024,Cu=1024,Cp=64*1024*1024,M$=2e4,sb=new T$("utf-8",{fatal:!0});function As(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _s(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ba(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Pp(e,t){if(typeof e!="string"||e.length===0||ni.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ru(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function tb(e,t){if(Pp(e,t),e.includes("\\")||e!==ni.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 B$(e,t){let i=As(e,`transaction operations[${t}]`);if(_s(i,j$,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Pp(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Pp(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Au(e){let t=As(e,"Native Archive transaction journal");if(_s(t,$$,"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"||!nb.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(!Ba(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ru(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 i=t.operations.map((s,c)=>{let l=As(s,`Archive transaction operations[${c}]`);if(_s(l,O$,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);tb(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&tb(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ru(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(Ru(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`);Ru(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.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)||i.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 i.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:i}}function xp(e){let t=As(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Au(t);if(_s(t,I$,"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"||!nb.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ni.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ni.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(!Ba(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 i=t.operations.map(B$),r=i.map(n=>n.id);if(new Set(r).size!==r.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:i}}function cb(e,t){let i=As(e,`Native transaction event at line ${t}`);if(_s(i,H$,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Ba(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!ab.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function L$(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Ba(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Ba(e)}function Ma(e,t){return e.length<t.length&&t.startsWith(e)}function q$(e){let t='","operationId":"';if(Ma(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Ma(i.slice(r),'"}'):!1}function V$(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>ob)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Ma(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!L$(n))return!1;if(r.length<24)return!0;if(!Ba(n))return!1;let a='","type":"',o=r.slice(24);if(Ma(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of ab){if(Ma(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(q$(l))return!0}else if(Ma(l,'"}'))return!0}return!1}function W$(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>ob)throw new Error(`Native transaction event at line ${t} is too large`);return cb(JSON.parse(e),t)}function z$(e){let t=e.split(`
|
|
172
|
+
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>Cu)throw new Error(`Native transaction event log exceeds ${Cu} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push(W$(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&V$(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function lb(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
173
173
|
`)}
|
|
174
|
-
`}function N$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ti.join(e.transactionsDir,t)}function gu(e,t){let i=N$(e,t);return{directory:i,journal:ti.join(i,"transaction.json"),events:ti.join(i,"events.jsonl"),staged:ti.join(i,"staged"),backups:ti.join(i,"backups")}}async function Li(e,t){let i=gu(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function b$(e,t){if(t.length===0||ti.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=ti.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function Vr(e,t){let i=b$(e,t);return T(j(e,i),i)}async function Fn(e){try{return await Ss.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pp(e,t,i={}){let r=await Li(e,t);try{await Ss.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ve({root:e.runtimeDir,file:r.events,maxBytes:f$,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=WN.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=y$(a),s=JN(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function MN(e,t,i){let r=await pp(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function ii(e,t,i,r){let n=await Li(e,t),a=await pp(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await we(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>MN(e,t,a)}),o;if(a.events.length>=pu)throw new Error(`Native transaction event log ${t} exceeds ${pu} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return zN(s,s.sequence),await Ss.mkdir(n.directory,{recursive:!0}),await we(n.events,JN([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>MN(e,t,a)}),s}async function mp(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=hp(t);let i=await Li(e,t.id);await Ss.mkdir(i.staged,{recursive:!0}),await Ss.mkdir(i.backups,{recursive:!0}),await me(i.journal,t,{containedRoot:e.runtimeDir}),await ii(e,t.id,"prepared")}async function It(e,t,i={}){let r=await Li(e,t),n=await ve({root:e.runtimeDir,file:r.journal,maxBytes:d$,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(WN.decode(n.bytes)),o=hp(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Wr(e,t,i={}){return(await pp(e,t,i)).events}async function mu(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=hp({...t,status:i});return await me((await Li(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function dp(e,t,i){try{return await ve({root:j(e,t),file:t,maxBytes:fp,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function vp(e,t,i,r){let n=await dp(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await dp(e,i,`${r} target`);await Bi({root:j(e,i),directory:ti.dirname(i),label:`${r} target parent`}),await qr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:fp,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function GN(e,t,i){let r=await dp(e,t,i);r&&await fu({root:j(e,t),file:t,maxBytes:fp,expectedHash:r.hash,expectedSize:r.size,label:i})}async function BN(e,t){if(!t.backup)return;let i=await Vr(e,t.target),r=await Vr(e,t.backup);!await Fn(i)||await Fn(r)||await vp(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function k$(e,t){let i=await Vr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await BN(e,t),await vp(e,await Vr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await BN(e,t),await GN(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await Vr(e,t.source),[n,a]=await Promise.all([Fn(r),Fn(i)]);if(!n&&a){await(await Tt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:h$})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await lp({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function UN(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await mu(e,t,"applying"):t,n=await Wr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await ii(e,r.id,"operation-started",s.id),await k$(e,s),await ii(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await It(e,r.id),r}async function S$(e,t){let i=await Vr(e,t.target),r=t.backup?await Vr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await Vr(e,t.source);if(await Fn(i)){if(await Fn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await lp({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Fn(r)?await vp(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await GN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function wu(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await Wr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await mu(e,t,"rolling-back");await ii(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await S$(e,a);return await ii(e,r.id,"rollback-completed"),r=await mu(e,r,"rolled-back"),r}async function ja(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await ii(e,t.id,i),i==="commit"?mu(e,t,"committed"):t}async function R$(e,t,i){let r;try{r=await E$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await It(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Dn(n.name))try{let a=await ks(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if($N(a))return!0}catch{return!0}return!1}async function x$(e,t){let i=Date.now()+5e3,r=P$.join(e.locksDir,"root-move.lock");for(;;)try{return await nr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await vs(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function F(e,t,i,r){let n=await x$(e,t);try{if(await Ea(e.projectRoot),await R$(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await ar(n)}}function KN(e){return Number.isSafeInteger(e)&&e>=1}async function YN(e){if(!KN(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!KN(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Su}from"crypto";import{spawn as ob}from"node:child_process";import{promises as ye}from"fs";import W from"path";import{createHash as XN}from"crypto";import{createReadStream as C$}from"fs";async function ri(e){let t=XN("sha256");for await(let i of C$(e))t.update(i);return t.digest("hex")}function B(e){return XN("sha256").update(e).digest("hex")}var yu={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},kp=1e3,A$=8*1024*1024,_$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,T$=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),I$=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),j$=new Set(["schema","include","exclude","hash"]),$$=new Set(["provider","gitSelection","physicalSelection","projection"]),O$=new Set(["provider","selection"]),H$=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),D$=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),F$=new Set(["schema","status","before","after"]),M$=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),B$=new Set(["path","hash","size","type","gitObjectId"]),L$=new Set(["path","size","type","reason"]),q$=new Set(["ref","hash","count"]),V$=new Set(["change-created","legacy-migration","explicit"]),W$=new Set(["file","directory","other"]),z$=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"]),Eu=/^[a-f0-9]{64}$/u,sb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,J$=new Set(["EACCES","EPERM"]),Fa=64*1024,Np=64*1024,G$=6e4,U$=1e3,K$=2,Sp={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Y$={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function cb(e){let t=e.deadlineMs??G$;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function bi(e){return Math.max(0,e.deadlineAt-Date.now())}function q(e){return bi(e)>=1}function gp(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Ha(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function X$(e){let t={...Y$,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function Q$(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&W.win32.isAbsolute(r)?W.win32.resolve(r):"C:\\Windows",a=W.win32.join(n,"System32","taskkill.exe");if(!W.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=ob(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),U$),u.unref()}catch{d(!1)}});for(let s=0;s<K$;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Ep(e,t,i,r){let n=bi(e);if(n<1)throw gp();let a=e.gitProcess,o=ob(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=Q$(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?gp(m.error):gp()}return{code:h,spawnError:s}});return{child:o,completion:f}}function lb(e){let t={...Sp,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Nu(e,t,i,r=Np){let{child:n,completion:a}=Ep(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let m=Math.max(0,r-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=Fa)return;let m=Fa-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function wp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function xs(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Ep(e,t,i,r.stdin!==void 0),c=[],l=Su("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),v=!1,N=!1,y=!1,S=E=>{let k=0;for(;k<E.byteLength;){let b=E.indexOf(0,k),R=b<0?E.byteLength:b,w=E.subarray(k,R);if(!v&&w.byteLength>0&&(p.byteLength+w.byteLength>r.maxRecordBytes?(p=Buffer.alloc(0),v=!0,N=!0):p=Buffer.concat([p,w])),b<0)break;m+=1,p.byteLength===0&&!v&&(y=!0);let g=p.byteLength+1;!v&&m<=r.maxRecords&&h+g<=r.maxBytes?(c.push(p),h+=g):N=!0,p=Buffer.alloc(0),v=!1,k=b+1}};o.stdout.on("data",E=>{l.update(E),f+=E.byteLength,f>r.maxBytes&&(N=!0);let k=r.outputChunkBytes;if(k===void 0){S(E);return}for(let b=0;b<E.byteLength;b+=k)S(E.subarray(b,Math.min(E.byteLength,b+k)))}),o.stderr.on("data",E=>{if(d>=Fa)return;let k=Fa-d,b=Buffer.from(E).subarray(0,k);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:E,spawnError:k})=>{let b=r.acceptedExitCodes??[0];if(E!==null&&b.includes(E)&&k===null&&!y&&p.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:N,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||p.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function bu(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function Z$(e,t,i){if(i.length===0)return new Set;let r=await xs(e,t,["check-ignore","--no-index","-z","--stdin"],{...Sp,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=bu(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function eO(e,t,i){let{child:r,completion:n}=Ep(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Fa)return;let d=Fa-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Da(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||W.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||W.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function tO(e,t){return e.map(i=>{let r=Da(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function iO(e){let t=W.resolve(e);for(;;){try{return await ye.lstat(W.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=W.dirname(t);if(i===t)return!1;t=i}}async function ub(e,t,i,r={}){let n=W.resolve(t.projectRoot),a=W.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=W.relative(n,W.resolve(f)).replaceAll("\\","/"),m=Da(h);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await xs(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await xs(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await xs(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function db(e){return{stageBefore:wp(e.stagedBefore),combined:wp(e.combined),stageAfter:wp(e.stagedAfter)}}async function fb(e,t,i=Sp,r={}){let n=W.resolve(t.projectRoot);if(!await iO(n))return null;let a;try{a=await Nu(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Ha(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await ub(e,t,i,r)}catch(y){throw Ha(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=y=>{for(let S of y){let E=bu(S),k=E.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(E.slice(0,k))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=Da(E.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),b.stage==="0"&&d.set(R,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let m=c.records.map(bu),p=tO(m,"combined"),v=new Set(p.filter(y=>!u.has(y))),N=new Set(p.filter((y,S)=>!u.has(y)&&m[S].endsWith("/")));for(let y of f)N.delete(y);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:N,omissions:[],overflow:null,evidence:null,initialFence:db(o)}}function Jr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function QN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function rO(e,t){return!Jr(e.stageBefore,e.stageAfter)||!Jr(e.stageAfter,t.stageBefore)||!Jr(e.combined,t.combined)||!Jr(t.stageBefore,t.stageAfter)}async function hb(e,t,i,r,n){let a;try{a=await ub(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Ha(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=db(a),c=QN(o)||QN(s),l=rO(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:B(`comet.native.git-selection-overflow.v2
|
|
175
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var
|
|
174
|
+
`}function J$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ni.join(e.transactionsDir,t)}function _u(e,t){let i=J$(e,t);return{directory:i,journal:ni.join(i,"transaction.json"),events:ni.join(i,"events.jsonl"),staged:ni.join(i,"staged"),backups:ni.join(i,"backups")}}async function zi(e,t){let i=_u(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function G$(e,t){if(t.length===0||ni.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=ni.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function Gr(e,t){let i=G$(e,t);return T(j(e,i),i)}async function Wn(e){try{return await xs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ap(e,t,i={}){let r=await zi(e,t);try{await xs.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ge({root:e.runtimeDir,file:r.events,maxBytes:F$,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=sb.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=z$(a),s=lb(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function ib(e,t,i){let r=await Ap(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function ai(e,t,i,r){let n=await zi(e,t),a=await Ap(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await Ne(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>ib(e,t,a)}),o;if(a.events.length>=Cu)throw new Error(`Native transaction event log ${t} exceeds ${Cu} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return cb(s,s.sequence),await xs.mkdir(n.directory,{recursive:!0}),await Ne(n.events,lb([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>ib(e,t,a)}),s}async function _p(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=xp(t);let i=await zi(e,t.id);await xs.mkdir(i.staged,{recursive:!0}),await xs.mkdir(i.backups,{recursive:!0}),await ve(i.journal,t,{containedRoot:e.runtimeDir}),await ai(e,t.id,"prepared")}async function Ot(e,t,i={}){let r=await zi(e,t),n=await ge({root:e.runtimeDir,file:r.journal,maxBytes:D$,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(sb.decode(n.bytes)),o=xp(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Ur(e,t,i={}){return(await Ap(e,t,i)).events}async function xu(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=xp({...t,status:i});return await ve((await zi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function Rp(e,t,i){try{return await ge({root:j(e,t),file:t,maxBytes:Cp,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Tp(e,t,i,r){let n=await Rp(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await Rp(e,i,`${r} target`);await Wi({root:j(e,i),directory:ni.dirname(i),label:`${r} target parent`}),await Jr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Cp,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function ub(e,t,i){let r=await Rp(e,t,i);r&&await Pu({root:j(e,t),file:t,maxBytes:Cp,expectedHash:r.hash,expectedSize:r.size,label:i})}async function rb(e,t){if(!t.backup)return;let i=await Gr(e,t.target),r=await Gr(e,t.backup);!await Wn(i)||await Wn(r)||await Tp(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function U$(e,t){let i=await Gr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await rb(e,t),await Tp(e,await Gr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await rb(e,t),await ub(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await Gr(e,t.source),[n,a]=await Promise.all([Wn(r),Wn(i)]);if(!n&&a){await(await $t({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:M$})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Ep({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function db(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await xu(e,t,"applying"):t,n=await Ur(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await ai(e,r.id,"operation-started",s.id),await U$(e,s),await ai(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await Ot(e,r.id),r}async function K$(e,t){let i=await Gr(e,t.target),r=t.backup?await Gr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await Gr(e,t.source);if(await Wn(i)){if(await Wn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Ep({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Wn(r)?await Tp(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await ub(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Tu(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await Ur(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await xu(e,t,"rolling-back");await ai(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await K$(e,a);return await ai(e,r.id,"rollback-completed"),r=await xu(e,r,"rolled-back"),r}async function La(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await ai(e,t.id,i),i==="commit"?xu(e,t,"committed"):t}async function Q$(e,t,i){let r;try{r=await Y$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Ot(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Vn(n.name))try{let a=await Cs(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(XN(a))return!0}catch{return!0}return!1}async function Z$(e,t){let i=Date.now()+5e3,r=X$.join(e.locksDir,"root-move.lock");for(;;)try{return await cr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await bs(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function F(e,t,i,r){let n=await Z$(e,t);try{if(await Ia(e.projectRoot),await Q$(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await lr(n)}}function fb(e){return Number.isSafeInteger(e)&&e>=1}async function hb(e){if(!fb(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!fb(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Hu}from"crypto";import{spawn as Sb}from"node:child_process";import{promises as be}from"fs";import J from"path";import{createHash as pb}from"crypto";import{createReadStream as eO}from"fs";async function oi(e){let t=pb("sha256");for await(let i of eO(e))t.update(i);return t.digest("hex")}function B(e){return pb("sha256").update(e).digest("hex")}var Iu={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Dp=1e3,tO=8*1024*1024,iO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rO=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),nO=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),aO=new Set(["schema","include","exclude","hash"]),oO=new Set(["provider","gitSelection","physicalSelection","projection"]),sO=new Set(["provider","selection"]),cO=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),lO=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),uO=new Set(["schema","status","before","after"]),dO=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),fO=new Set(["path","hash","size","type","gitObjectId"]),hO=new Set(["path","size","type","reason"]),pO=new Set(["ref","hash","count"]),mO=new Set(["change-created","legacy-migration","explicit"]),vO=new Set(["file","directory","other"]),gO=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"]),Du=/^[a-f0-9]{64}$/u,Eb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,wO=new Set(["EACCES","EPERM"]),Ja=64*1024,Op=64*1024,yO=6e4,NO=1e3,bO=2,Fp={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},kO={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Pb(e){let t=e.deadlineMs??yO;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Pi(e){return Math.max(0,e.deadlineAt-Date.now())}function V(e){return Pi(e)>=1}function Ip(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Wa(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function SO(e){let t={...kO,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function EO(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&J.win32.isAbsolute(r)?J.win32.resolve(r):"C:\\Windows",a=J.win32.join(n,"System32","taskkill.exe");if(!J.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=Sb(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),NO),u.unref()}catch{d(!1)}});for(let s=0;s<bO;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Mp(e,t,i,r){let n=Pi(e);if(n<1)throw Ip();let a=e.gitProcess,o=Sb(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=EO(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Ip(m.error):Ip()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Rb(e){let t={...Fp,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function ju(e,t,i,r=Op){let{child:n,completion:a}=Mp(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let m=Math.max(0,r-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=Ja)return;let m=Ja-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function jp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Is(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Mp(e,t,i,r.stdin!==void 0),c=[],l=Hu("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),v=!1,g=!1,y=!1,E=S=>{let k=0;for(;k<S.byteLength;){let b=S.indexOf(0,k),R=b<0?S.byteLength:b,N=S.subarray(k,R);if(!v&&N.byteLength>0&&(p.byteLength+N.byteLength>r.maxRecordBytes?(p=Buffer.alloc(0),v=!0,g=!0):p=Buffer.concat([p,N])),b<0)break;m+=1,p.byteLength===0&&!v&&(y=!0);let w=p.byteLength+1;!v&&m<=r.maxRecords&&h+w<=r.maxBytes?(c.push(p),h+=w):g=!0,p=Buffer.alloc(0),v=!1,k=b+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>r.maxBytes&&(g=!0);let k=r.outputChunkBytes;if(k===void 0){E(S);return}for(let b=0;b<S.byteLength;b+=k)E(S.subarray(b,Math.min(S.byteLength,b+k)))}),o.stderr.on("data",S=>{if(d>=Ja)return;let k=Ja-d,b=Buffer.from(S).subarray(0,k);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:k})=>{let b=r.acceptedExitCodes??[0];if(S!==null&&b.includes(S)&&k===null&&!y&&p.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||p.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function $u(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function PO(e,t,i){if(i.length===0)return new Set;let r=await Is(e,t,["check-ignore","--no-index","-z","--stdin"],{...Fp,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=$u(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function RO(e,t,i){let{child:r,completion:n}=Mp(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Ja)return;let d=Ja-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function za(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||J.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||J.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function CO(e,t){return e.map(i=>{let r=za(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function xO(e){let t=J.resolve(e);for(;;){try{return await be.lstat(J.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=J.dirname(t);if(i===t)return!1;t=i}}async function Cb(e,t,i,r={}){let n=J.resolve(t.projectRoot),a=J.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=J.relative(n,J.resolve(f)).replaceAll("\\","/"),m=za(h);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Is(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Is(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Is(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function xb(e){return{stageBefore:jp(e.stagedBefore),combined:jp(e.combined),stageAfter:jp(e.stagedAfter)}}async function Ab(e,t,i=Fp,r={}){let n=J.resolve(t.projectRoot);if(!await xO(n))return null;let a;try{a=await ju(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Wa(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Cb(e,t,i,r)}catch(y){throw Wa(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=y=>{for(let E of y){let S=$u(E),k=S.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(S.slice(0,k))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=za(S.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),b.stage==="0"&&d.set(R,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let m=c.records.map($u),p=CO(m,"combined"),v=new Set(p.filter(y=>!u.has(y))),g=new Set(p.filter((y,E)=>!u.has(y)&&m[E].endsWith("/")));for(let y of f)g.delete(y);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:xb(o)}}function Yr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function mb(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function AO(e,t){return!Yr(e.stageBefore,e.stageAfter)||!Yr(e.stageAfter,t.stageBefore)||!Yr(e.combined,t.combined)||!Yr(t.stageBefore,t.stageAfter)}async function _b(e,t,i,r,n){let a;try{a=await Cb(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Wa(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=xb(a),c=mb(o)||mb(s),l=AO(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:B(`comet.native.git-selection-overflow.v2
|
|
175
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var _O=(1n<<256n)-1n;function TO(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function vb(e){let t=J.resolve(e.paths.projectRoot),i=J.resolve(e.paths.nativeRoot),r=J.resolve(e.paths.runtimeDir),n=J.resolve(e.paths.configFile),a=J.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,m=!1,p=!1,v=()=>Pi(e.execution)>=1?!0:(h=!0,p=!0,!1),g=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),b=Hu("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=b[R];if(l=l+BigInt(`0x${b.toString("hex")}`)&_O,d+=1,f+=k.byteLength,Buffer.byteLength(S.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,p=!0;return}o.push(S)},y=async S=>{if(p||!v())return;let k;try{k=await be.opendir(S)}catch(P){if(!v())return;if(!Me(P)&&!Fe(P)||S===t&&Me(P))throw P;m||=Fe(P),h||=Me(P),p=!0;return}if(!v()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let b=!1,R;try{for(;!p&&v();){let P;try{P=await k.read()}catch(fe){if(!v())break;if(!Me(fe)&&!Fe(fe)||S===t&&Me(fe))throw fe;m||=Fe(fe),h||=Me(fe),p=!0;break}if(!v()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,p=!0;break}let L=J.join(S,P.name),H=jO(t,L);if(L===n||L===a||Ri(i,L)||Ri(r,L)||e.denylist.some(fe=>Ri(fe,L))||Hi(H)!==null)continue;if(!v())break;let nt;try{nt=await be.lstat(L)}catch(fe){if(!v())break;if(!Me(fe)&&!Fe(fe))throw fe;if(m=!0,g({path:H,type:"other"}),s.push({path:H,size:null,type:"file",reason:Me(fe)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(H),p||!v())break;continue}if(!v())break;let Pe=TO(nt);if(Pe==="directory"){if(DO(e.policy,H))continue;if(!v())break;let fe;try{fe=await be.realpath(L)}catch(Oi){if(!v())break;if(!Me(Oi)&&!Fe(Oi))throw Oi;if(m=!0,g({path:H,type:Pe}),s.push({path:H,size:null,type:"directory",reason:Me(Oi)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(H),p||!v())break;continue}if(!v())break;if(!$(e.physicalProjectRoot,fe)||Ri(e.physicalNativeRoot,fe))continue;if(g({path:H,type:Pe}),await e.hooks?.afterNode?.(H),!v()||(await y(L),p))break;continue}if(g({path:H,type:Pe}),await e.hooks?.afterNode?.(H),!v()||p)break}}catch(P){b=!0,R=P}let N;try{await k.close()}catch(P){N=P}let w=v();if(b)throw R;if(w&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await y(t),v(),h?(o.length=0,d=0,f=0):(o.sort((S,k)=>S.path.localeCompare(k.path,"en")),s.sort((S,k)=>S.path.localeCompare(k.path,"en")));let E=h?B(`comet.native.physical-selection-incomplete.v1
|
|
176
176
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):B(`comet.native.physical-selection.v1
|
|
177
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:
|
|
178
|
-
`)}function
|
|
179
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function
|
|
177
|
+
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:m}}}function Tb(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 IO(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!Tb(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Ib(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function gb(e,t){let r=(await ju(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Eb.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return B(`gitlink:${r}`)}async function wb(e,t){let i=await gb(e,t),r=await RO(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await gb(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Ts(e,t){if(Hi(t)!==null)return!1;let i=J.resolve(e.projectRoot,...t.split("/"));return!Ri(J.resolve(e.nativeRoot),i)&&!Ri(J.resolve(e.runtimeDir),i)}function Bp(e,t={}){let i=fr(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<i.omittedCount}}function jO(e,t){return J.relative(e,t).split(J.sep).join("/")}function $O(e,t){return t.map(i=>J.resolve(e,...i.split(/[\\/]/u)))}function Ri(e,t){let i=J.resolve(e),r=J.resolve(t);return r===i||$(i,r)}function Me(e){return wO.has(e.code??"")}function Fe(e){return e.code==="ENOENT"}function Lp(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
178
|
+
`)}function OO(e,t){return B(`comet.native.snapshot-policy.v1
|
|
179
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function $p(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function HO(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function yb(e){let t=su(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?HO(n):void 0;if(a&&!a())return!1;let o=$p(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[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=$p(i,c,a),o===null||o.size===0)return!1}return $p(i,o,a)?.has(i.length)??!1}}function jb(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>su(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>su(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 r=OO(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(yb),excludeMatchers:i.map(yb),excludedDirectoryPrefixes:i.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 DO(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Nb(e,t,i){if(!e)return!0;let r=()=>V(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function js(e,t,i){let r=JSON.stringify(i);return B(`${e}
|
|
180
180
|
${Buffer.byteLength(t)}:${t}
|
|
181
|
-
${Buffer.byteLength(r)}:${r}`)}function bp(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ku(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!bp(i))return e.splice(t,1),i}return null}function zr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?L(i,r):L(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function fO(e,t,i,r){if(!q(r))return{status:"budget-exhausted"};let n;try{n=await ye.open(e,"r")}catch(c){if(!q(r))return{status:"budget-exhausted"};throw c}if(!q(r))return await n.close(),{status:"budget-exhausted"};let a=Su("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!q(r))return{status:"budget-exhausted"};let c=await n.stat();if(!q(r))return{status:"budget-exhausted"};if(!c.isFile()||!zr(i,c))return{status:"changed"};for(;;){if(!q(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!q(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!q(r))return{status:"budget-exhausted"};let d=await n.stat();return q(r)?!d.isFile()||!zr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function ni(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ai(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Oa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function gb(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 i=W.posix.normalize(e);if(i!==e||W.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function hO(e,t){let i=ni(e,`Native snapshot entry ${t}`);ai(i,B$,`Native snapshot entry ${t}`);let r=gb(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Eu.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:qi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!sb.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function pO(e,t){let i=ni(e,`Native snapshot omission ${t}`);if(ai(i,L$,`Native snapshot omission ${t}`),!W$.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!z$.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:gb(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:qi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function mO(e){let t=ni(e,"Native snapshot omission overflow");if(ai(t,q$,"Native snapshot omission overflow"),typeof t.hash!="string"||!Eu.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Oa(t.count,"Native snapshot omission overflow count")}}function $a(e,t){let i=ni(e,t);if(ai(i,D$,t),typeof i.hash!="string"||!Eu.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=qi(i.recordCount,`${t} recordCount`),n=qi(i.storedRecordCount,`${t} storedRecordCount`),a=qi(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function nb(e){let t=ni(e,"Native Git selection evidence");if(ai(t,H$,"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 i=$a(t.stageBefore,"Native Git selection stageBefore"),r=$a(t.combined,"Native Git selection combined"),n=$a(t.stageAfter,"Native Git selection stageAfter"),a=$a(t.finalStageBefore,"Native Git selection finalStageBefore"),o=$a(t.finalCombined,"Native Git selection finalCombined"),s=$a(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Jr(i,n)||!Jr(n,a)||!Jr(r,o)||!Jr(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:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function ab(e,t){let i=ni(e,t);if(ai(i,M$,t),typeof i.hash!="string"||!Eu.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=qi(i.visitedNodeCount,`${t} visitedNodeCount`),n=qi(i.recordCount,`${t} recordCount`),a=qi(i.storedRecordCount,`${t} storedRecordCount`),o=qi(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function vO(e){let t=ni(e,"Native physical selection evidence");if(ai(t,F$,"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 i=ab(t.before,"Native physical selection before"),r=ab(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!pb(i,r);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:i,after:r}}function cr(e){let t=ni(e,"Native content snapshot manifest");if(ai(t,T$,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!V$.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=ni(t.capture,"Native content snapshot capture");if(ai(b,$$,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=b.gitSelection===void 0?void 0:nb(b.gitSelection),w=b.physicalSelection===void 0?void 0:vO(b.physicalSelection),g=null;if(b.projection!==void 0){let P=ni(b.projection,"Native content snapshot projection");if(ai(P,O$,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...P.selection===void 0?{}:{selection:nb(P.selection)}}}if(b.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(w&&g)throw new Error("Native physical-tree capture cannot combine selection and projection");i=g?{provider:"physical-tree",projection:g}:{provider:"physical-tree",...w?{physicalSelection:w}:{}}}}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 r=ni(t.limits,"Native content snapshot limits");ai(r,I$,"Native content snapshot limits");let n={maxFiles:Oa(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Oa(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Oa(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Oa(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Oa(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=ni(t.policy,"Native snapshot policy");if(ai(b,j$,"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=vb({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(hO),s=t.omitted.map(pO),c=qi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:mO(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,R)=>b+R.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>kp||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"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])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||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.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"),N=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...v,...N])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||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,S=y?.status==="overflow"||y?.status==="overflow-and-changed",E=y?.status==="changed"||y?.status==="overflow-and-changed";if(S!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(N.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Rp(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Pu(e,t,i={}){let r=cr(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=W.resolve(e.projectRoot),a=cb(i),o=lb(i.gitSelectionLimits),s=await fb(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(mb(s).filter(w=>Rs(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>Rs(e,w)),d=(w,g)=>g.some(P=>w===P||w.startsWith(`${P}/`)),f=w=>d(w,l),h=w=>d(w,u),m=[...r.entries.map(w=>w.path),...r.omitted.flatMap(w=>w.type==="directory"?[w.path,`${w.path}/`]:[w.path])].filter(w=>!c.has(w)&&!f(w)&&!h(w)),p=await Z$(a,n,m),v=r.entries.filter(w=>!f(w.path)&&!h(w.path)&&Rs(e,w.path)&&(c.has(w.path)||!p.has(w.path)));await hb(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let N=[...s.omissions];for(let w of l)N.push({path:w,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((w,g)=>w.path.localeCompare(g.path,"en"));let y=r.omitted.filter(w=>f(w.path)||h(w.path)||!Rs(e,w.path)?!1:p.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of N)y.some(g=>g.path===w.path&&g.reason===w.reason)||y.push(w);y.sort((w,g)=>w.path.localeCompare(g.path,"en"));let S=r.omissionOverflow?.count??0,E=r.omissionOverflow?.hash??B("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,E=Cs(E,"git-selection",{source:"git-selection",...s.overflow}));let k=w=>{S+=1,E=Cs(E,"omission",w)};for(;y.length>kp;){let w=ku(y);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(w)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+S===0,entries:v,omitted:y,omittedCount:y.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:S}}:{}}),R=b();for(;Rp(R)>r.limits.maxManifestBytes;){let w=ku(y);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(w),R=b()}return cr(R)}function wb(e,t){if(!_$.test(t))throw new Error(`Invalid Native change name: ${t}`);return W.join(D(e,t),"baseline-manifest.json")}async function Ru(e,t={}){let i={maxFiles:t.limits?.maxFiles??yu.maxFiles,maxFileBytes:t.limits?.maxFileBytes??yu.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??yu.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??yu.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=vb(t.policy),n=cb({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=lb(t.gitSelectionLimits),o=X$(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=W.resolve(e.projectRoot),c=await ye.realpath(s),l=W.resolve(e.nativeRoot),u=await ye.realpath(l),d=W.resolve(e.runtimeDir),f=W.resolve(e.configFile),h=W.join(s,".comet","current-change.json"),m=cO(s,t.denylist??[]),p=[],v=[],N=new Map,y=new Map,S=0,E=0,k=B("comet.native.snapshot-omission-overflow.v1"),b=0,R=!1,w=null,g=_=>{E+=1,k=Cs(k,"omission",_)},P=_=>{if(S+=1,v.length<kp){v.push(_);return}if(bp(_)){let A=ku(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),v.push(_);return}g(_)},z=_=>{S+=_.count,E+=_.count,k=Cs(k,"git-selection",{source:"git-selection",..._})},H=_=>{E+=1,k=Cs(k,"manifest-entry",{reason:"manifest-size",entry:_})},rt=async(_,A)=>{p.push(_),b+=_.size,N.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Se=(_,A)=>{let I=p.findIndex(ge=>ge.path===_);if(I<0)return;let[J]=p.splice(I,1);b-=J.size,N.delete(_),P(A)},fe=async(_,A,I,J)=>{if(!I.isFile()||I.isSymbolicLink()||!q(n))return;let ge;try{ge=await ye.realpath(_)}catch(C){if(!q(n))return;if(!Me(C)&&!Fe(C))throw C;P({path:A,size:I.size,type:"file",reason:Fe(C)?"changed-during-read":"unreadable"});return}if(!q(n)||!$(c,ge)||ki(u,ge))return;if(p.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let Z,V,Ae;try{if(Z=await fO(ge,I.size,I,n),Z.status==="budget-exhausted"||!q(n))return;if(Z.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!q(n)||(Ae=await ye.realpath(_),!q(n)))return;V=await ye.lstat(_)}catch(C){if(!q(n))return;if(!Me(C)&&!Fe(C))throw C;P({path:A,size:I.size,type:"file",reason:Fe(C)?"changed-during-read":"unreadable"});return}if(q(n)){if(Z.bytes!==I.size||Ae!==ge||!zr(I,Z.finalStat)||!zr(Z.finalStat,V)||!V.isFile()||V.isSymbolicLink()||V.size!==I.size||V.mtimeMs!==I.mtimeMs||V.ctimeMs!==I.ctimeMs){P({path:A,size:V.isFile()?V.size:null,type:V.isFile()?"file":"other",reason:"changed-during-read"});return}q(n)&&await rt({path:A,hash:Z.hash,size:V.size,type:"file",...J===void 0?{}:{gitObjectId:J}},{kind:"file",target:_,realTarget:ge,stat:V})}},_i=async(_,A,I)=>{if(!q(n))return;let J,ge,Z;try{if(J=await ye.readlink(_,{encoding:"buffer"}),!q(n)||(Z=await ye.lstat(_),!q(n)))return;ge=await ye.readlink(_,{encoding:"buffer"})}catch(C){if(!q(n))return;if(!Me(C)&&!Fe(C))throw C;P({path:A,size:null,type:"other",reason:Fe(C)?"changed-during-read":"unreadable"});return}if(!q(n))return;if(!Z.isSymbolicLink()||!zr(I,Z)||Z.mtimeMs!==I.mtimeMs||Z.ctimeMs!==I.ctimeMs||!J.equals(ge)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let V=J.byteLength;if(p.length>=i.maxFiles){P({path:A,size:V,type:"other",reason:"file-count"});return}if(V>i.maxFileBytes){P({path:A,size:V,type:"other",reason:"file-size"});return}if(b+V>i.maxTotalBytes){P({path:A,size:V,type:"other",reason:"total-size"});return}let Ae=Su("sha256").update("symlink\0").update(J).digest("hex");q(n)&&await rt({path:A,hash:Ae,size:V,type:"file"},{kind:"symlink",target:_,rawTarget:J,stat:Z})},fi=async()=>{for(let[_,A]of[...N]){if(!q(n))return;if(A.kind==="file"){let V,Ae;try{if(V=await ye.realpath(A.target),!q(n))return;Ae=await ye.lstat(A.target)}catch(C){if(!q(n))return;if(!Me(C)&&!Fe(C))throw C;Se(_,{path:_,size:null,type:"file",reason:Me(C)?"unreadable":"changed-during-read"});continue}if(!q(n))return;(V!==A.realTarget||!Ae.isFile()||Ae.isSymbolicLink()||!zr(A.stat,Ae)||Ae.size!==A.stat.size||Ae.mtimeMs!==A.stat.mtimeMs||Ae.ctimeMs!==A.stat.ctimeMs)&&Se(_,{path:_,size:Ae.isFile()?Ae.size:null,type:Ae.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let V,Ae;try{if(V=await ye.lstat(A.target),!q(n))return;Ae=await ye.readlink(A.target,{encoding:"buffer"})}catch(C){if(!q(n))return;if(!Me(C)&&!Fe(C))throw C;Se(_,{path:_,size:null,type:"other",reason:Me(C)?"unreadable":"changed-during-read"});continue}if(!q(n))return;(!V.isSymbolicLink()||!zr(A.stat,V)||V.mtimeMs!==A.stat.mtimeMs||V.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Ae))&&Se(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,J;try{if(I=await ye.realpath(A.target),!q(n))return;J=await ye.lstat(A.target)}catch{if(!q(n))return;Se(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!q(n))return;if(!(I===A.realTarget&&J.isDirectory()&&!J.isSymbolicLink()&&zr(A.stat,J)&&$(c,I)&&!ki(u,I))){Se(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let Z;try{if(!q(n))return;Z=await tb(n,I)}catch(V){if(Ha(V))throw V;Se(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!q(n))return;Z.dirty?Se(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):Z.hash!==A.hash&&Se(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!q(n))return;try{let I=await ye.lstat(A);if(!q(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!q(n))return;if(Fe(I))continue;if(!Me(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},Ft=await fb(n,e,a,t.gitSelectionHooks);if(Ft===null){let _=await ZN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let J of _.records){if(J.type!=="file"&&J.type!=="symlink"||N.has(J.path))continue;if(bi(n)<1)break;if(!rb(r,J.path,n))continue;if(bi(n)<1)break;let ge=W.resolve(s,...J.path.split("/")),Z;try{Z=await ye.lstat(ge)}catch(V){if(!q(n))break;if(!Me(V)&&!Fe(V))throw V;P({path:J.path,size:null,type:"file",reason:Fe(V)?"changed-during-read":"unreadable"});continue}if(bi(n)<1)break;if(J.type==="symlink"&&Z.isSymbolicLink()){if(await _i(ge,J.path,Z),bi(n)<1)break;continue}if(J.type!=="file"||!Z.isFile()||Z.isSymbolicLink()){P({path:J.path,size:Z.isFile()?Z.size:null,type:Z.isDirectory()?"directory":Z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await fe(ge,J.path,Z),bi(n)<1)break}bi(n)>=1&&await fi();let A=await ZN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:r,limits:o}),I=oO(_.evidence,A.evidence);w=I.evidence;for(let J of[..._.omissions,...A.omissions,...I.omissions])v.some(ge=>ge.path===J.path&&ge.reason===J.reason)||P(J)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let C=cr(_);for(let Ee of C.entries)Ee.gitObjectId!==void 0&&A.set(Ee.path,Ee);I=A.size>0}let J=new Set,ge=!0;try{let C=await xs(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(C.overflow)I=!1,ge=!1,A.clear();else for(let Ee of C.records){let _e=bu(Ee),pt=_e.indexOf(" "),nt=pt<0?null:Da(_e.slice(pt+1));if(pt!==1||nt===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");_e[0]!=="H"&&J.add(nt)}}catch(C){if(Ha(C))throw C;I=!1,ge=!1,A.clear()}let Z=new Set;try{let C=await Nu(n,s,["ls-files","--modified","-z"],Np);for(let Ee of C.toString("utf8").split("\0")){let _e=Da(Ee);_e!==null&&Z.add(_e)}}catch{I=!1,ge=!1,A.clear()}let V=new Set,Ae=new Set;for(let C of mb(Ft)){if(N.has(C)||!Rs(e,C))continue;if(bi(n)<1)break;if(!rb(r,C,n))continue;if(bi(n)<1)break;let Ee=W.resolve(s,...C.split("/"));if(Ee===f||Ee===h||ki(d,Ee)||m.some(Mt=>ki(Mt,Ee)))continue;if(Ft.gitlinks.has(C)){if(p.length>=i.maxFiles){P({path:C,size:0,type:"file",reason:"file-count"});continue}let Mt,$c;try{[Mt,$c]=await Promise.all([ye.realpath(Ee),ye.lstat(Ee)])}catch{P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if($c.isSymbolicLink()||!$c.isDirectory()||!$(c,Mt)||ki(u,Mt)){P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ca=await tb(n,Mt);if(ca.dirty){P({path:C,size:null,type:"directory",reason:"gitlink-dirty"});continue}await rt({path:C,hash:ca.hash,size:0,type:"file"},{kind:"gitlink",target:Ee,realTarget:Mt,stat:$c,hash:ca.hash})}catch(ca){if(Ha(ca))throw ca;P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let _e;try{_e=await ye.lstat(Ee)}catch(Mt){if(Fe(Mt)&&Ft.tracked.has(C)){y.set(C,Ee);continue}if(!Me(Mt)&&!Fe(Mt))throw Mt;P({path:C,size:null,type:"file",reason:Fe(Mt)?"changed-during-read":"unreadable"});continue}if(_e.isSymbolicLink()){await _i(Ee,C,_e);continue}if(!_e.isFile()){Ft.nestedRepositories.has(C)||P({path:C,size:null,type:"other",reason:"changed-during-read"});continue}let pt=Ft.trackedObjectIds.get(C),nt=pt?A.get(C):void 0;if(I&&nt?.gitObjectId!==void 0&&nt.gitObjectId===pt&&!J.has(C)&&!Z.has(C)){if(p.length>=i.maxFiles){P({path:C,size:nt.size,type:"file",reason:"file-count"});continue}if(nt.size>i.maxFileBytes){P({path:C,size:nt.size,type:"file",reason:"file-size"});continue}if(b+nt.size>i.maxTotalBytes){P({path:C,size:nt.size,type:"file",reason:"total-size"});continue}p.push({...nt}),b+=nt.size,V.add(C);continue}let Wv=ge&&!J.has(C)&&!Z.has(C)?pt:void 0;await fe(Ee,C,_e,Wv),Wv!==void 0&&Ae.add(C)}if(await fi(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await hb(n,e,a,Ft,t.gitSelectionHooks?.outputChunkBytes),V.size>0||I&&Ae.size>0){let C=await Nu(n,s,["ls-files","--modified","-z"],Np),Ee=new Set;for(let _e of C.toString("utf8").split("\0")){let pt=Da(_e);pt!==null&&Ee.add(pt)}for(let _e of V){if(!Ee.has(_e))continue;let pt=p.find(nt=>nt.path===_e);Se(_e,{path:_e,size:pt?.size??null,type:"file",reason:"changed-during-read"})}for(let _e of Ae){if(!Ee.has(_e))continue;let pt=p.find(nt=>nt.path===_e);pt&&delete pt.gitObjectId}}for(let C of Ft.omissions)P(C);Ft.overflow&&z(Ft.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let lx=Ft===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...Ft.evidence?{gitSelection:Ft.evidence}:{}},Vv=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:lx,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:i,...r?{policy:r.manifest}:{},entries:p,omitted:v,omittedCount:S,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:E}}:{}}),Jd=Vv();for(;Rp(Jd)>i.maxManifestBytes;){if(v.filter(A=>!bp(A)).length>0){let A=Math.max(1,Math.ceil(v.length/4));for(let I=0;I<A;I+=1){let J=ku(v);if(J===null)break;g(J)}}else if(p.length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I of p.splice(-A))S+=1,H(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Jd=Vv()}return Jd}async function xp(e,t,i={}){let n=(await Y(e.projectRoot))?.native.snapshot??Gh;return Ru(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Cp(e,t,i){let r=wb(e,t);await T(j(e,r),r),await me(r,cr(i))}async function Ma(e,t){let i=wb(e,t),r=j(e,i);await T(r,i);try{let n=await du({root:r,file:i,maxBytes:A$,label:"Native baseline snapshot manifest"});return cr(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as BO}from"crypto";import LO from"path";var qt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as $O}from"node:crypto";import{constants as Cu,promises as gt}from"node:fs";import Vt from"node:path";import{TextDecoder as OO}from"node:util";import _O from"path";var kO=ko(Na(),1);import{promises as SO}from"node:fs";import EO from"node:path";var As=".gitignore",yb=4*1024*1024,Nb="# >>> Comet managed project state >>>",bb="# <<< Comet managed project state <<<";function PO(e){return e.includes(`\r
|
|
181
|
+
${Buffer.byteLength(r)}:${r}`)}function Hp(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ou(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Hp(i))return e.splice(t,1),i}return null}function Kr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function FO(e,t,i,r){if(!V(r))return{status:"budget-exhausted"};let n;try{n=await be.open(e,"r")}catch(c){if(!V(r))return{status:"budget-exhausted"};throw c}if(!V(r))return await n.close(),{status:"budget-exhausted"};let a=Hu("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!V(r))return{status:"budget-exhausted"};let c=await n.stat();if(!V(r))return{status:"budget-exhausted"};if(!c.isFile()||!Kr(i,c))return{status:"changed"};for(;;){if(!V(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!V(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!V(r))return{status:"budget-exhausted"};let d=await n.stat();return V(r)?!d.isFile()||!Kr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function si(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ci(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Va(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ji(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function $b(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 i=J.posix.normalize(e);if(i!==e||J.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function MO(e,t){let i=si(e,`Native snapshot entry ${t}`);ci(i,fO,`Native snapshot entry ${t}`);let r=$b(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:Ji(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Eb.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function BO(e,t){let i=si(e,`Native snapshot omission ${t}`);if(ci(i,hO,`Native snapshot omission ${t}`),!vO.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!gO.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:$b(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:Ji(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function LO(e){let t=si(e,"Native snapshot omission overflow");if(ci(t,pO,"Native snapshot omission overflow"),typeof t.hash!="string"||!Du.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Va(t.count,"Native snapshot omission overflow count")}}function qa(e,t){let i=si(e,t);if(ci(i,lO,t),typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=Ji(i.recordCount,`${t} recordCount`),n=Ji(i.storedRecordCount,`${t} storedRecordCount`),a=Ji(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function bb(e){let t=si(e,"Native Git selection evidence");if(ci(t,cO,"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 i=qa(t.stageBefore,"Native Git selection stageBefore"),r=qa(t.combined,"Native Git selection combined"),n=qa(t.stageAfter,"Native Git selection stageAfter"),a=qa(t.finalStageBefore,"Native Git selection finalStageBefore"),o=qa(t.finalCombined,"Native Git selection finalCombined"),s=qa(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Yr(i,n)||!Yr(n,a)||!Yr(r,o)||!Yr(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:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function kb(e,t){let i=si(e,t);if(ci(i,dO,t),typeof i.hash!="string"||!Du.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=Ji(i.visitedNodeCount,`${t} visitedNodeCount`),n=Ji(i.recordCount,`${t} recordCount`),a=Ji(i.storedRecordCount,`${t} storedRecordCount`),o=Ji(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function qO(e){let t=si(e,"Native physical selection evidence");if(ci(t,uO,"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 i=kb(t.before,"Native physical selection before"),r=kb(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!Tb(i,r);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:i,after:r}}function fr(e){let t=si(e,"Native content snapshot manifest");if(ci(t,rO,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!mO.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=si(t.capture,"Native content snapshot capture");if(ci(b,oO,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=b.gitSelection===void 0?void 0:bb(b.gitSelection),N=b.physicalSelection===void 0?void 0:qO(b.physicalSelection),w=null;if(b.projection!==void 0){let P=si(b.projection,"Native content snapshot projection");if(ci(P,sO,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:bb(P.selection)}}}if(b.provider==="git"){if(N||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=si(t.limits,"Native content snapshot limits");ci(r,nO,"Native content snapshot limits");let n={maxFiles:Va(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Va(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Va(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Va(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Va(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=si(t.policy,"Native snapshot policy");if(ci(b,aO,"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=jb({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(MO),s=t.omitted.map(BO),c=Ji(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:LO(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,R)=>b+R.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>Dp||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"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])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||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.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 y=i?.physicalSelection,E=y?.status==="overflow"||y?.status==="overflow-and-changed",S=y?.status==="changed"||y?.status==="overflow-and-changed";if(E!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Lp(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Fu(e,t,i={}){let r=fr(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=J.resolve(e.projectRoot),a=Pb(i),o=Rb(i.gitSelectionLimits),s=await Ab(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(Ib(s).filter(N=>Ts(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>Ts(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),m=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),p=await PO(a,n,m),v=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&Ts(e,N.path)&&(c.has(N.path)||!p.has(N.path)));await _b(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let N of l)g.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omitted.filter(N=>f(N.path)||h(N.path)||!Ts(e,N.path)?!1:p.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of g)y.some(w=>w.path===N.path&&w.reason===N.reason)||y.push(N);y.sort((N,w)=>N.path.localeCompare(w.path,"en"));let E=r.omissionOverflow?.count??0,S=r.omissionOverflow?.hash??B("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,S=js(S,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{E+=1,S=js(S,"omission",N)};for(;y.length>Dp;){let N=Ou(y);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+E===0,entries:v,omitted:y,omittedCount:y.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:E}}:{}}),R=b();for(;Lp(R)>r.limits.maxManifestBytes;){let N=Ou(y);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=b()}return fr(R)}function Ob(e,t){if(!iO.test(t))throw new Error(`Invalid Native change name: ${t}`);return J.join(M(e,t),"baseline-manifest.json")}async function Mu(e,t={}){let i={maxFiles:t.limits?.maxFiles??Iu.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Iu.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Iu.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Iu.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=jb(t.policy),n=Pb({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Rb(t.gitSelectionLimits),o=SO(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=J.resolve(e.projectRoot),c=await be.realpath(s),l=J.resolve(e.nativeRoot),u=await be.realpath(l),d=J.resolve(e.runtimeDir),f=J.resolve(e.configFile),h=J.join(s,".comet","current-change.json"),m=$O(s,t.denylist??[]),p=[],v=[],g=new Map,y=new Map,E=0,S=0,k=B("comet.native.snapshot-omission-overflow.v1"),b=0,R=!1,N=null,w=_=>{S+=1,k=js(k,"omission",_)},P=_=>{if(E+=1,v.length<Dp){v.push(_);return}if(Hp(_)){let A=Ou(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),v.push(_);return}w(_)},L=_=>{E+=_.count,S+=_.count,k=js(k,"git-selection",{source:"git-selection",..._})},H=_=>{S+=1,k=js(k,"manifest-entry",{reason:"manifest-size",entry:_})},nt=async(_,A)=>{p.push(_),b+=_.size,g.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Pe=(_,A)=>{let I=p.findIndex(ye=>ye.path===_);if(I<0)return;let[G]=p.splice(I,1);b-=G.size,g.delete(_),P(A)},fe=async(_,A,I,G)=>{if(!I.isFile()||I.isSymbolicLink()||!V(n))return;let ye;try{ye=await be.realpath(_)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:I.size,type:"file",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(!V(n)||!$(c,ye)||Ri(u,ye))return;if(p.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let Z,z,_e;try{if(Z=await FO(ye,I.size,I,n),Z.status==="budget-exhausted"||!V(n))return;if(Z.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!V(n)||(_e=await be.realpath(_),!V(n)))return;z=await be.lstat(_)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:I.size,type:"file",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(V(n)){if(Z.bytes!==I.size||_e!==ye||!Kr(I,Z.finalStat)||!Kr(Z.finalStat,z)||!z.isFile()||z.isSymbolicLink()||z.size!==I.size||z.mtimeMs!==I.mtimeMs||z.ctimeMs!==I.ctimeMs){P({path:A,size:z.isFile()?z.size:null,type:z.isFile()?"file":"other",reason:"changed-during-read"});return}V(n)&&await nt({path:A,hash:Z.hash,size:z.size,type:"file",...G===void 0?{}:{gitObjectId:G}},{kind:"file",target:_,realTarget:ye,stat:z})}},Oi=async(_,A,I)=>{if(!V(n))return;let G,ye,Z;try{if(G=await be.readlink(_,{encoding:"buffer"}),!V(n)||(Z=await be.lstat(_),!V(n)))return;ye=await be.readlink(_,{encoding:"buffer"})}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;P({path:A,size:null,type:"other",reason:Fe(x)?"changed-during-read":"unreadable"});return}if(!V(n))return;if(!Z.isSymbolicLink()||!Kr(I,Z)||Z.mtimeMs!==I.mtimeMs||Z.ctimeMs!==I.ctimeMs||!G.equals(ye)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let z=G.byteLength;if(p.length>=i.maxFiles){P({path:A,size:z,type:"other",reason:"file-count"});return}if(z>i.maxFileBytes){P({path:A,size:z,type:"other",reason:"file-size"});return}if(b+z>i.maxTotalBytes){P({path:A,size:z,type:"other",reason:"total-size"});return}let _e=Hu("sha256").update("symlink\0").update(G).digest("hex");V(n)&&await nt({path:A,hash:_e,size:z,type:"file"},{kind:"symlink",target:_,rawTarget:G,stat:Z})},vi=async()=>{for(let[_,A]of[...g]){if(!V(n))return;if(A.kind==="file"){let z,_e;try{if(z=await be.realpath(A.target),!V(n))return;_e=await be.lstat(A.target)}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;Pe(_,{path:_,size:null,type:"file",reason:Me(x)?"unreadable":"changed-during-read"});continue}if(!V(n))return;(z!==A.realTarget||!_e.isFile()||_e.isSymbolicLink()||!Kr(A.stat,_e)||_e.size!==A.stat.size||_e.mtimeMs!==A.stat.mtimeMs||_e.ctimeMs!==A.stat.ctimeMs)&&Pe(_,{path:_,size:_e.isFile()?_e.size:null,type:_e.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let z,_e;try{if(z=await be.lstat(A.target),!V(n))return;_e=await be.readlink(A.target,{encoding:"buffer"})}catch(x){if(!V(n))return;if(!Me(x)&&!Fe(x))throw x;Pe(_,{path:_,size:null,type:"other",reason:Me(x)?"unreadable":"changed-during-read"});continue}if(!V(n))return;(!z.isSymbolicLink()||!Kr(A.stat,z)||z.mtimeMs!==A.stat.mtimeMs||z.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(_e))&&Pe(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,G;try{if(I=await be.realpath(A.target),!V(n))return;G=await be.lstat(A.target)}catch{if(!V(n))return;Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!V(n))return;if(!(I===A.realTarget&&G.isDirectory()&&!G.isSymbolicLink()&&Kr(A.stat,G)&&$(c,I)&&!Ri(u,I))){Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let Z;try{if(!V(n))return;Z=await wb(n,I)}catch(z){if(Wa(z))throw z;Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!V(n))return;Z.dirty?Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):Z.hash!==A.hash&&Pe(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!V(n))return;try{let I=await be.lstat(A);if(!V(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!V(n))return;if(Fe(I))continue;if(!Me(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},Lt=await Ab(n,e,a,t.gitSelectionHooks);if(Lt===null){let _=await vb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let G of _.records){if(G.type!=="file"&&G.type!=="symlink"||g.has(G.path))continue;if(Pi(n)<1)break;if(!Nb(r,G.path,n))continue;if(Pi(n)<1)break;let ye=J.resolve(s,...G.path.split("/")),Z;try{Z=await be.lstat(ye)}catch(z){if(!V(n))break;if(!Me(z)&&!Fe(z))throw z;P({path:G.path,size:null,type:"file",reason:Fe(z)?"changed-during-read":"unreadable"});continue}if(Pi(n)<1)break;if(G.type==="symlink"&&Z.isSymbolicLink()){if(await Oi(ye,G.path,Z),Pi(n)<1)break;continue}if(G.type!=="file"||!Z.isFile()||Z.isSymbolicLink()){P({path:G.path,size:Z.isFile()?Z.size:null,type:Z.isDirectory()?"directory":Z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await fe(ye,G.path,Z),Pi(n)<1)break}Pi(n)>=1&&await vi();let A=await vb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:r,limits:o}),I=IO(_.evidence,A.evidence);N=I.evidence;for(let G of[..._.omissions,...A.omissions,...I.omissions])v.some(ye=>ye.path===G.path&&ye.reason===G.reason)||P(G)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=fr(_);for(let Re of x.entries)Re.gitObjectId!==void 0&&A.set(Re.path,Re);I=A.size>0}let G=new Set,ye=!0;try{let x=await Is(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,ye=!1,A.clear();else for(let Re of x.records){let Te=$u(Re),vt=Te.indexOf(" "),at=vt<0?null:za(Te.slice(vt+1));if(vt!==1||at===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");Te[0]!=="H"&&G.add(at)}}catch(x){if(Wa(x))throw x;I=!1,ye=!1,A.clear()}let Z=new Set;try{let x=await ju(n,s,["ls-files","--modified","-z"],Op);for(let Re of x.toString("utf8").split("\0")){let Te=za(Re);Te!==null&&Z.add(Te)}}catch{I=!1,ye=!1,A.clear()}let z=new Set,_e=new Set;for(let x of Ib(Lt)){if(g.has(x)||!Ts(e,x))continue;if(Pi(n)<1)break;if(!Nb(r,x,n))continue;if(Pi(n)<1)break;let Re=J.resolve(s,...x.split("/"));if(Re===f||Re===h||Ri(d,Re)||m.some(qt=>Ri(qt,Re)))continue;if(Lt.gitlinks.has(x)){if(p.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let qt,Wc;try{[qt,Wc]=await Promise.all([be.realpath(Re),be.lstat(Re)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Wc.isSymbolicLink()||!Wc.isDirectory()||!$(c,qt)||Ri(u,qt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let pa=await wb(n,qt);if(pa.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await nt({path:x,hash:pa.hash,size:0,type:"file"},{kind:"gitlink",target:Re,realTarget:qt,stat:Wc,hash:pa.hash})}catch(pa){if(Wa(pa))throw pa;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let Te;try{Te=await be.lstat(Re)}catch(qt){if(Fe(qt)&&Lt.tracked.has(x)){y.set(x,Re);continue}if(!Me(qt)&&!Fe(qt))throw qt;P({path:x,size:null,type:"file",reason:Fe(qt)?"changed-during-read":"unreadable"});continue}if(Te.isSymbolicLink()){await Oi(Re,x,Te);continue}if(!Te.isFile()){Lt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let vt=Lt.trackedObjectIds.get(x),at=vt?A.get(x):void 0;if(I&&at?.gitObjectId!==void 0&&at.gitObjectId===vt&&!G.has(x)&&!Z.has(x)){if(p.length>=i.maxFiles){P({path:x,size:at.size,type:"file",reason:"file-count"});continue}if(at.size>i.maxFileBytes){P({path:x,size:at.size,type:"file",reason:"file-size"});continue}if(b+at.size>i.maxTotalBytes){P({path:x,size:at.size,type:"file",reason:"total-size"});continue}p.push({...at}),b+=at.size,z.add(x);continue}let sg=ye&&!G.has(x)&&!Z.has(x)?vt:void 0;await fe(Re,x,Te,sg),sg!==void 0&&_e.add(x)}if(await vi(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await _b(n,e,a,Lt,t.gitSelectionHooks?.outputChunkBytes),z.size>0||I&&_e.size>0){let x=await ju(n,s,["ls-files","--modified","-z"],Op),Re=new Set;for(let Te of x.toString("utf8").split("\0")){let vt=za(Te);vt!==null&&Re.add(vt)}for(let Te of z){if(!Re.has(Te))continue;let vt=p.find(at=>at.path===Te);Pe(Te,{path:Te,size:vt?.size??null,type:"file",reason:"changed-during-read"})}for(let Te of _e){if(!Re.has(Te))continue;let vt=p.find(at=>at.path===Te);vt&&delete vt.gitObjectId}}for(let x of Lt.omissions)P(x);Lt.overflow&&L(Lt.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let IC=Lt===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...Lt.evidence?{gitSelection:Lt.evidence}:{}},og=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:IC,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:p,omitted:v,omittedCount:E,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),lf=og();for(;Lp(lf)>i.maxManifestBytes;){if(v.filter(A=>!Hp(A)).length>0){let A=Math.max(1,Math.ceil(v.length/4));for(let I=0;I<A;I+=1){let G=Ou(v);if(G===null)break;w(G)}}else if(p.length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I of p.splice(-A))E+=1,H(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");lf=og()}return lf}async function qp(e,t,i={}){let n=(await Y(e.projectRoot))?.native.snapshot??cp;return Mu(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Vp(e,t,i){let r=Ob(e,t);await T(j(e,r),r),await ve(r,fr(i))}async function Ga(e,t){let i=Ob(e,t),r=j(e,i);await T(r,i);try{let n=await Eu({root:r,file:i,maxBytes:tO,label:"Native baseline snapshot manifest"});return fr(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as v0}from"crypto";import g0 from"path";var zt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as u0}from"node:crypto";import{constants as Vu,promises as bt}from"node:fs";import Jt from"node:path";import{TextDecoder as d0}from"node:util";import o0 from"path";var UO=ma(_n(),1);import{promises as KO}from"node:fs";import YO from"node:path";var $s=".gitignore",Hb=4*1024*1024,Db="# >>> Comet managed project state >>>",Fb="# <<< Comet managed project state <<<";function XO(e){return e.includes(`\r
|
|
182
182
|
`)?`\r
|
|
183
183
|
`:`
|
|
184
|
-
`}function RO(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function xO(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function CO(e){let t=[],i=!1;for(let r of RO(e)){let n=xO(r);if(n===Nb){if(i)throw new Error("Comet .gitignore managed block is malformed");i=!0;continue}if(n===bb){if(!i)throw new Error("Comet .gitignore managed block is malformed");i=!1;continue}i||t.push(r)}if(i)throw new Error("Comet .gitignore managed block is incomplete");return t.join("")}function kb(e){let t=PO(e),i=CO(e);return i.length>0&&!/(?:\r\n|\n|\r)$/u.test(i)&&(i+=t),i+[Nb,"!/.comet/","/.comet/*","!/.comet/config.yaml",bb,""].join(t)}async function Ap(e){let t=EO.resolve(e),i=await rr(t,As,{label:"project .gitignore",expected:"file"}),r="",n=new Uint8Array;i.exists&&(n=(await Oi(t,As,yb,{label:"project .gitignore"})).bytes,r=Buffer.from(n).toString("utf8"));let a=kb(r);a!==r&&(await An(i.target,a,{containedRoot:t,exclusive:!i.exists,beforeCommit:i.exists?async()=>{if(!(await Oi(t,As,yb,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await rr(t,As,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}}),await rr(t,As,{label:"project .gitignore",expected:"file"}),await SO.access(i.target))}var Sb=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Ts(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function _s(e,t){let i=Ts(e,t);if(_O.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function TO(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Eb(e){if(!e.run_id)return null;let t=Ts(e,"run_id"),i=Ts(e,"skill"),r=Ts(e,"skill_version"),n=Ts(e,"skill_hash"),a=_s(e,"pending_ref"),o=_s(e,"trajectory_ref"),s=_s(e,"context_ref"),c=_s(e,"artifacts_ref"),l=_s(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Sb(e,"current_step"),iteration:u,pending:Sb(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:TO(e)}}var Fz=256*1024;var IO=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function jO(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Eb(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function xu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!IO.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return jO(t)}var ct={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function js(e,t){let i=Vt.relative(e,t);return i===""||!Vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Vt.sep}`)}function Rb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Is(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function HO(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gr(e,t,i){let r=qt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=Vt.resolve(e),a=Vt.resolve(n,...r.slice(8).split("/"));if(!js(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function Pb(e){let t=await gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await gt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function _p(e,t){let i=Vt.resolve(e),r=Vt.resolve(t);if(!js(i,r))throw new Error("Native Run path is outside its change");let n=[await Pb(i)],a=i;for(let o of Vt.relative(i,r).split(Vt.sep).filter(Boolean)){a=Vt.join(a,o);let s;try{s=await Pb(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!js(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Au(e){for(let t of e){let i=await gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!HO(t,i)||await gt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function DO(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Mn(e,t,i,r,n){let a=await _p(e,Vt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await gt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=Rb(o),c=await gt.realpath(t);if(!js(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Cu.O_RDONLY:Cu.O_RDONLY|Cu.O_NOFOLLOW|Cu.O_NONBLOCK,u;try{u=await gt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),gt.lstat(t),gt.realpath(t)]);if(await Au(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Is(s,d)||!Is(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let m=await DO(u,i,r);await n?.beforeFinalCheck?.();let[p,v,N]=await Promise.all([u.stat(),gt.lstat(t),gt.realpath(t)]);if(await Au(a),!v.isFile()||v.isSymbolicLink()||N!==c||!Is(s,p)||!Is(s,v))throw new Error(`${r} changed while reading`);let y;try{y=new OO("utf-8",{fatal:!0}).decode(m)}catch(S){throw new Error(`${r} is not valid UTF-8`,{cause:S})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function FO(e,t,i){let r=await _p(e,Vt.dirname(t));if(!r)return{exists:!1};let n;try{n=await gt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await gt.realpath(t);if(!js(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Au(r),{exists:!0,identity:Rb(n),realPath:a}}async function MO(e,t,i,r){let n=await _p(e,Vt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await gt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Is(i.identity,a)||await gt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Au(n)}async function _u(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await FO(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await we(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await MO(e.changeDir,e.file,i,e.label)}});let r=await Mn(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function xb(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Cb(e){return`${JSON.stringify(e,null,2)}
|
|
185
|
-
`}function
|
|
186
|
-
`;if(Buffer.byteLength(a,"utf8")>ct.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${ct.trajectoryEventBytes} bytes`);let o=await
|
|
187
|
-
`)])}catch(d){if(!
|
|
188
|
-
${t}`).digest("hex")}async function
|
|
184
|
+
`}function QO(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function ZO(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function e0(e){let t=[],i=!1;for(let r of QO(e)){let n=ZO(r);if(n===Db){if(i)throw new Error("Comet .gitignore managed block is malformed");i=!0;continue}if(n===Fb){if(!i)throw new Error("Comet .gitignore managed block is malformed");i=!1;continue}i||t.push(r)}if(i)throw new Error("Comet .gitignore managed block is incomplete");return t.join("")}function Mb(e){let t=XO(e),i=e0(e);return i.length>0&&!/(?:\r\n|\n|\r)$/u.test(i)&&(i+=t),i+[Db,"!/.comet/","/.comet/*","!/.comet/config.yaml",Fb,""].join(t)}async function Wp(e){let t=YO.resolve(e),i=await sr(t,$s,{label:"project .gitignore",expected:"file"}),r="",n=new Uint8Array;i.exists&&(n=(await Mi(t,$s,Hb,{label:"project .gitignore"})).bytes,r=Buffer.from(n).toString("utf8"));let a=Mb(r);a!==r&&(await $n(i.target,a,{containedRoot:t,exclusive:!i.exists,beforeCommit:i.exists?async()=>{if(!(await Mi(t,$s,Hb,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await sr(t,$s,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}}),await sr(t,$s,{label:"project .gitignore",expected:"file"}),await KO.access(i.target))}import Nt from"path";var t0=null;function i0(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Bu(e,t){return(...i)=>{let r=t0;if(r===null)return t(...i);let n=i0(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var r0=Bu("hookWritePolicy",async e=>(await tp(e))?.hook??{allow_paths:[]});function Bb(e,t){let i=Nt.relative(e,t);return i===""||!Nt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Nt.sep}`)}function n0(e,t){let i=Nt.isAbsolute(t)?Nt.resolve(t):Nt.resolve(e,t),r=Nt.relative(Nt.resolve(e),i);return r===""||Nt.isAbsolute(r)||r===".."||r.startsWith(`..${Nt.sep}`)?null:r.replaceAll("\\","/")}function Lb(e){return process.platform==="win32"?e.toLowerCase():e}async function Lu(e,t,i=[]){let r=Nt.isAbsolute(t)?Nt.resolve(t):Nt.resolve(e,t),n=Nt.resolve(e);if(!Bb(n,r)||i.some(c=>Bb(Nt.resolve(c),r)))return null;let a=n0(e,t);if(!a)return null;let s=(await r0(e)).allow_paths.find(c=>{let l=Lb(a),u=Lb(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}var qb=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Hs(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Os(e,t){let i=Hs(e,t);if(o0.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function s0(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Vb(e){if(!e.run_id)return null;let t=Hs(e,"run_id"),i=Hs(e,"skill"),r=Hs(e,"skill_version"),n=Hs(e,"skill_hash"),a=Os(e,"pending_ref"),o=Os(e,"trajectory_ref"),s=Os(e,"context_ref"),c=Os(e,"artifacts_ref"),l=Os(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:qb(e,"current_step"),iteration:u,pending:qb(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:s0(e)}}var xJ=256*1024;var c0=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function l0(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Vb(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function qu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!c0.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return l0(t)}var ct={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Fs(e,t){let i=Jt.relative(e,t);return i===""||!Jt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Jt.sep}`)}function zb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ds(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function f0(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xr(e,t,i){let r=zt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=Jt.resolve(e),a=Jt.resolve(n,...r.slice(8).split("/"));if(!Fs(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function Wb(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zp(e,t){let i=Jt.resolve(e),r=Jt.resolve(t);if(!Fs(i,r))throw new Error("Native Run path is outside its change");let n=[await Wb(i)],a=i;for(let o of Jt.relative(i,r).split(Jt.sep).filter(Boolean)){a=Jt.join(a,o);let s;try{s=await Wb(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Fs(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Wu(e){for(let t of e){let i=await bt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!f0(t,i)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function h0(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function zn(e,t,i,r,n){let a=await zp(e,Jt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await bt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=zb(o),c=await bt.realpath(t);if(!Fs(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Vu.O_RDONLY:Vu.O_RDONLY|Vu.O_NOFOLLOW|Vu.O_NONBLOCK,u;try{u=await bt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await Wu(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Ds(s,d)||!Ds(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let m=await h0(u,i,r);await n?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([u.stat(),bt.lstat(t),bt.realpath(t)]);if(await Wu(a),!v.isFile()||v.isSymbolicLink()||g!==c||!Ds(s,p)||!Ds(s,v))throw new Error(`${r} changed while reading`);let y;try{y=new d0("utf-8",{fatal:!0}).decode(m)}catch(E){throw new Error(`${r} is not valid UTF-8`,{cause:E})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function p0(e,t,i){let r=await zp(e,Jt.dirname(t));if(!r)return{exists:!1};let n;try{n=await bt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await bt.realpath(t);if(!Fs(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Wu(r),{exists:!0,identity:zb(n),realPath:a}}async function m0(e,t,i,r){let n=await zp(e,Jt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await bt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Ds(i.identity,a)||await bt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Wu(n)}async function zu(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await p0(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await Ne(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await m0(e.changeDir,e.file,i,e.label)}});let r=await zn(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Jb(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Gb(e){return`${JSON.stringify(e,null,2)}
|
|
185
|
+
`}function Qr(e){return qu(e)}async function Je(e,t){let i=Xr(e,"stateRef"),r=await zn(e,i,ct.runStateBytes,"Native Run state",t);return r?qu(Jb(r.text,"Native Run state")):null}async function Jn(e,t,i){let r=qu(t);await zu({changeDir:e,file:Xr(e,"stateRef"),content:Gb(r),maxBytes:ct.runStateBytes,label:"Native Run state",hooks:i})}async function kt(e,t,i){let r=Xr(e,"trajectoryRef",t),n=await zn(e,r,ct.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>ct.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ct.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function Ub(e,t,i){return(await zn(e,Xr(e,"trajectoryRef",t),ct.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Kb(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=Xr(e,"trajectoryRef",t),o=await zn(e,a,ct.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(u0("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await zu({changeDir:e,file:a,content:i,maxBytes:ct.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function Yb(e,t,i,r){let n=Xr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
|
|
186
|
+
`;if(Buffer.byteLength(a,"utf8")>ct.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${ct.trajectoryEventBytes} bytes`);let o=await zn(e,n,ct.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=ct.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ct.trajectoryEvents} events`);await zu({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:ct.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function Ua(e,t,i){let r=await zn(e,Xr(e,"checkpointRef",t),ct.checkpointBytes,"Native Run checkpoint",i);return r?Jb(r.text,"Native Run checkpoint"):null}async function Xb(e,t,i,r){await zu({changeDir:e,file:Xr(e,"checkpointRef",t),content:Gb(i),maxBytes:ct.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var w0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ju=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Jp(e){return v0("sha256").update(e).digest("hex")}function y0(e,t){if(!w0.test(t))throw new Error(`Invalid Native change name: ${t}`);return g0.join(M(e,t),"trajectory.jsonl")}function N0(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function b0(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function k0(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=N0(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
187
|
+
`)])}catch(d){if(!b0(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Jp(t),targetHash:Jp(l),tailHash:Jp(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Qb(e,t){let i=y0(e,t);await T(j(e,i),i);let r=M(e,t),n=await Ub(r,zt.trajectoryRef);return n===null?{status:"clean",file:i}:k0(i,Buffer.from(n))}async function Ka(e,t){let i=await Qb(e,t);return"inspection"in i?i.inspection:i}async function Gu(e,t){let i=await Ka(e,t);if(i.status!=="clean")throw new Ju(i)}async function Zb(e,t,i){return F(e,`repair trajectory tail for ${t}`,async()=>{let r=await Qb(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new Ju(r)}try{await Kb(M(e,t),zt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await Ka(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as S0}from"node:crypto";import{promises as Uu}from"node:fs";import hr from"node:path";var Ms=/^[a-f0-9]{64}$/u,ek=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,E0=16*1024,Up=process.platform,P0=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Ya(e){return P0.has(e)}function rk(e,t){let i=hr.relative(e,t);return hr.isAbsolute(i)||i===".."||i.startsWith(`..${hr.sep}`)?null:i.replaceAll("\\","/")||"."}function nk(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function ak(e,t){if(e.length===0||nk(e)||e.includes("\\")||hr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=hr.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Kp(e,t){return S0("sha256").update(`${e}
|
|
188
|
+
${t}`).digest("hex")}async function tk(e,t){let i=await Uu.realpath(t),r=await Uu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Up==="win32"?hr.normalize(i).toLowerCase():i;return Kp(e,`${n}
|
|
189
189
|
${r.dev}
|
|
190
190
|
${r.ino}
|
|
191
|
-
${r.birthtimeMs}`)}async function
|
|
191
|
+
${r.birthtimeMs}`)}async function ik(e,t){let i=await Uu.realpath(t),r=await Uu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Up==="win32"?hr.normalize(i).toLowerCase():i;return Kp(e,n)}function R0(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 Gp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||nk(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function ok(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Gp(e.changeBranch,"Native workspace change branch"),Gp(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 C0(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!ek.test(t.baseCommit)||typeof t.targetCommit!="string"||!ek.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Gp(t.targetBranch,"Native workspace Git target branch")}function Bs(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.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"||!Ms.test(String(t.projectRootId))||!Ms.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");R0(t.capturedAt),ak(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&&!Ms.test(String(t.projectRootPathId))||a&&!Ms.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ms.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&C0(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(ok(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 Xa(e,t){return hr.join(M(e,t),"workspace.json")}function x0(e,t){let i=Xa(e,t),r=j(e,i),n=rk(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:ak(n,"Native workspace file ref")}}async function sk(e,t){try{let i=x0(e,t),r=await ee({root:i.root,ref:i.ref,maxBytes:E0});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ku(e,t){let i=me(e.projectRoot),r={projectRoot:hr.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await lt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await Gi({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Yp(e,t){let i=await sk(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Bs(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function ck(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=rk(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=me(e.paths.projectRoot),r=i.isGitWorktree?uf(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:uf(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([tk("comet.native.workspace-project-root.v2",e.paths.projectRoot),tk("comet.native.workspace-native-root.v2",e.paths.nativeRoot),ik("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),ik("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&ok(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Kp("comet.native.workspace-session.v2",`${s}
|
|
192
192
|
${c}
|
|
193
|
-
${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return
|
|
194
|
-
`);function Bs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xb(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function qn(e){if(!Yb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function o0(e){if(!Yb.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Qb(e,t){if(e.length===0||ut.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function s0(e,t){let i=Bs(e,`spec_changes[${t}]`);if(Xb(i,t0,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(o0(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Qb(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Dp.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Dp.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function c0(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 Fp(e,t){if(Xb(e,t,qe),typeof e.name!="string")throw new Error("Native change name is required");if(qn(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"||!i0.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&&!r0.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 i=e.spec_changes.map(s0),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!n0.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"&&Qb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!c0(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:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Hn(e){let t=Bs(e,qe);if(t.schema!==vt)throw new Error(`Expected ${vt}`);return{schema:vt,...Fp(t,ZO)}}function Ms(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Hp(e,t,i){if(e===null)return null;let r=typeof e=="string"?a0.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function l0(e){if(e==null)return null;if(typeof e!="string"||!Dp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function u0(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Mi(e){let t=Bs(e,qe);if(t.schema!==Oe)throw new Error(`Expected ${Oe}`);if(Ms(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Oe} minimum_runtime_version must be 2`);return{schema:Oe,minimum_runtime_version:2,revision:Ms(t.revision,"Native v2 revision"),...Fp(t,Kb)}}function _t(e){let t=Bs(e,qe);if(t.schema!==$e){if(t.schema===vt||t.schema===Oe){let o=t.schema===vt?Hn(t):Mi(t);throw new Ds(o.name,o.schema)}throw new ur(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Ms(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ur(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Ms(t.revision,"Native revision"),n=Fp(t,e0),a=l0(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:$e,minimum_runtime_version:3,revision:r,verification_protocol:u0(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Hp(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Hp(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Hp(t.partial_allowance,"Native partial_allowance","allowances")}}function Zb(e){let t=Bs(e,qe);if(t.schema===vt){let n=Hn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${$e}`}}if(t.schema===Oe){let n=Mi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${$e}`}}if(t.schema!==$e){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 ur(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Ms(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ur(t.schema,i).message};let r=_t(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Ln(e){let t=_t(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Du(e){let t=Mi(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function ee(e,t){qn(t);let i=ut.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Ja(e,t){let i=D(e,t),r=ut.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Hs.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Ga(e,t){let i=D(e,t),r=ut.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Hs.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var d0=256*1024;async function Fu(e,t=ut.dirname(e)){let i=ut.relative(t,e).split(ut.sep).join("/"),r=await ne({root:t,ref:i,maxBytes:d0}),n=(0,Hu.parseDocument)(r.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 oi(e,t){let i=ut.join(ee(e,t),qe);await T(e.nativeRoot,i);let r=Zb(await Fu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Ja(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await f0(e,r.state),r)}async function Vn(e,t){let i=ut.join(ee(e,t),qe);await T(e.nativeRoot,i);let r=Zb(await Fu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function f0(e,t){if(await Ma(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Ie(e,t){let i=await oi(e,t);if(i.status==="migration-required")throw new Ds(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new ur(i.schema,i.minimumRuntimeVersion);return await zb(e,t),i.state}async function ek(e,t,i){let r={...t,schema:$e,minimum_runtime_version:3,revision:i+1},n=await YN({expectedRevision:i,next:r,read:async()=>{let a=_t(await Fu(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>we(e,(0,Hu.stringify)(Ln(a))),equals:(a,o)=>JSON.stringify(Ln(a))===JSON.stringify(Ln(o)),conflict:a=>new Fs(t.name,i,a)});return Object.assign(t,n),n}async function Ls(e,t,i,r){if(await Ea(e.projectRoot),await Ja(e,t.name))throw new Ds(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await Ga(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await Ie(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Iu(e,t.name);let a=ut.join(ee(e,t.name),qe);return await T(e.nativeRoot,a),ek(a,t,i)}async function tk(e,t){return ek(e,t,t.revision)}async function ik(e){return _t(await Fu(e))}async function h0(e){let t;try{let r=await Tt({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await r.verify(),t=r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}return t.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort()}async function rk(e){let t=[];for(let i of await h0(e)){let r=await Vn(e,i);if(!r.state){if(await Gb(e,i))continue;t.push(i);continue}if(r.state.archived)continue;let n=await lt(e,i);if(!(!n&&await Gb(e,i))){if(n?.schema==="comet.native.workspace.v3"){if((await Vi({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Kr({paths:e,identity:n})).state==="drifted")continue;t.push(i)}}return t}function Jb(e,t){let i=ut.resolve(e),r=ut.resolve(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function Gb(e,t){for(let i of Ti(e.projectRoot))if(!Jb(i,e.projectRoot))try{let r=await Y(i);if(!r)continue;let n=await ce(i,r.native.artifact_root),a=ut.join(n.changesDir,t),o=ut.join(a,"comet-state.yaml");try{let l=await Hs.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Hs.readFile(ut.join(We(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&Jb(d.workspace.projectRoot,i))return!0;continue}}catch(l){l.code}await Hs.access(ut.join(a,qe));let s=await lt(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Vi({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Kr({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}import{randomUUID as tm}from"node:crypto";import{promises as si}from"node:fs";import He from"node:path";import{createWriteStream as $0,promises as O0}from"node:fs";import Wt from"node:path";import{spawn as Mp}from"node:child_process";import{existsSync as nk}from"node:fs";import Wn from"node:path";var p0=new Set([".bat",".cmd",".ps1"]),m0=new Set([".bat",".cmd"]),v0=/[&|<>()^%"!\r\n]/u,g0=["$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("; ");function Bp(e,t){let i=t.toLowerCase();return Object.entries(e).find(([r,n])=>r.toLowerCase()===i&&n!==void 0)?.[1]}function w0(e){let t=(Bp(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function y0(e,t,i){let n=Wn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Bp(t,"PATH")??"").split(Wn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Wn.win32.extname(e)?[e]:w0(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Wn.join(s,c):Wn.resolve(i,c)))}function N0(e,t,i){return y0(e,t,i).find(r=>nk(r))??e}function b0(e){let t=Bp(e,"SystemRoot");if(t){let i=Wn.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(nk(i))return i}return"powershell.exe"}function k0(e){if(e.some(t=>v0.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function S0(e,t,i){let r=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(g0,"utf16le").toString("base64");return Mp(b0(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:i.cwd,env:{...i.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Lp(e,t,i){let r=i.env??process.env;if(process.platform!=="win32")return Mp(e,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=N0(e,r,i.cwd),a=Wn.win32.extname(n).toLowerCase();return m0.has(a)&&k0(t),p0.has(a)?S0(n,t,{cwd:i.cwd,env:r}):Mp(n,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as E0}from"node:child_process";import qp from"node:path";var P0=1e3,R0=2;async function Mu(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,r=i&&qp.win32.isAbsolute(i)?qp.win32.resolve(i):"C:\\Windows",n=qp.win32.join(r,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=E0(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),P0)}catch{u(!1)}});for(let o=0;o<R0;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(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}var x0=/\b(Bearer|Basic)\s+[^\s"']+/giu,C0=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,A0=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,_0=/\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,T0=/("(?:[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,I0=/(["'])((?:[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,j0=/\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;function yt(e){return e.replace(x0,"$1 [REDACTED]").replace(C0,"[REDACTED PRIVATE KEY]").replace(A0,"$1[REDACTED]@").replace(_0,"[REDACTED TOKEN]").replace(T0,'$1"[REDACTED]"').replace(I0,"$1$2$1$3$4[REDACTED]$4").replace(j0,"$1$2[REDACTED]")}function ak(e,t){let i=Wt.relative(e,t);return i===""||!Wt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Wt.sep}`)}function ok(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Bu(e,t){if(t.length===0||t.includes("\\")||Wt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Wt.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let i=Wt.resolve(e),r=Wt.resolve(i,...t.split("/"));if(!ak(i,r))throw new Error("Native check cwd escaped the project root");return r}function qs(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var H0=/^(?:-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;function Vp(e){let t=!1;return e.map(i=>{if(t)return t=!1,"[REDACTED]";let r=yt(i);return H0.test(i)&&(t=!0),r})}function Lu(e,t){if(ok(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 Bu(e,t.cwdRef)}async function Wp(e){let{plan:t}=e;ok(e.operationId,"Native check operation ID");let i=Lu(e.projectRoot,t),r=Wt.join(e.runtimeDir,"logs","checks"),n=Wt.join(r,`${e.operationId}-${t.id}.log`);if(!ak(Wt.resolve(e.runtimeDir),Wt.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await O0.mkdir(r,{recursive:!0});let a=(e.now??(()=>new Date))(),o=$0(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Lp(t.executable,t.argv,{cwd:i,env:process.env})}catch(h){o.destroy(),c(h);return}let u=!1,d=null,f=setTimeout(()=>{u=!0,Mu(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);f.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",h=>{d=h,o.write(`
|
|
195
|
-
[comet] failed to start check: ${
|
|
196
|
-
`)}),l.once("close",(h,m)=>{clearTimeout(f);let p=(e.now??(()=>new Date))();o.end(()=>{let v=u||d!==null||m!==null;s({id:t.id,name:t.name,argvDisplay:Vp(t.argv),cwdRef:t.cwdRef,status:v?"interrupted":h===0?"passed":"failed",exitCode:h,signal:m,timedOut:u,durationMs:Math.max(0,p.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:p.toISOString(),repeatable:t.repeatable,logRef:Wt.relative(e.runtimeDir,n).split(Wt.sep).join("/")})})}),o.once("error",h=>{clearTimeout(f),Mu(l).catch(()=>l.kill("SIGKILL")),c(h)})})}import{randomUUID as B0}from"node:crypto";var sk=Symbol("comet.native.trusted-execution-identity"),ck=Symbol("comet.native.trusted-verifier-envelope"),Je="skill-coordinated";function zp(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Jp(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){zp(t.identityProvider,"Native identity provider");let i=Object.freeze({identityProvider:Je,executionRef:zp(t.executionRef,"Native execution ref"),[sk]:!0});return e.add(i),i},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:zp(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[ck]:!0})}})}function qu(e){return typeof e=="object"&&e!==null&&e[ck]===!0}function lk(e){return typeof e=="object"&&e!==null&&e[sk]===!0}function Vu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vs(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Ws(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function zn(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function D0(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,i)=>{let r=Vu(t,`Native Verifier acceptance ${i}`);Vs(r,["id","result","reason"],`Native Verifier acceptance ${i}`);let n=zn(r.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(r.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:r.result,reason:zn(r.reason,`Native Verifier acceptance ${n} reason`)}})}function F0(e){let t=Vu(e,"Native Verifier final result");if(Vs(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Ws(t.iteration,"Native Verifier iteration"),attempt:Ws(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:D0(t.acceptance),risks:t.risks,summary:zn(t.summary,"Native Verifier summary")}}function M0(e,t){let i=Vu(e,`Native Verifier check request ${t}`);if(Vs(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="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 r=Ws(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(r<1)throw new Error("Native Verifier check timeout must be positive");return{id:zn(i.id,`Native Verifier check request ${t} ID`),name:zn(i.name,`Native Verifier check request ${t} name`),executable:zn(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:zn(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:r,repeatable:i.repeatable}}function Gp(e){let t=Vu(e,"Native Verifier response");if(t.kind==="final-result")return Vs(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:F0(t.result)};if(t.kind==="request-checks"){if(Vs(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Ws(t.iteration,"Native Verifier iteration"),attempt:Ws(t.attempt,"Native Verifier attempt"),checks:t.checks.map(M0)}}throw new Error("Native Verifier response kind is invalid")}function uk(e){if(!qu(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:i}=e;if(t.candidateId!==i.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==i.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===i.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let r=Gp(t.payload),n=r.kind==="final-result"?r.result.iteration:r.iteration,a=r.kind==="final-result"?r.result.attempt:r.attempt;if(n!==i.iteration||a!==i.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(r.kind==="request-checks")return r;let o=[...i.acceptanceIds],s=r.result.acceptance.map(({id:f})=>f),c=s.filter((f,h)=>s.indexOf(f)!==h),l=s.filter(f=>!o.includes(f)),u=o.filter(f=>!s.includes(f));if(c.length>0||l.length>0||u.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${u.join(", ")||"none"})`);if(!i.requiredChecksPassed&&r.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=r.result.acceptance.map(({result:f})=>f);if(r.result.verdict==="pass"&&d.some(f=>f!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(r.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(r.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return r}var zs=3,Up=2;function zt(e){return e.state_version+1}function L0(e,t,i){let r=[...e];if(new Set(r).size!==r.length)throw new Error(`${i} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${i} contains unknown IDs: ${a.join(", ")}`);return r}function Kp(e){return e.map(t=>({...t,result:"pending",reason:null}))}function q0(e){return(e??[]).map(t=>({name:ue(t.name),result:t.result,note:t.note?ue(t.note):null}))}function Jn(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:ue(e.summary),completed_at:e.completedAt}}function dk(e){let t=X(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let i=e.acceptance.map(({id:r})=>r);if(new Set(i).size!==i.length)throw new Error("Native acceptance IDs must be unique");return X({...t,phase:"build",state_version:zt(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(r=>({...r,result:"pending",reason:null}))})}function fk(e){let t=X(e.state),{input:i}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!lk(i.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");let r=L0(i.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=(i.now??new Date).toISOString();return X({...t,phase:"verify",state_version:zt(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:Kp(t.acceptance),builder_handoff:{candidate_id:i.candidateId??B0(),identity_provider:i.identity.identityProvider,builder_execution_ref:i.identity.executionRef,iteration:t.loop.iteration,summary:ue(i.summary),addressed_acceptance_ids:r,checks:q0(i.checks),checks_truncated:!1,known_limits:(i.knownLimits??[]).map(a=>ue(a)),known_limits_truncated:!1,submitted_at:n},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function hk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt is not ready to dispatch");return X({...t,state_version:zt(t),loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function V0(e,t){let i=e.loop.previous_unresolved_ids;if(i.length===0)return 0;let r=new Set(i),n=new Set(t);return n.size<r.size&&[...n].every(o=>r.has(o))?0:e.loop.no_progress_count+1}function W0(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===Je?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:ue(e.response.result.summary),risks:e.response.result.risks.map(t=>ue(t)),risks_truncated:!1,completed_at:e.completedAt}}function pk(e){let t=X(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 i=uk({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:t.acceptance.map(({id:m})=>m),requiredChecksPassed:e.checks.every(({status:m})=>m==="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 r=(e.now??new Date).toISOString(),n=new Map(i.result.acceptance.map(m=>[m.id,m])),a=t.acceptance.map(m=>{let p=n.get(m.id);return{...m,result:p.result,reason:ue(p.reason)}}),o=a.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),s=W0({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:r});if(i.result.verdict==="pass"){let m=ei({...t,acceptance:a,verification:s},Jn({state:t,outcome:"pass",summary:i.result.summary,completedAt:r})),p=t.builder_handoff.identity_provider===Je;return{response:i,state:X({...m,phase:p?"verify":"archive",status:p?"await-user":"active",state_version:zt(t),verification_result:"pass",verification_report:"verification.md",blockers:p?[{owner:"user",reason:ue("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:p?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:p?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=ei({...t,acceptance:a,verification:s},Jn({state:t,outcome:"blocked",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:X({...m,status:"await-user",state_version:zt(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:ue(i.result.summary),acceptance_ids:o,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:o,next_action:"resolve-verifier-blocker"}})}}let c=t.loop.failed_iteration_count+1,l=V0(t,o),u=c>=e.maxVerifyFailures,d=l>=3,f=u||d,h=ei({...t,acceptance:a,verification:s},Jn({state:t,outcome:"fail",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:X({...h,phase:f?"verify":"build",status:f?"await-user":"active",state_version:zt(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:f?[{owner:"user",reason:ue(u?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:o,resolution_action:"await-user"}]:l>=2?[{owner:"builder",reason:ue("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:o,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:f?"await-user":"repairing",iteration:f?t.loop.iteration:t.loop.iteration+1,attempt:f?t.loop.attempt:0,failed_iteration_count:c,no_progress_count:l,execution_failure_count:0,previous_unresolved_ids:o,next_action:f?"await-user":"repair-failed-acceptance"}})}}function mk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Je||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 X({...t,phase:"archive",status:"active",state_version:zt(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function vk(e){let t=X(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Je||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 i=(e.now??new Date).toISOString(),r=t.acceptance.map(({id:a})=>a),n=ei(t,Jn({state:t,outcome:"blocked",unresolvedIds:r,summary:e.summary,completedAt:i}));return X({...n,status:"await-user",state_version:zt(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:ue(e.summary),risks:[ue("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:i},blockers:[{owner:"user",reason:ue("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:r,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:r,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function gk(e){let t=X(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 i=(e.now??new Date).toISOString(),r=ue(e.summary),n=ei(t,Jn({state:t,outcome:"pass",summary:e.summary,completedAt:i}));return X({...n,phase:"archive",status:"active",state_version:zt(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:r,completed_at:i},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:ue(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function wk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return X({...t,status:"active",state_version:zt(t),verification_result:"pending",verification_report:null,verification:null,acceptance:Kp(t.acceptance),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function yk(e){let t=X(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 i=(e.now??new Date).toISOString(),r=t.loop.execution_failure_count+1,n=r>=zs,a=ei(t,Jn({state:t,outcome:"execution-error",summary:e.summary,completedAt:i}));return X({...a,status:n?"blocked":"active",state_version:zt(t),blockers:n?[{owner:"runtime",reason:ue(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:r,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Nk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return X({...t,status:"active",state_version:zt(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Js(e){let t=X(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=ei(t,Jn({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return X({...r,phase:"build",status:"active",state_version:zt(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:Kp(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as kk}from"node:fs";import Gs from"node:path";function Wu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zu(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Wi(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function bk(e,t){return e===null?null:Wi(e,t)}function Gu(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function z0(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 J0(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Ju(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Yp(e,t){if(e===null)return null;let i=Wi(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Xp(e,t){let i=Wi(e,t);if(!Gs.isAbsolute(i))throw new Error(`${t} must be absolute`);return Gs.resolve(i)}function G0(e,t){let i=`Native local checks[${t}]`,r=Wu(e,i);if(zu(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>Wi(l,`${i}.argv[${u}]`,!0)),a=Ju(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Yp(r.startedAt,`${i}.startedAt`),s=Yp(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Gu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Wi(r.id,`${i}.id`),name:Wi(r.name,`${i}.name`),operationId:Wi(r.operationId,`${i}.operationId`),status:a,repeatable:J0(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Gu(r.executionCount,`${i}.executionCount`),argv:n,cwd:Xp(r.cwd,`${i}.cwd`),exitCode:z0(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Wi(r.log,`${i}.log`)}}function Qp(e){let t="Native local execution state",i=Wu(e,t);if(zu(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ns)throw new Error(`Native local execution schema must be ${Ns}`);let r=Wu(i.workspace,"Native local workspace");zu(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Wu(i.execution,"Native local execution");zu(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Yp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Wi(o.operationId,"Native local execution.operationId"),stage:Ju(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Ju(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:bk(o.executionId,"Native local execution.executionId"),status:Ju(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Gu(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(G0);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:Ns,change:Wi(i.change,"Native local change"),basedOnStateVersion:Gu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Xp(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Xp(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:bk(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Ge(e){return Qp({schema:Ns,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Gs.resolve(e.projectRoot),worktreeRoot:Gs.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Si(e){let t;try{t=await kk.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return Qp(i)}async function de(e,t,i={}){let r=Qp(t);await kk.mkdir(Gs.dirname(e),{recursive:!0}),await me(e,r,i)}async function Zp(e){let t=null,i=null;try{t=await Si(e.file),t===null&&(i="missing")}catch(n){if(n.code)throw n;i="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(i="version-mismatch"),t&&i===null)return{state:t,rebuilt:!1,reason:null};let r=Ge(e);return await de(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:r,rebuilt:!0,reason:i??"missing"}}import{promises as U0}from"node:fs";function Yr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
197
|
-
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function
|
|
198
|
-
`),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(
|
|
199
|
-
`),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${
|
|
200
|
-
`),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${
|
|
201
|
-
`),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${
|
|
193
|
+
${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Bs(h),h}async function Yu(e){let t=await ck(e),i=Xa(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await ve(i,t,{containedRoot:r}),t}async function lt(e,t){let i=await sk(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Bs(i),i)}async function lk(e){return await Yp(e.paths,e.name)?Yu(e):null}async function Zr(e){Bs(e.identity);let t=await ck({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Up==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function Gi(e){if(Bs(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Zr(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=me(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function uk(e,t){let i=await lt(e,t);if(i===null)return null;let r=await Gi({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var hk=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],A0=new Set(hk),pk=new Set([...hk,"minimum_runtime_version","revision"]),_0=new Set([...pk,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),T0=new Set(["capability","operation","source","base_hash"]),I0=new Set(["shape","build","verify","archive"]),j0=new Set(["implicit","confirmed"]),$0=new Set(["pending","pass","fail"]),Ve="comet-state.yaml",Qp=/^[a-f0-9]{64}$/u,mk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,O0=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,qs=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},pr=class extends Error{constructor(i,r){super(i!==$e||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Vs=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Qa=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Za=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;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"},bG=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
194
|
+
`);function zs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function vk(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Un(e){if(!mk.test(e))throw new Error(`Invalid Native change name: ${e}`)}function H0(e){if(!mk.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function gk(e,t){if(e.length===0||ut.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function D0(e,t){let i=zs(e,`spec_changes[${t}]`);if(vk(i,T0,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(H0(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&gk(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Qp.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Qp.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function F0(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 Zp(e,t){if(vk(e,t,Ve),typeof e.name!="string")throw new Error("Native change name is required");if(Un(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"||!I0.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&&!j0.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 i=e.spec_changes.map(D0),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!$0.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"&&gk(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!F0(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:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function qn(e){let t=zs(e,Ve);if(t.schema!==yt)throw new Error(`Expected ${yt}`);return{schema:yt,...Zp(t,A0)}}function Ws(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xp(e,t,i){if(e===null)return null;let r=typeof e=="string"?O0.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function M0(e){if(e==null)return null;if(typeof e!="string"||!Qp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function B0(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 Vi(e){let t=zs(e,Ve);if(t.schema!==Oe)throw new Error(`Expected ${Oe}`);if(Ws(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Oe} minimum_runtime_version must be 2`);return{schema:Oe,minimum_runtime_version:2,revision:Ws(t.revision,"Native v2 revision"),...Zp(t,pk)}}function jt(e){let t=zs(e,Ve);if(t.schema!==$e){if(t.schema===yt||t.schema===Oe){let o=t.schema===yt?qn(t):Vi(t);throw new qs(o.name,o.schema)}throw new pr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Ws(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new pr(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Ws(t.revision,"Native revision"),n=Zp(t,_0),a=M0(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:$e,minimum_runtime_version:3,revision:r,verification_protocol:B0(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xp(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xp(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xp(t.partial_allowance,"Native partial_allowance","allowances")}}function wk(e){let t=zs(e,Ve);if(t.schema===yt){let n=qn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${$e}`}}if(t.schema===Oe){let n=Vi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${$e}`}}if(t.schema!==$e){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 pr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Ws(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new pr(t.schema,i).message};let r=jt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Gn(e){let t=jt(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Qu(e){let t=Vi(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function te(e,t){Un(t);let i=ut.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function eo(e,t){let i=M(e,t),r=ut.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Ls.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function to(e,t){let i=M(e,t),r=ut.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Ls.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var L0=256*1024;async function Zu(e,t=ut.dirname(e)){let i=ut.relative(t,e).split(ut.sep).join("/"),r=await ee({root:t,ref:i,maxBytes:L0}),n=(0,Xu.parseDocument)(r.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 li(e,t){let i=ut.join(te(e,t),Ve);await T(e.nativeRoot,i);let r=wk(await Zu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await eo(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await q0(e,r.state),r)}async function Kn(e,t){let i=ut.join(te(e,t),Ve);await T(e.nativeRoot,i);let r=wk(await Zu(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function q0(e,t){if(await Ga(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function je(e,t){let i=await li(e,t);if(i.status==="migration-required")throw new qs(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new pr(i.schema,i.minimumRuntimeVersion);return await uk(e,t),i.state}async function yk(e,t,i){let r={...t,schema:$e,minimum_runtime_version:3,revision:i+1},n=await hb({expectedRevision:i,next:r,read:async()=>{let a=jt(await Zu(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Ne(e,(0,Xu.stringify)(Gn(a))),equals:(a,o)=>JSON.stringify(Gn(a))===JSON.stringify(Gn(o)),conflict:a=>new Vs(t.name,i,a)});return Object.assign(t,n),n}async function Js(e,t,i,r){if(await Ia(e.projectRoot),await eo(e,t.name))throw new qs(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await to(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await je(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Gu(e,t.name);let a=ut.join(te(e,t.name),Ve);return await T(e.nativeRoot,a),yk(a,t,i)}async function Nk(e,t){return yk(e,t,t.revision)}async function bk(e){return jt(await Zu(e))}async function V0(e){let t;try{let r=await $t({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await r.verify(),t=r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}return t.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort()}async function kk(e){let t=[];for(let i of await V0(e)){let r=await Kn(e,i);if(!r.state){if(await fk(e,i))continue;t.push(i);continue}if(r.state.archived)continue;let n=await lt(e,i);if(!(!n&&await fk(e,i))){if(n?.schema==="comet.native.workspace.v3"){if((await Gi({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Zr({paths:e,identity:n})).state==="drifted")continue;t.push(i)}}return t}function dk(e,t){let i=ut.resolve(e),r=ut.resolve(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function fk(e,t){for(let i of Zt(e.projectRoot))if(!dk(i,e.projectRoot))try{let r=await Y(i);if(!r)continue;let n=await re(i,r.native.artifact_root),a=ut.join(n.changesDir,t),o=ut.join(a,"comet-state.yaml");try{let l=await Ls.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ls.readFile(ut.join(ze(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&dk(d.workspace.projectRoot,i))return!0;continue}}catch(l){l.code}await Ls.access(ut.join(a,Ve));let s=await lt(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Gi({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Zr({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}import{randomUUID as hd}from"node:crypto";import{promises as di}from"node:fs";import He from"node:path";var am=ma(_n(),1);import{promises as _k}from"node:fs";import ui from"node:path";import{execFileSync as W0}from"node:child_process";var z0=3e4,J0=8*1024*1024,em=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function Sk(e,t){try{return W0("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:z0,maxBuffer:J0,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new em(e,t,r)}}function he(e,t){return Sk(e,t).trim()}function Gs(e){return he(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function tm(e,t){he(e,["check-ref-format","--branch",t])}function im(e){let t=Sk(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;n<i.length;n+=1){let a=i[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(r.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=i[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");r.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(r)].sort()}function Ek(e,t){try{let r=he(e,["config","--get",`branch.${t}.remote`]);if(r&&r!==".")return r}catch{}let i=he(e,["remote"]).split(/\r?\n/u).map(r=>r.trim()).filter(Boolean);if(i.includes("origin"))return"origin";if(i.length===1)return i[0];throw new Error(i.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${i.join(", ")}`)}var Pk="children.yaml",rm="comet.native.children.v1",G0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,U0=new Set(["schema","children"]),K0=new Set(["name","depends_on","covers"]);function Rk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ck(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0)throw new Error(`${i} fields are invalid`)}function xk(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function nm(e,t){let i=ui.normalize(ui.resolve(e)),r=ui.normalize(ui.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Y0(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function X0(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function Q0(e,t){let i=(0,am.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Rk(i.toJS({mapAsMap:!1}),"Native children contract");if(Ck(r,U0,"Native children contract"),r.schema!==rm)throw new Error(`Native children schema must be ${rm}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Rk(s,`Native child ${c}`);if(Ck(l,K0,`Native child ${c}`),typeof l.name!="string"||!G0.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:xk(l.depends_on,`Native child ${l.name} depends_on`),covers:xk(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return Y0(n),t&&X0(n,t),{schema:rm,children:n}}async function Us(e){let t=ui.join(e.changeDir,Pk);try{await _k.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await ee({root:e.changeDir,ref:Pk});return{contract:Q0(i.text,e.acceptanceIds),size:i.size}}function ed(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function Z0(e){let t=Zt(e.projectRoot);t.some(r=>nm(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>ui.resolve(n)))]){let n=await Y(r);n&&i.push({projectRoot:r,paths:await re(r,n.native.artifact_root),parent:nm(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function eH(e,t){let i=ui.join(e.paths.changesDir,t,"comet-state.yaml");try{return await wt(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function tH(e,t){let i;try{i=await _k.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=ui.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await wt(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function iH(e,t,i){let r=ui.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${ui.sep}`))return null;let n=r.split(ui.sep).join("/");try{let a=(0,am.parseDocument)(he(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:X(a.toJS({mapAsMap:!1}))}catch{return null}}function rH(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||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 ${i??"(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 Ak(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Gt(e){let t=ui.join(e.paths.changesDir,e.state.name),i=await Us({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=ed({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await Z0(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:p})=>p)),c=new Map,l=new Map;for(let p of a){let v=p.parent&&o?`refs/heads/${o}`:"HEAD";for(let g of await tH(p,s)){let y={...g,source:p,committedState:iH(p,g.file,v)};c.set(g.state.name,[...c.get(g.state.name)??[],y])}for(let g of s){let y=await eH(p,g);y&&l.set(g,[...l.get(g)??[],{source:p,state:y}])}}let u=new Map;for(let p of i.contract.children){let v=(c.get(p.name)??[]).find(({source:E,committedState:S})=>E.parent&&S?.name===p.name&&Ak(S,o));if(v){u.set(p.name,{kind:"done",phase:v.state.phase,projectRoot:v.source.projectRoot,message:null});continue}let g=c.get(p.name)?.[0];if(g){u.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=l.get(p.name)??[];y.length>1?u.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&u.set(p.name,rH(y[0].state,y[0].source,o))}let d=new Map(i.contract.children.map(p=>[p.name,p])),f=new Map,h=p=>{let v=f.get(p);if(v)return v;let g=d.get(p),E=g.depends_on.map(h).every(({status:w})=>w==="done"),S=u.get(p),k=S?.kind==="active"&&E?g.depends_on.filter(w=>!(c.get(w)??[]).some(({source:P,committedState:L})=>nm(P.projectRoot,S.projectRoot)&&L?.name===w&&Ak(L,o))):[],b,R=S?.message??null;S?.kind==="done"?(b=E?"done":"blocked",E||(R=`Native child ${p} was merged before its dependencies`)):S?.kind==="active"?(b=E&&k.length===0?"active":"blocked",E?k.length>0&&(R=`Native child ${p} does not include merged dependencies: ${k.join(", ")}`):R=`Native child ${p} started before its dependencies merged`):S?.kind==="blocked"?b="blocked":(b=n&&E?"ready":"pending",n||(R="Parent Shape confirmation is required"));let N={name:p,dependsOn:[...g.depends_on],covers:[...g.covers],status:b,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:R};return f.set(p,N),N},m=i.contract.children.map(({name:p})=>h(p));return{contractHash:r,confirmed:n,parentBranch:o,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}import{createWriteStream as EH,promises as PH}from"node:fs";import Ut from"node:path";import{spawn as om}from"node:child_process";import{existsSync as Tk}from"node:fs";import Yn from"node:path";var nH=new Set([".bat",".cmd",".ps1"]),aH=new Set([".bat",".cmd"]),oH=/[&|<>()^%"!\r\n]/u,sH=["$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("; ");function sm(e,t){let i=t.toLowerCase();return Object.entries(e).find(([r,n])=>r.toLowerCase()===i&&n!==void 0)?.[1]}function cH(e){let t=(sm(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function lH(e,t,i){let n=Yn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(sm(t,"PATH")??"").split(Yn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Yn.win32.extname(e)?[e]:cH(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Yn.join(s,c):Yn.resolve(i,c)))}function uH(e,t,i){return lH(e,t,i).find(r=>Tk(r))??e}function dH(e){let t=sm(e,"SystemRoot");if(t){let i=Yn.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Tk(i))return i}return"powershell.exe"}function fH(e){if(e.some(t=>oH.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function hH(e,t,i){let r=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(sH,"utf16le").toString("base64");return om(dH(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:i.cwd,env:{...i.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function cm(e,t,i){let r=i.env??process.env;if(process.platform!=="win32")return om(e,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=uH(e,r,i.cwd),a=Yn.win32.extname(n).toLowerCase();return aH.has(a)&&fH(t),nH.has(a)?hH(n,t,{cwd:i.cwd,env:r}):om(n,[...t],{cwd:i.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as pH}from"node:child_process";import lm from"node:path";var mH=1e3,vH=2;async function td(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,r=i&&lm.win32.isAbsolute(i)?lm.win32.resolve(i):"C:\\Windows",n=lm.win32.join(r,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=pH(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),mH)}catch{u(!1)}});for(let o=0;o<vH;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(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}var gH=/\b(Bearer|Basic)\s+[^\s"']+/giu,wH=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,yH=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,NH=/\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,bH=/("(?:[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,kH=/(["'])((?:[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,SH=/\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;function St(e){return e.replace(gH,"$1 [REDACTED]").replace(wH,"[REDACTED PRIVATE KEY]").replace(yH,"$1[REDACTED]@").replace(NH,"[REDACTED TOKEN]").replace(bH,'$1"[REDACTED]"').replace(kH,"$1$2$1$3$4[REDACTED]$4").replace(SH,"$1$2[REDACTED]")}function Ik(e,t){let i=Ut.relative(e,t);return i===""||!Ut.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ut.sep}`)}function jk(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function id(e,t){if(t.length===0||t.includes("\\")||Ut.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Ut.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let i=Ut.resolve(e),r=Ut.resolve(i,...t.split("/"));if(!Ik(i,r))throw new Error("Native check cwd escaped the project root");return r}function Ks(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var RH=/^(?:-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;function um(e){let t=!1;return e.map(i=>{if(t)return t=!1,"[REDACTED]";let r=St(i);return RH.test(i)&&(t=!0),r})}function rd(e,t){if(jk(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 id(e,t.cwdRef)}async function dm(e){let{plan:t}=e;jk(e.operationId,"Native check operation ID");let i=rd(e.projectRoot,t),r=Ut.join(e.runtimeDir,"logs","checks"),n=Ut.join(r,`${e.operationId}-${t.id}.log`);if(!Ik(Ut.resolve(e.runtimeDir),Ut.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await PH.mkdir(r,{recursive:!0});let a=(e.now??(()=>new Date))(),o=EH(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=cm(t.executable,t.argv,{cwd:i,env:process.env})}catch(h){o.destroy(),c(h);return}let u=!1,d=null,f=setTimeout(()=>{u=!0,td(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);f.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",h=>{d=h,o.write(`
|
|
195
|
+
[comet] failed to start check: ${St(h.message)}
|
|
196
|
+
`)}),l.once("close",(h,m)=>{clearTimeout(f);let p=(e.now??(()=>new Date))();o.end(()=>{let v=u||d!==null||m!==null;s({id:t.id,name:t.name,argvDisplay:um(t.argv),cwdRef:t.cwdRef,status:v?"interrupted":h===0?"passed":"failed",exitCode:h,signal:m,timedOut:u,durationMs:Math.max(0,p.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:p.toISOString(),repeatable:t.repeatable,logRef:Ut.relative(e.runtimeDir,n).split(Ut.sep).join("/")})})}),o.once("error",h=>{clearTimeout(f),td(l).catch(()=>l.kill("SIGKILL")),c(h)})})}import{randomUUID as _H}from"node:crypto";var $k=Symbol("comet.native.trusted-execution-identity"),Ok=Symbol("comet.native.trusted-verifier-envelope"),Ge="skill-coordinated";function fm(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Ys(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){fm(t.identityProvider,"Native identity provider");let i=Object.freeze({identityProvider:Ge,executionRef:fm(t.executionRef,"Native execution ref"),[$k]:!0});return e.add(i),i},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:fm(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Ok]:!0})}})}function nd(e){return typeof e=="object"&&e!==null&&e[Ok]===!0}function Hk(e){return typeof e=="object"&&e!==null&&e[$k]===!0}function ad(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xs(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Qs(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Xn(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function CH(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,i)=>{let r=ad(t,`Native Verifier acceptance ${i}`);Xs(r,["id","result","reason"],`Native Verifier acceptance ${i}`);let n=Xn(r.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(r.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:r.result,reason:Xn(r.reason,`Native Verifier acceptance ${n} reason`)}})}function xH(e){let t=ad(e,"Native Verifier final result");if(Xs(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Qs(t.iteration,"Native Verifier iteration"),attempt:Qs(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:CH(t.acceptance),risks:t.risks,summary:Xn(t.summary,"Native Verifier summary")}}function AH(e,t){let i=ad(e,`Native Verifier check request ${t}`);if(Xs(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="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 r=Qs(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(r<1)throw new Error("Native Verifier check timeout must be positive");return{id:Xn(i.id,`Native Verifier check request ${t} ID`),name:Xn(i.name,`Native Verifier check request ${t} name`),executable:Xn(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:Xn(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:r,repeatable:i.repeatable}}function hm(e){let t=ad(e,"Native Verifier response");if(t.kind==="final-result")return Xs(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:xH(t.result)};if(t.kind==="request-checks"){if(Xs(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Qs(t.iteration,"Native Verifier iteration"),attempt:Qs(t.attempt,"Native Verifier attempt"),checks:t.checks.map(AH)}}throw new Error("Native Verifier response kind is invalid")}function Dk(e){if(!nd(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:i}=e;if(t.candidateId!==i.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==i.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===i.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let r=hm(t.payload),n=r.kind==="final-result"?r.result.iteration:r.iteration,a=r.kind==="final-result"?r.result.attempt:r.attempt;if(n!==i.iteration||a!==i.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(r.kind==="request-checks")return r;let o=[...i.acceptanceIds],s=r.result.acceptance.map(({id:f})=>f),c=s.filter((f,h)=>s.indexOf(f)!==h),l=s.filter(f=>!o.includes(f)),u=o.filter(f=>!s.includes(f));if(c.length>0||l.length>0||u.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${u.join(", ")||"none"})`);if(!i.requiredChecksPassed&&r.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let d=r.result.acceptance.map(({result:f})=>f);if(r.result.verdict==="pass"&&d.some(f=>f!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(r.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(r.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return r}var Zs=3,pm=2;function Kt(e){return e.state_version+1}function TH(e,t,i){let r=[...e];if(new Set(r).size!==r.length)throw new Error(`${i} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${i} contains unknown IDs: ${a.join(", ")}`);return r}function mm(e){return e.map(t=>({...t,result:"pending",reason:null}))}function IH(e){return(e??[]).map(t=>({name:ue(t.name),result:t.result,note:t.note?ue(t.note):null}))}function Qn(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:ue(e.summary),completed_at:e.completedAt}}function Fk(e){let t=X(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let i=e.acceptance.map(({id:r})=>r);if(new Set(i).size!==i.length)throw new Error("Native acceptance IDs must be unique");return X({...t,phase:"build",state_version:Kt(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(r=>({...r,result:"pending",reason:null}))})}function vm(e){let t=X(e.state),{input:i}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Hk(i.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");let r=TH(i.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=(i.now??new Date).toISOString();return X({...t,phase:"verify",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:mm(t.acceptance),builder_handoff:{candidate_id:i.candidateId??_H(),identity_provider:i.identity.identityProvider,builder_execution_ref:i.identity.executionRef,iteration:t.loop.iteration,summary:ue(i.summary),addressed_acceptance_ids:r,checks:IH(i.checks),checks_truncated:!1,known_limits:(i.knownLimits??[]).map(a=>ue(a)),known_limits_truncated:!1,submitted_at:n},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Mk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt is not ready to dispatch");return X({...t,state_version:Kt(t),loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function jH(e,t){let i=e.loop.previous_unresolved_ids;if(i.length===0)return 0;let r=new Set(i),n=new Set(t);return n.size<r.size&&[...n].every(o=>r.has(o))?0:e.loop.no_progress_count+1}function $H(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===Ge?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:ue(e.response.result.summary),risks:e.response.result.risks.map(t=>ue(t)),risks_truncated:!1,completed_at:e.completedAt}}function Bk(e){let t=X(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 i=Dk({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:t.acceptance.map(({id:m})=>m),requiredChecksPassed:e.checks.every(({status:m})=>m==="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 r=(e.now??new Date).toISOString(),n=new Map(i.result.acceptance.map(m=>[m.id,m])),a=t.acceptance.map(m=>{let p=n.get(m.id);return{...m,result:p.result,reason:ue(p.reason)}}),o=a.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),s=$H({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:r});if(i.result.verdict==="pass"){let m=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"pass",summary:i.result.summary,completedAt:r})),p=t.builder_handoff.identity_provider===Ge;return{response:i,state:X({...m,phase:p?"verify":"archive",status:p?"await-user":"active",state_version:Kt(t),verification_result:"pass",verification_report:"verification.md",blockers:p?[{owner:"user",reason:ue("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:p?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:p?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"blocked",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:X({...m,status:"await-user",state_version:Kt(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:ue(i.result.summary),acceptance_ids:o,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:o,next_action:"resolve-verifier-blocker"}})}}let c=t.loop.failed_iteration_count+1,l=jH(t,o),u=c>=e.maxVerifyFailures,d=l>=3,f=u||d,h=ri({...t,acceptance:a,verification:s},Qn({state:t,outcome:"fail",unresolvedIds:o,summary:i.result.summary,completedAt:r}));return{response:i,state:X({...h,phase:f?"verify":"build",status:f?"await-user":"active",state_version:Kt(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:f?[{owner:"user",reason:ue(u?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:o,resolution_action:"await-user"}]:l>=2?[{owner:"builder",reason:ue("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:o,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:f?"await-user":"repairing",iteration:f?t.loop.iteration:t.loop.iteration+1,attempt:f?t.loop.attempt:0,failed_iteration_count:c,no_progress_count:l,execution_failure_count:0,previous_unresolved_ids:o,next_action:f?"await-user":"repair-failed-acceptance"}})}}function Lk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Ge||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 X({...t,phase:"archive",status:"active",state_version:Kt(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function qk(e){let t=X(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Ge||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 i=(e.now??new Date).toISOString(),r=t.acceptance.map(({id:a})=>a),n=ri(t,Qn({state:t,outcome:"blocked",unresolvedIds:r,summary:e.summary,completedAt:i}));return X({...n,status:"await-user",state_version:Kt(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:ue(e.summary),risks:[ue("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:i},blockers:[{owner:"user",reason:ue("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:r,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:r,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Vk(e){let t=X(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 i=(e.now??new Date).toISOString(),r=ue(e.summary),n=ri(t,Qn({state:t,outcome:"pass",summary:e.summary,completedAt:i}));return X({...n,phase:"archive",status:"active",state_version:Kt(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:r,completed_at:i},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:ue(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Wk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.verdict!=="blocked"||t.verification.assurance==="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="resolve-verifier-blocker"||!t.blockers.some(({resolution_action:i})=>i==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");return X({...t,status:"active",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,acceptance:mm(t.acceptance),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function zk(e){let t=X(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 i=(e.now??new Date).toISOString(),r=t.loop.execution_failure_count+1,n=r>=Zs,a=ri(t,Qn({state:t,outcome:"execution-error",summary:e.summary,completedAt:i}));return X({...a,status:n?"blocked":"active",state_version:Kt(t),blockers:n?[{owner:"runtime",reason:ue(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:r,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Jk(e){let t=X(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:i})=>i==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return X({...t,status:"active",state_version:Kt(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function ec(e){let t=X(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=ri(t,Qn({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return X({...r,phase:"build",status:"active",state_version:Kt(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:mm(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as Uk}from"node:fs";import tc from"node:path";function od(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function sd(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ui(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Gk(e,t){return e===null?null:Ui(e,t)}function ld(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function OH(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 HH(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function cd(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function gm(e,t){if(e===null)return null;let i=Ui(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function wm(e,t){let i=Ui(e,t);if(!tc.isAbsolute(i))throw new Error(`${t} must be absolute`);return tc.resolve(i)}function DH(e,t){let i=`Native local checks[${t}]`,r=od(e,i);if(sd(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>Ui(l,`${i}.argv[${u}]`,!0)),a=cd(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=gm(r.startedAt,`${i}.startedAt`),s=gm(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=ld(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ui(r.id,`${i}.id`),name:Ui(r.name,`${i}.name`),operationId:Ui(r.operationId,`${i}.operationId`),status:a,repeatable:HH(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:ld(r.executionCount,`${i}.executionCount`),argv:n,cwd:wm(r.cwd,`${i}.cwd`),exitCode:OH(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ui(r.log,`${i}.log`)}}function ym(e){let t="Native local execution state",i=od(e,t);if(sd(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ps)throw new Error(`Native local execution schema must be ${Ps}`);let r=od(i.workspace,"Native local workspace");sd(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=od(i.execution,"Native local execution");sd(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=gm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ui(o.operationId,"Native local execution.operationId"),stage:cd(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:cd(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Gk(o.executionId,"Native local execution.executionId"),status:cd(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ld(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(DH);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:Ps,change:Ui(i.change,"Native local change"),basedOnStateVersion:ld(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:wm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:wm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Gk(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function Be(e){return ym({schema:Ps,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:tc.resolve(e.projectRoot),worktreeRoot:tc.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ci(e){let t;try{t=await Uk.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return ym(i)}async function ce(e,t,i={}){let r=ym(t);await Uk.mkdir(tc.dirname(e),{recursive:!0}),await ve(e,r,i)}async function Nm(e){let t=null,i=null;try{t=await Ci(e.file),t===null&&(i="missing")}catch(n){if(n.code)throw n;i="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(i="version-mismatch"),t&&i===null)return{state:t,rebuilt:!1,reason:null};let r=Be(e);return await ce(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:r,rebuilt:!0,reason:i??"missing"}}import{promises as FH}from"node:fs";function en(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
197
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function mr(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function MH(e){return e.verification?.assurance==="semantic-verification-unavailable"?"Semantic verification unavailable, user confirmation required":e.verification?.assurance==="user-confirmed-degraded"?"Passed with user-confirmed degraded assurance":e.verification_result==="pass"?e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?"Passed, user confirmation required":"Passed":e.verification_result==="blocked"?"Blocked":e.verification_result==="fail"?"Failed":"Pending"}function BH(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===Ge?Ge:"host-attested")}function LH(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${mr(o.id)} | ${mr(o.result)} | ${mr(o.source)} | ${mr(o.text)} | ${mr(en(o.reason))} |`).join(`
|
|
198
|
+
`),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(en).join(" ");return`| ${mr(en(o.name))} | ${mr(s||"—")} | ${mr(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(`
|
|
199
|
+
`),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${en(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(`
|
|
200
|
+
`),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${en(o)}`).join(`
|
|
201
|
+
`),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${mr(en(o.summary))} | ${o.completed_at} |`)].join(`
|
|
202
202
|
`);return`---
|
|
203
203
|
generated_from_state_version: ${e.state_version}
|
|
204
204
|
---
|
|
@@ -207,13 +207,13 @@ generated_from_state_version: ${e.state_version}
|
|
|
207
207
|
|
|
208
208
|
## Current result
|
|
209
209
|
|
|
210
|
-
- Result: **${
|
|
211
|
-
- Assurance: **${
|
|
210
|
+
- Result: **${MH(e)}**
|
|
211
|
+
- Assurance: **${BH(e)}**
|
|
212
212
|
- Goal cycle: ${e.loop.goal_cycle}
|
|
213
213
|
- Iteration: ${e.verification.iteration}
|
|
214
214
|
- Verifier attempt: ${e.verification.attempt}
|
|
215
215
|
- Completed: ${e.verification.completed_at}
|
|
216
|
-
- Summary: ${
|
|
216
|
+
- Summary: ${en(e.verification.summary)}
|
|
217
217
|
|
|
218
218
|
## Acceptance
|
|
219
219
|
|
|
@@ -241,8 +241,8 @@ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summ
|
|
|
241
241
|
|
|
242
242
|
`:""}## Conclusion
|
|
243
243
|
|
|
244
|
-
${
|
|
245
|
-
`}function
|
|
244
|
+
${en(e.verification.summary)}
|
|
245
|
+
`}function qH(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function ic(e){let t;try{t=await FH.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=qH(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function vr(e){await Ne(e.file,LH(e.state))}var pd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VH="comet-state.yaml",WH="state.json",zH=`# Outcome
|
|
246
246
|
|
|
247
247
|
# Scope
|
|
248
248
|
|
|
@@ -257,42 +257,42 @@ ${Yr(e.verification.summary)}
|
|
|
257
257
|
# Open questions
|
|
258
258
|
|
|
259
259
|
# Verification expectations
|
|
260
|
-
`;function je(e,t){if(!Xu.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=He.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function jt(e,t){return He.join(je(e,t),Z0)}function oe(e,t){return He.join(We(e,t),eH)}async function Ne(e,t){try{let i=await si.readFile(jt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function iH(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Jt(e){return pe(e).currentBranch}function rH(e,t){if(!t)return;let i=pe(e);if(t.changeBranch!==null&&(!i.isGitWorktree||i.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Ek(e){return F(e.paths,`create portable change ${e.name}`,async()=>{if(!Xu.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await Y(e.paths.projectRoot)===null&&await Bt(e.paths.projectRoot,e.initialProjectConfig),rH(e.paths.projectRoot,e.workspaceBinding);let t=(await rk(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new Wa(e.workspaceBinding?.isolation??"current",t);let i=je(e.paths,e.name),r=We(e.paths,e.name);await Promise.all([T(e.paths.nativeRoot,i),T(e.paths.runtimeDir,r)]);let n=!1,a=!1;try{await si.mkdir(e.paths.changesDir,{recursive:!0}),await si.mkdir(i,{recursive:!1}),n=!0,await si.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await si.mkdir(r,{recursive:!1}),a=!0,await si.mkdir(He.join(i,"specs"),{recursive:!0}),await we(He.join(i,"brief.md"),tH);let o=RN({name:e.name,language:e.language,workspace:iH(e.workspaceBinding),createdAt:e.now,nextAction:"confirm-shape"});return await bs(jt(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await de(oe(e.paths,e.name),Ge({portableState:o,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await si.rm(r,{recursive:!0,force:!0}),n&&await si.rm(i,{recursive:!0,force:!0}),o}})}async function K(e,t){return Zt(jt(e,t))}async function Nt(e){let t=await $n({file:jt(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 i=He.join(je(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await si.rm(i,{force:!0})}return t}async function Pk(e){let t=je(e.paths,e.state.name),i=He.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await si.readdir(i,{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(!Xu.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=He.join(t,...s.split("/")),l=await si.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=He.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await si.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Rk(e){let t=je(e.paths,e.state.name),i=await ne({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await ne({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return iu({briefMarkdown:i.text,specs:r})}async function xk(e){return F(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await Pk({paths:e.paths,state:t}),r=await Rk({paths:e.paths,state:t,specChanges:i}),n=dk({state:{...t,spec_changes:i},acceptance:r.map(o=>({...o}))}),a=await Nt({paths:e.paths,previous:t,next:n});return await de(oe(e.paths,t.name),Ge({portableState:a,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Qu(e){let t=await Pk(e);if(!(t.length===e.state.spec_changes.length&&t.every((a,o)=>{let s=e.state.spec_changes[o];return s!==void 0&&a.capability===s.capability&&a.source===s.source&&(a.operation===s.operation||e.ignoreSpecOperationFor?.has(a.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let r=await Rk({...e,specChanges:t}),n=e.state.acceptance.map(({source:a,text:o})=>({source:a,text:o}));return EN(n,r)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native confirmed acceptance criteria changed"}}async function Xr(e){let t=await Qu(e);if(!t.drifted)return;let i=t.reason??"Native confirmed requirements changed";throw await Zu({paths:e.paths,state:e.state,reason:i}),new Error(`${i}; Native change returned to Shape and requires confirmation`)}async function Ck(e){return F(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await K(e.paths,e.name);await Xr({paths:e.paths,state:t});let i=fk({state:t,input:e.input}),r=await Nt({paths:e.paths,previous:t,next:i});return await de(oe(e.paths,t.name),Ge({portableState:r,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r})}function im(e,t,i){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:Bu(i,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function Ak(e,t,i,r){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...im(t,i,r),executionCount:e.executionCount}}function _k(e,t){let i=He.relative(He.resolve(e),He.resolve(t));if(He.isAbsolute(i)||i===".."||i.startsWith(`..${He.sep}`))throw new Error("Native local check cwd escaped the project root");let r=i.length===0?".":i.split(He.sep).join("/");return Bu(e,r),r}function em(e,t){let[i,...r]=e.argv;if(!i)throw new Error(`Native local check ${e.id} has no executable`);return qs({id:e.id,name:e.id,executable:i,argv:r,cwdRef:_k(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function nH(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Ua(e){let t=new Map;for(let i of e.supplied){if(t.has(i.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${i.id}`);t.set(i.id,i)}return e.local.checks.map(i=>{if(i.status==="planned"||i.status==="running")throw new Error(`Native Runtime check ${i.id} has not completed`);let r=e.requestedNames?.get(i.id)??i.name;return{id:i.id,name:ue(r),argv_display:Vp(i.argv.slice(1)).map(n=>ue(n)),argv_truncated:!1,cwd_ref:_k(e.projectRoot,i.cwd),status:i.status,exit_code:i.exitCode,duration_ms:nH(i)}})}function aH(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Ks(e){if(e.local===null||e.local.change!==e.state.name)return Ge({portableState:e.state,projectRoot:e.projectRoot,branch:Jt(e.projectRoot)});let t=e.local.execution?.operationId??tm();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(i=>i.status==="running"||i.status==="planned"?{...i,operationId:t,status:"interrupted"}:{...i,operationId:t})}}async function Ka(e){try{let t=await Si(oe(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function Tk(e){let{state:t,local:i,expected:r}=e;if(t.state_version!==r.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==r.iteration||t.loop.attempt!==r.attempt||t.builder_handoff===null||i===null||i.basedOnStateVersion!==t.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return i}function oH(e){let{state:t,local:i,envelope:r}=e;if(!qu(r))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(r.candidateId!==t.builder_handoff.candidate_id||r.identityProvider!==t.builder_handoff.identity_provider||r.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(i===null||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==null&&i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return r}function sH(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Yu(e){let t=await Ka({paths:e.paths,state:e.state}),i=yk({state:e.state,summary:e.summary}),r=await Nt({paths:e.paths,previous:e.state,next:i});return await de(oe(e.paths,e.state.name),Ks({local:t,state:r,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),r}function Sk(e,t,i){return e.checks.length!==t.length?!1:e.checks.every((r,n)=>em(r,i)===qs(t[n]))}async function cH(e){return F(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(await Xr({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let i=oe(e.paths,t.name),r=(await Zp({file:i,portableState:t,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(r.execution?.stage==="checking"&&r.execution.actor==="runtime"&&Sk(r,e.plans,e.paths.projectRoot)){let o=r.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=r.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:u})=>[l,u]));return{kind:"reuse",state:t,checks:Ua({local:r,projectRoot:e.paths.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=Js({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(u=>!u.repeatable).map(({id:u})=>u).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await Nt({paths:e.paths,previous:t,next:c});throw await de(oe(e.paths,t.name),Ge({portableState:l,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(u=>!u.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(r.execution!==null&&r.checks.length>0){if(!(r.execution.stage==="checking"&&r.execution.actor==="runtime"&&r.checks.some(s=>s.status==="interrupted")&&Sk(r,e.plans,e.paths.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(r.execution!==null||r.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=tm(),a={...r,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=r.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?Ak(s,o,n,e.paths.projectRoot):s?{...s,operationId:n}:im(o,n,e.paths.projectRoot)})};return await de(i,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=r.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function Uu(e){return F(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await K(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 i=oe(e.paths,t.name),r=await Si(i);if(r===null||r.basedOnStateVersion!==t.state_version||r.execution?.operationId!==e.operationId||r.execution.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(r);return await de(i,n,{containedRoot:e.paths.runtimeDir}),n})}async function Ik(e){if(new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let t=[],i=new Set;for(let s of e.plans){Lu(e.paths.projectRoot,s);let c=qs(s);i.has(c)||(i.add(c),t.push(s))}let r=await cH({...e,plans:t});if(r.kind==="reuse")return r;let n=r.local.execution.operationId,a=We(e.paths,r.state.name);try{for(let s of r.plans){let c=new Date().toISOString();await Uu({paths:e.paths,state:r.state,operationId:n,update:u=>({...u,checks:u.checks.map(d=>d.id===s.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:c}:d)})});let l=await Wp({projectRoot:e.paths.projectRoot,runtimeDir:a,operationId:n,plan:s});await Uu({paths:e.paths,state:r.state,operationId:n,update:u=>({...u,checks:u.checks.map(d=>d.id===s.id?{...d,status:l.status,exitCode:l.exitCode,startedAt:l.startedAt,completedAt:l.completedAt,log:l.logRef}:d)})})}await Uu({paths:e.paths,state:r.state,operationId:n,update:s=>({...s,execution:{...s.execution,status:"completed"}})})}catch(s){try{await Uu({paths:e.paths,state:r.state,operationId:n,update:c=>({...c,execution:{...c.execution,status:"interrupted"},checks:c.checks.map(l=>l.status==="planned"||l.status==="running"?{...l,status:"interrupted"}:l)})})}catch{}throw s}let o=await Si(oe(e.paths,r.state.name));if(o===null)throw new Error("Native Runtime check state disappeared after execution");return{state:r.state,checks:Ua({local:o,projectRoot:e.paths.projectRoot,supplied:[]})}}async function lH(e){let t=oe(e.paths,e.state.name),i=e.local;if(i===null||i.change!==e.state.name||i.basedOnStateVersion!==e.state.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(i.execution.executionId!==null&&i.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(i.execution.requestCheckRounds>=Up)throw new Error(`Native Verifier request-checks exceeded ${Up} rounds for this attempt`);let r=new Map,n=new Map,a=new Map;for(let h of i.checks){let m=em(h,e.paths.projectRoot);n.set(m,h),h.status!=="interrupted"&&r.set(m,h),a.set(h.id,m)}let o=new Map,s=new Map;for(let h of e.response.checks){let m=aH(h);Lu(e.paths.projectRoot,m);let p=qs(m),v=s.get(m.id);if(v!==void 0&&v!==p)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let N=a.get(m.id);if(N!==void 0&&N!==p)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,p);let y=n.get(p);if(y?.status==="interrupted"&&!y.repeatable)throw new Error(`Native check ${y.id} was interrupted and is not repeatable; user resolution is required`);o.has(p)||o.set(p,m)}let c=[...o.entries()],l=c.filter(([h])=>!r.has(h));if(i.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=i.execution.requestCheckRounds+1,d=new Map(c.map(([,h])=>[h.id,h.name])),f={...i,execution:{...i.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...i.checks.map(h=>{let m=em(h,e.paths.projectRoot),p=o.get(m);return p&&h.status==="interrupted"?Ak(h,p,i.execution.operationId,e.paths.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>im(h,i.execution.operationId,e.paths.projectRoot))]};return await de(t,f,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:f,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,h])=>h),requestedNames:d,reusedCheckIds:c.filter(([h])=>r.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function Ku(e){return F(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await K(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 i=oe(e.paths,t.name),r=await Si(i),n=r?.execution;if(r===null||r.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(r);return await de(i,a,{containedRoot:e.paths.runtimeDir}),a})}async function uH(e){let t;try{for(let i of e.reservation.novelPlans){let r=new Date().toISOString();t=await Ku({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:r}:o)})});let n=await Wp({projectRoot:e.paths.projectRoot,runtimeDir:We(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:i});t=await Ku({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await Ku({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(i){try{await Ku({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,status:"interrupted"},checks:r.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw i}return{checks:Ua({local:t,projectRoot:e.paths.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:i})=>i)}}}async function jk(e){return F(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await Xr({paths:e.paths,state:t});let i=(await Zp({file:oe(e.paths,t.name),portableState:t,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot),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");Ua({local:i,projectRoot:e.paths.projectRoot,supplied:e.checks});let r=hk(t),n=await Nt({paths:e.paths,previous:t,next:r}),a=oe(e.paths,t.name),o=tm();return await de(a,{...i,basedOnStateVersion:n.state_version,execution:{operationId:o,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(s=>({...s,operationId:o}))},{containedRoot:e.paths.runtimeDir}),n})}async function $k(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await F(e.paths,`apply portable verifier ${e.name}`,async()=>{let i=await K(e.paths,e.name);await Xr({paths:e.paths,state:i});let r=await Ka({paths:e.paths,state:i}),n=oH({state:i,local:r,envelope:e.envelope}),a;try{a=Gp(n.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,f=await Yu({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${f.loop.execution_failure_count}/${zs} was recorded`,{cause:u})}let o=sH(a);if(o.iteration!==i.loop.iteration||o.attempt!==i.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let s=[],c;try{r!==null&&(s=Ua({local:r,projectRoot:e.paths.projectRoot,supplied:e.checks}));let u=pk({state:i,envelope:n,checks:s,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(r===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await lH({paths:e.paths,state:i,local:r,envelope:n,response:u.response,suppliedChecks:s});return{kind:"request-checks",state:i,response:u.response,reservation:d}}if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==n.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");c=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,f=await Yu({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${f.loop.execution_failure_count}/${zs} was recorded`,{cause:u})}let l=await Nt({paths:e.paths,previous:i,next:c.state});return await de(oe(e.paths,i.name),l.loop.next_action==="resolve-verifier-blocker"?Ks({local:r,state:l,projectRoot:e.paths.projectRoot}):Ge({portableState:l,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),l.verification!==null&&await fr({file:He.join(je(e.paths,i.name),"verification.md"),state:l}),{kind:"final-result",result:{state:l,response:c.response,checks:s,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let i=await uH({paths:e.paths,reservation:t.reservation});return{state:t.state,response:t.response,checks:i.checks,requestChecks:i.requestChecks}}catch(i){let r=`Native Verifier response was invalid: ${i.message}`,n=await F(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await K(e.paths,e.name);return a.state_version!==t.state.state_version?null:Yu({paths:e.paths,state:a,summary:r})});throw new Error(n?`${r}; execution error ${n.loop.execution_failure_count}/${zs} was recorded`:`${r}; the portable state changed before the execution error could be recorded`,{cause:i})}}async function Ok(e){return F(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await Ka({paths:e.paths,state:t});if(Tk({state:t,local:i,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 Yu({paths:e.paths,state:t,summary:e.summary})})}async function Hk(e){return F(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await Xr({paths:e.paths,state:t});let i=await Ka({paths:e.paths,state:t}),r=Tk({state:t,local:i,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=Ua({local:r,projectRoot:e.paths.projectRoot,supplied:[]}),a=vk({state:t,checks:n,verifierExecutionRef:r.execution.executionId,summary:e.summary}),o=await Nt({paths:e.paths,previous:t,next:a});return await de(oe(e.paths,t.name),Ks({local:r,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await fr({file:He.join(je(e.paths,t.name),"verification.md"),state:o}),o})}async function Dk(e){return F(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await K(e.paths,e.name);await Xr({paths:e.paths,state:t});let i=mk(t),r=await Nt({paths:e.paths,previous:t,next:i});return await de(oe(e.paths,t.name),Ge({portableState:r,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await fr({file:He.join(je(e.paths,t.name),"verification.md"),state:r}),r})}async function Fk(e){return F(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await Xr({paths:e.paths,state:t});let i=gk({state:t,summary:e.summary}),r=await Nt({paths:e.paths,previous:t,next:i});return await de(oe(e.paths,t.name),Ge({portableState:r,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await fr({file:He.join(je(e.paths,t.name),"verification.md"),state:r}),r})}async function Mk(e){return F(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await K(e.paths,e.name);await Xr({paths:e.paths,state:t});let i=await Ka({paths:e.paths,state:t}),r=wk(t),n=await Nt({paths:e.paths,previous:t,next:r});return await de(oe(e.paths,t.name),Ks({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Bk(e){return F(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await Ka({paths:e.paths,state:t}),r=Nk(t),n=await Nt({paths:e.paths,previous:t,next:r});return await de(oe(e.paths,t.name),Ks({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Ya(e){return F(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await K(e.paths,e.name);if(t.phase==="build")return t;let i=Js({state:t,reason:e.reason}),r=await Nt({paths:e.paths,previous:t,next:i});return await de(oe(e.paths,t.name),Ge({portableState:r,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r})}async function Lk(e){if(!Xu.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return F(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await K(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i=t.spec_changes.filter(({capability:a})=>a!==e.capability),r={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...i,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}},n=await Nt({paths:e.paths,previous:t,next:r});return await de(oe(e.paths,t.name),Ge({portableState:n,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function qk(e){return F(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let i={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},r=await Nt({paths:e.paths,previous:t,next:i});return r.verification!==null&&await fr({file:He.join(je(e.paths,t.name),"verification.md"),state:r}),r})}async function Vk(e){return F(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await K(e.paths,e.name);return t.phase==="shape"?t:Zu({paths:e.paths,state:t,reason:e.reason})})}async function Zu(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...ei(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ue(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:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}},n=await Nt({paths:e.paths,previous:t,next:r});return await de(oe(e.paths,t.name),Ge({portableState:n,projectRoot:e.paths.projectRoot,branch:Jt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function ed(e){if(e.state.verification===null)return"not-applicable";let t=He.join(je(e.paths,e.state.name),"verification.md");return await Us({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await fr({file:t,state:e.state}),"rebuilt")}async function Wk(e){let t=await K(e.paths,e.name),i=oe(e.paths,e.name);try{let r=await Si(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}import{randomUUID as dH}from"crypto";import{promises as Ys}from"fs";import Jk from"path";var rm="comet.selection.v2",fH=16*1024;function Xs(e){return Jk.join(e,".comet","current-change.json")}function hH(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zk(e){return e===null||typeof e=="string"}function Gk(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!hH(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!zk(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:rm,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==rm)throw new Error(`current change selection schema must be ${rm}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!zk(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function nm(e){let t;try{let r=Xs(e),{bytes:n}=await Cn(r,fH,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...Gk(t)}}async function Uk(e,t){let i=Gk(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=Xs(e),n=`${r}.${dH()}.tmp`;await Ys.mkdir(Jk.dirname(r),{recursive:!0});try{await Ys.writeFile(n,`${JSON.stringify(i.selection,null,2)}
|
|
261
|
-
`,"utf8"),await Ys.rename(n,r)}catch(a){throw await Ys.rm(n,{force:!0}),a}}async function Kk(e){await Ys.rm(Xs(e),{force:!0})}async function Yk(e,t,i){let r=await nm(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await Kk(e),!0)}var LG=16*1024;async function Qs(e){let t=await nm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(qn(t.selection.change),t.selection)}function Zs(e){return Xs(e.projectRoot)}async function td(e,t){return F(e,`select change ${t}`,async()=>{qn(t),await Ne(e,t)?await K(e,t):await Ie(e,t),await Uk(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Xk(e){let t=await Qs(e);return t?(await Ne(e,t.change)?await K(e,t.change):await Ie(e,t.change),t.change):null}async function ec(e,t){return await Ea(e.projectRoot),Yk(e.projectRoot,"native",t)}var tc=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function am(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function om(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=bt.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function id(e){try{return await et.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Qk(e,t){let i=bt.normalize(bt.resolve(e)),r=bt.normalize(bt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function Zk(e,t){let i;try{i=await et.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=bt.join(e.archiveDir,n.name);try{let o=await Zt(bt.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function sm(e,t){let i=await Ca(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function eS(e,t){return await sm(e,t)!==null||await Zk(e,t)!==null}async function Gn(e,t){await et.mkdir(e.transactionsDir,{recursive:!0}),await me(Mr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function tS(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Ti(e.paths.projectRoot);i.some(a=>Qk(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Y(a);if(!o)continue;let s=await ce(a,o.native.artifact_root);r.some(c=>Qk(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await et.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Zt(bt.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Vn(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function mH(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function vH(e){let t=bt.join(e.paths.specsDir,e.change.capability),i=bt.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await et.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await et.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([et.realpath(e.paths.specsDir),et.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await et.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await et.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await et.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=bt.join(je(e.paths,e.state.name),e.change.source);await we(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await et.mkdir(t,{recursive:!0}),await we(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function cm(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function gH(e,t){let i=je(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await ne({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function wH(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(cm(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function lm(e){let t=await K(e.paths,e.name),i=[];try{cm(t)}catch(o){i.push(o.message)}if(await sm(e.paths,e.name)===null)try{let o=await Qu({paths:e.paths,state:t});o.drifted&&i.push(o.reason??"Native confirmed requirements changed")}catch(o){i.push(o.message)}let n=t.verification===null?"missing":await Us({file:bt.join(je(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await tS({paths:e.paths,state:t});return a.length>0&&i.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:i.length===0,blockers:i,capabilityPeers:a,archiveDir:om(e.paths,am(t)),stateVersion:t.state_version}}async function ic(e){return F(e.paths,`archive portable change ${e.name}`,async()=>{let t=mH(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await sm(e.paths,e.name),r=je(e.paths,e.name),n=await id(r),a=n?null:await Zk(e.paths,e.name),o;if(n)o=await K(e.paths,e.name);else if(i)o=await Zt(bt.join(om(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await Qu({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await Zu({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=om(e.paths,i?.archive_ref??am(o)),c=await id(s);if(i&&wH(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await ec(e.paths,o.name),await et.rm(We(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)cm(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await tS({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new tc(l);i={schema:lu,id:pH(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:am(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await gH(e.paths,o),created_at:new Date().toISOString()},await Gn(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await Gn(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await vH({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await Gn(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await Gn(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await $n({file:jt(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await Gn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await id(r)?r:s;if(await fr({file:bt.join(l,"verification.md"),state:o}),await Us({file:bt.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await Gn(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await et.mkdir(e.paths.archiveDir,{recursive:!0}),await id(s))throw new Error(`Native Archive target already exists: ${s}`);await et.rename(r,s),i={...i,status:"moved"},await Gn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await ec(e.paths,o.name),await et.rm(We(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await et.rm(Mr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function re(e){let t={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},i=r=>({kind:r,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...t,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:i("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...t,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...t,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...t,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...t,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:{...t,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:i("none")};if(e.status==="blocked"){let r=e.blockers.some(({resolution_action:n})=>n==="retry-verifier");return{...t,disposition:"blocked",action:r?"retry-verifier":"none",commandArgs:r?["comet","native","next",e.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:r?["summary"]:["repair-runtime"],inputOptions:r?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:i(r?"retry-verifier":"none")}}if(e.phase==="shape")return{...t,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")};if(e.phase==="build")return{...t,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}],known_limits:[]}}],runnerAction:i("builder-handoff")};if(e.phase==="verify"){let r=e.loop.next_action==="await-verifier-result";return{...t,disposition:"continue",action:r?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[r?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:r?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|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:"<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:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:i(r?"await-verifier":"dispatch-verifier")}}return{...t,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:i("none")}}import{randomUUID as yH}from"node:crypto";import{promises as Xa}from"node:fs";import cS from"node:path";var lS=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function NH(e){try{return await Xa.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function um(e,t){let i=ee(e,t),r=[Mr(e,{kind:"migration",change:t}),_n(e,t),...lS.map(n=>cS.join(i,n))];return(await Promise.all(r.map(NH))).some(Boolean)}async function bH(e,t){let i=await Ca(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function iS(e,t){await Xa.mkdir(e.transactionsDir,{recursive:!0}),await me(Mr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function rS(e,t){await Promise.all([Xa.rm(We(e,t),{recursive:!0,force:!0}),Xa.rm(_n(e,t),{recursive:!0,force:!0}),...lS.map(i=>Xa.rm(cS.join(ee(e,t),i),{force:!0}))])}async function nS(e,t){await de(oe(e,t.name),Ge({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function aS(e,t){try{let i=await lt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function oS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=pe(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function kH(e){let t=ee(e.paths,e.state.name),i=await ne({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await ne({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return iu({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function sS(e,t){let i=await Vn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Ei(e){return F(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await bH(e.paths,e.name),i=await Ne(e.paths,e.name)?await Zt(jt(e.paths,e.name)):null;if(!t&&i)return await rS(e.paths,e.name),await nS(e.paths,i),i;let r=null,n=null;for(t||(r=await sS(e.paths,e.name),n=await aS(e.paths,e.name),oS(e.paths,n),t={schema:cu,id:yH(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await iS(e.paths,t));;){let a=CN(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await sS(e.paths,e.name),n??=await aS(e.paths,e.name),oS(e.paths,n),i=xN({state:r,acceptance:await kH({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await bs(jt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await rS(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Zt(jt(e.paths,e.name)),await nS(e.paths,i)),t={...t,status:a.nextStatus},await iS(e.paths,t)}return await Xa.rm(Mr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Zt(jt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as uS}from"node:fs";import dS from"node:path";function SH(e,t){let i=pe(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function EH(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function PH(e,t){let i=new Date().toISOString(),r=e.verification===null?e:ei(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ue(t),completed_at:i});return X({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:EH(e),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 RH(e){try{let t=await Si(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 Un(e){return F(e.paths,`recover portable change ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.status==="done")return await ed({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 i=SH(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=oe(e.paths,e.name),n=await RH(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await de(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await ed({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=Js({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await $n({file:jt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await uS.rm(dS.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Ge({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await de(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=PH(t,l?"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.");t=await $n({file:jt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=Ge({portableState:t,projectRoot:e.paths.projectRoot,branch:pe(e.paths.projectRoot).currentBranch});return await uS.mkdir(dS.dirname(oe(e.paths,t.name)),{recursive:!0}),await de(r,d,{containedRoot:e.paths.runtimeDir}),await ed({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"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{promises as HH}from"node:fs";import Qa from"node:path";import{execFileSync as xH}from"node:child_process";var CH=6e4,AH=8*1024*1024,dm=class extends Error{constructor(i,r,n,a){super(`${i} ${r.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=i;this.args=r;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function fm(e,t,i={}){let r=i.timeoutMs??CH,n=i.maxBufferBytes??AH;if(!Number.isSafeInteger(r)||r<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");try{return xH(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r,maxBuffer:n,windowsHide:!0,shell:!1})}catch(a){let o=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new dm(e,t,o,{cause:a})}}import{execFileSync as _H}from"node:child_process";var TH=3e4,IH=8*1024*1024,hm=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function fS(e,t){try{return _H("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:TH,maxBuffer:IH,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new hm(e,t,r)}}function xe(e,t){return fS(e,t).trim()}function rc(e){return xe(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function pm(e,t){xe(e,["check-ref-format","--branch",t])}function mm(e){let t=fS(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;n<i.length;n+=1){let a=i[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(r.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=i[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");r.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(r)].sort()}function hS(e,t){try{let r=xe(e,["config","--get",`branch.${t}.remote`]);if(r&&r!==".")return r}catch{}let i=xe(e,["remote"]).split(/\r?\n/u).map(r=>r.trim()).filter(Boolean);if(i.includes("origin"))return"origin";if(i.length===1)return i[0];throw new Error(i.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${i.join(", ")}`)}import{promises as vm}from"fs";import pS from"path";var mS=["Outcome","Scope","Non-goals","Acceptance examples"],jH=[...mS,"Constraints and invariants","Decisions","Open questions","Verification expectations"],$H=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],vS={maxFileBytes:Ro};function gS(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
262
|
-
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function OH(e,t){let i=pS.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await vm.realpath(e),n=await vm.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await vm.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function nc(e){return{valid:e.length===0,findings:e}}async function gm(e,t){let i=[],r;try{r=(await ne({root:e,ref:t,maxBytes:vS.maxFileBytes})).text}catch(o){return nc([{code:"brief-missing",message:o.message,path:t}])}let n=gS(r);for(let o of jH)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of mS)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),nc(i)}async function wm(e,t){let i=[],r;try{r=(await ne({root:e,ref:t,maxBytes:vS.maxFileBytes})).text}catch(a){return nc([{code:"verification-missing",message:a.message,path:t}])}let n=gS(r);for(let a of $H)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return nc(i)}function Kn(e,t){return pS.join(e.specsDir,t,"spec.md")}async function wS(e,t){let i=[],r=ee(e,t.name);for(let n of t.spec_changes){let a=Kn(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await ri(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await OH(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return nc(i)}var ac=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function DH(e,t){let i=Qa.relative(e,t);return i===""||!Qa.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qa.sep}`)}function Yn(e,t){let i=Qa.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||Qa.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function yS(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function FH(e){try{if(xe(e,["config","--get","user.name"])&&xe(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function MH(e,t){for(let i of Ti(e))if(pe(i).currentBranch===t)return i;return null}function BH(e,t){try{fm(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function ym(e){let{paths:t,state:i}=e,r=i.workspace;if(r.isolation==="current")return null;if(!r.finish||!r.change_branch||!r.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(r.change_branch===r.target_branch)throw new Error("Native change and target branches must be different for workspace finish");let n=pe(t.projectRoot);if(!n.primaryWorktreeRoot||n.currentBranch!==r.change_branch)throw new Error(`Native workspace finish requires branch ${r.change_branch} in the current registered worktree`);FH(t.projectRoot);let a=[Yn(t.projectRoot,Zs(t))];e.archiveDir&&a.push(Yn(t.projectRoot,ee(t,i.name)),Yn(t.projectRoot,e.archiveDir));let o=mm(t.projectRoot).filter(l=>!yS(l,a));if(o.length>0)throw new Error(`Native workspace finish is blocked until change-owned implementation and artifacts are committed; remaining paths: ${o.slice(0,20).join(", ")}${o.length>20?", ...":""}`);let s=r.isolation==="branch"?t.projectRoot:MH(n.primaryWorktreeRoot,r.target_branch);if(r.finish==="merge"&&r.isolation==="worktree"){if(!s)throw new Error(`Native merge finish requires a registered worktree on target branch ${r.target_branch}`);if(!rc(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?hS(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&BH("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function LH(e,t){try{return fm("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function qH(e){try{return await HH.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function VH(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function NS(e){let t=VH(e.plan),i=null;try{let r=[Yn(e.paths.projectRoot,ee(e.paths,e.name)),Yn(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(c=>Yn(e.paths.projectRoot,Kn(e.paths,c.capability))),Yn(e.paths.projectRoot,Zs(e.paths))],n=mm(e.plan.changeRoot).filter(c=>!yS(c,r));if(n.length>0)throw new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.slice(0,20).join(", ")}${n.length>20?", ...":""}`);let a=[];for(let c of r){let l=Qa.resolve(e.paths.projectRoot,...c.split("/")),u=xe(e.plan.changeRoot,["ls-files","--",c])!=="";(await qH(l)||u)&&a.push(c)}if(a.length>0&&xe(e.plan.changeRoot,["add","-A","--",...a]),xe(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&xe(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=xe(e.plan.changeRoot,["rev-parse","HEAD"]),!rc(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){if(xe(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=LH(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(l=>/^https?:\/\//u.test(l.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let c=DH(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!c?(xe(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let s=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(xe(s,["switch",e.plan.targetBranch]),i=s),xe(s,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=s,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(i!==null){let n;try{xe(i,["merge","--abort"])}catch{}try{pe(i).currentBranch===e.plan.targetBranch&&xe(i,["switch",e.plan.changeBranch]),n=pe(i).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=i)}throw t.status="blocked",t.message=r.message,t.recoveryArgs=e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new ac(t)}}import bv from"path";import{promises as EP}from"fs";import vo from"path";import{isDeepStrictEqual as pB}from"util";import{createHash as WH}from"crypto";function bS(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function kS(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))kS(e[t]);return Object.freeze(e)}function Qr(e){return kS(structuredClone(e))}function Nm(e,t,i,r){return e.resolveStep({pkg:Qr(t),state:Qr(i),context:Qr(r)})}function SS(e,t,i,r,n,a){return e.resolveNext({pkg:Qr(t),state:Qr(i),step:Qr(r),outcome:Qr(n),context:Qr(a)})}function zH(e,t,i){return WH("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function bm(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function ES(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Nm(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=bm(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:zH(s.runId,s.iteration,o.id),stepId:o.id};return JH(e,s,c,i)}function JH(e,t,i,r){let n=bS(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function PS(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Nm(r,e,t,n):void 0,o=a?bm(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?SS(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!bm(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as qM}from"node:fs";import lP from"node:path";import RS from"node:path";var GH="comet.native.archive-preflight.v1",UH="comet.native.archive-preflight.v1",KH="comet.native.archive-operation.v1",YH=/^[a-f0-9]{64}$/u,xS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function rd(e,t){return e<t?-1:e>t?1:0}function QH(e,t){if(typeof e!="string"||!YH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hr(e,t){return e===null?null:QH(e,t)}function ZH(e,t){let i=RS.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||RS.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function eD(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function tD(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function iD(e,t){if(!xS.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=hr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=hr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=hr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function rD(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:hr(e.contractHash,"Native archive contract hash"),acceptanceHash:hr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:hr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:hr(e.reportHash,"Native archive report hash"),envelopeHash:hr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:hr(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function nD(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!XH.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(rd);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function aD(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(rd)}function CS(e){if(!xS.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(iD).sort((l,u)=>rd(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:M(KH,l)})),r=rD(e.evidence),n=tD(e.workspace),a=[...new Set([...nD(e.findingCodes??[]),...aD({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(rd),o=eD(e.revision),s=ZH(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:GH,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:M(UH,c)}}import{createHash as oD}from"node:crypto";import AS from"node:path";var sD="comet.native.conflict-radar.v1",$t=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}),cD="comet.native.conflict-radar.v1",lD="comet.native.conflict-radar-signals.v1",uD=/^[a-f0-9]{64}$/u,IS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dD=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),fD=new Set(["capability","operation","baseHash"]),hD=new Set(["path","kind"]);function Za(e,t){return e<t?-1:e>t?1:0}function km(e){return Buffer.byteLength(e,"utf8")}function Sm(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Em(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(km(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function pD(e,t){let i=Em(e,t,$t.maxArtifactPathBytes),r=AS.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||AS.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function jS(e,t){if(typeof e!="string"||!uD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mD(e,t){let i=Sm(e,fD,t),r=Em(i.capability,`${t} capability`,$t.maxCapabilityBytes);if(!IS.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:jS(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function vD(e,t){let i=Sm(e,hD,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:pD(i.path,`${t} path`),kind:i.kind}}function gD(e,t){let i=Sm(e,dD,`Conflict radar change ${t}`),r=Em(i.name,`Conflict radar change ${t} name`,$t.maxNameBytes);if(!IS.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>$t.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>$t.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>mD(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>Za(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>vD(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>Za(c.path,l.path)||Za(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:jS(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function wD(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>$t.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(gD).sort((n,a)=>Za(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>$t.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>$t.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function yD(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function ND(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function bD(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function kD(e,t){let i=[],r=oD("sha256").update(`${lD}
|
|
263
|
-
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(
|
|
264
|
-
`,"utf8")}function
|
|
265
|
-
${
|
|
266
|
-
`),e.omissionOverflow&&
|
|
267
|
-
`);let i=0;_m(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Zr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)uc(o,n.path)&&(a+=1,Zr(t,"change-attribution",o));Zr(t,"change-end",{attributionCount:a}),a===0&&Zr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Zr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function XS(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=FD(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(P=>!w.has(P)||n.some(z=>uc(z,P)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=M(oc,e),c=M(oc,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=CD)break;l.push(pr({kind:"snapshot-omission",source:R,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${R} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...DS("baseline",e),...DS("current",t),...o.totalChanges===0&&a===null?[pr({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(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>R.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!R.has(w))}},m=R=>{let w=o.candidates.slice(0,R.detailedChangeCount),g=w.filter(fi=>fi.attributedTo.length===0&&!u.has(fi.path)),P=o.totalChanges-w.length,z=o.totalUnattributed-g.length,H=d-R.detailedOmissionCount,rt=z+H,Se=[...g.map(fi=>pr({kind:"unattributed-change",source:"implementation-scope",path:fi.path,evidence:{after:fi.after,before:fi.before,changeKind:fi.kind}},`Changed path is not covered by a declared artifact: ${fi.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...rt>0?[YS(R.overflowHash,{changes:P,unattributed:z,unresolved:rt})]:[]],fe=HD(Se),_i=R.includeGitAdvisory?h():void 0;return{schema:Pm,contractHash:r,baselineProjectionRef:Rm(s),baselineProjectionHash:s,currentProjectionRef:Rm(c),currentProjectionHash:c,complete:fe.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:fe,noCodeReason:a,..._i?{gitAdvisory:_i}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},p=o.candidates.length,v=l.length,N=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:N,overflowHash:y});if(cc({...R,scopeHash:y})<=Qn)break;if(N){N=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let E=o.totalChanges>p||d>v?BD({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:v}):y,k=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:N,overflowHash:E}),b={...k,scopeHash:M(WS,k)};if(cc(b)>Qn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Im(e){let t=xm(e.baseline),i=xm(e.current),r=KS(e);return{authority:r,baseline:t,current:i,scope:XS(t,i,r)}}var LD=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function zi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ji(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Xn(e,t){if(typeof e!="string"||!Am.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MS(e,t,i){let r=Rm(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function to(e,t){let i=zi(e,"Native snapshot projection");if(Ji(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==VS)throw new Error("Native snapshot projection schema is invalid");let r=cr({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=xm(r);if(M(oc,i)!==M(oc,n))throw new Error("Native snapshot projection is not canonical");let a=M(oc,n);if(t!==void 0&&Xn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function jm(e,t){let i=zi(e,`Declared artifact ${t}`);if(Ji(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:en(i.path,`Declared artifact ${t} path`),kind:i.kind}}function BS(e,t){if(e===null)return null;let i=zi(e,t);return Ji(i,["hash","size"],[],t),{hash:Xn(i.hash,`${t} hash`),size:eo(i.size,`${t} size`)}}function LS(e,t){let i=zi(e,`Implementation change ${t}`);if(Ji(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(jm),n=lc(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=BS(i.before,`Implementation change ${t} before`),o=BS(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.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:en(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function qD(e,t){let i=zi(e,`Unresolved scope ${t}`);Ji(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?zS(i.path,`Unresolved scope ${t} path`):en(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function sc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>en(n,`${t} ${a}`)),r=[...new Set(i)].sort(dt);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function QS(e){let t=zi(e,"Native implementation external drift");if(Ji(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=sc(t.paths,"Native external drift paths");return US({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function io(e){let t=zi(e,"Native implementation scope"),i=[...LD].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(Ji(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Pm)throw new Error("Native implementation scope schema is invalid");let r=Xn(t.contractHash,"Implementation scope contractHash"),n=Xn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=MS(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Xn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=MS(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(jm);if(JSON.stringify(c)!==JSON.stringify(lc(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(LS),u=[...l].sort((g,P)=>dt(g.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(g=>g.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(g=>`${g.kind}:${g.path}`));if(l.some(g=>g.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(P=>uc(P,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(LS),h=t.externalDrift===void 0?void 0:QS(t.externalDrift),m=new Set(h?.paths??[]),p=l.filter(g=>g.attributedTo.length===0&&!m.has(g.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(qD),N=v.filter(g=>g.kind==="scope-detail-overflow");if(N.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=N[0]===void 0?null:MD(N[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,E=[...p.map(g=>pr({kind:"unattributed-change",source:"implementation-scope",path:g.path,evidence:{after:g.after,before:g.before,changeKind:g.kind}},`Changed path is not covered by a declared artifact: ${g.path}`)),...l.length+(y?.changes??0)===0&&S===null?[pr({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")]:[]],k=v.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(Cm))||new Set(v.map(g=>g.id)).size!==v.length||JSON.stringify(k)!==JSON.stringify(E.sort(Cm))||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 g=zi(t.gitAdvisory,"Implementation scope Git advisory");if(Ji(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=sc(g.changedPaths,"Git changed paths"),z=sc(g.pathsPresentInSnapshotChanges,"Git present paths"),H=sc(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),rt=[...z,...H].sort(dt);if(JSON.stringify(rt)!==JSON.stringify(P)||H.some(Se=>l.some(fe=>fe.path===Se)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:z,pathsAbsentFromSnapshotChanges:H}}let R={schema:Pm,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:S,...b?{gitAdvisory:b}:{},...h?{externalDrift:h}:{}},w=Xn(t.scopeHash,"Implementation scope scopeHash");if(M(WS,R)!==w)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:w}}function VD(e){let t=zi(e,"Native implementation scope authority");if(Ji(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 i=t.declaredArtifacts.map(jm);if(JSON.stringify(i)!==JSON.stringify(lc(i)))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 r;t.gitChangedPaths!==void 0&&(r=sc(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:QS(t.externalDrift),a=KS({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...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 dc(e){let t=zi(e,"Native implementation scope bundle");Ji(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=VD(t.authority),r=to(t.baseline),n=to(t.current),a=io(t.scope),o=XS(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function ZS(e){let t=io(e.scope);return dc({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})}import eE from"node:path";var iE=/^[a-f0-9]{64}$/u;var WD="comet.native.acceptance-trace.v2",zD="comet.native.partial-allowance.v1",JD="comet.native.verification-evidence.v2";function mr(e,t){if(!iE.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function nE(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 $m(e,t,i=2e3){let r=yt(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function fc(e,t){let i=eE.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||eE.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function GD(e,t,i){let r=fc(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=Ii(r),a=r.toLowerCase(),o=i?fc(i,"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"}): ${r}`);return r}function Om(e){let t=fc(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 ro(e,t){return e<t?-1:e>t?1:0}function nd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ad(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function aE(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function tE(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function UD(e){let t=nd(e,"Native acceptance trace");if(ad(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"||!iE.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 i=fc(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=nd(o,`Native acceptance trace entry ${s}`);if(ad(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=>Om(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ro))||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:fc(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:$m(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>ro(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=mr(t.traceHash,"Native acceptance trace hash");if(M(WD,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function od(e){let t=nd(e,"Native partial allowance");if(ad(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(ro))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:nE(t.change),scopeHash:mr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:$m(t.reason,"Partial allowance reason"),confirmedSummary:$m(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:rE(t.sourceRevision),confirmedAt:aE(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=mr(t.allowanceHash,"Native partial allowance hash");if(M(zD,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function hc(e){let t=nd(e,"Native verification evidence");if(ad(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 i=mr(t.implementationScopeHash,"Native verification implementation scope hash"),r=UD(t.acceptanceTrace),n=mr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.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(f=>Om(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ro)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(ro);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Om(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ro)))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:nE(t.change),sourceRevision:rE(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:mr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:tE(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:GD(t.reportRef,"Native verification report ref"),reportHash:mr(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:tE(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:aE(t.createdAt,"Native verification timestamp")},d=mr(t.envelopeHash,"Native verification envelope hash");if(M(JD,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import oE from"node:path";var sE="comet.native.check-receipt.v1",KD="comet.native.check-receipt.v1",no="scoped-text-safety",Hm=1,Ot=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),YD=/^[a-f0-9]{64}$/u,XD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QD="comet.native.checker-policy.v1",ZD="comet.native.check-input.v1",eF=2048,cE=M(QD,{policy:no,version:Hm,limits:Ot,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),tF=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),lE=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],dE=["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"],iF=new Set(dE);function tn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function rn(e,t,i,r=[]){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 vr(e,t){if(typeof e!="string"||!YD.test(e))throw new Error(`${t} must be a SHA-256 hash`);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 fE(e,t){let i=Gt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function uE(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function rF(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>eF||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=oE.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||oE.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function nF(e){let t=tn(e,"Native check receipt checker");rn(t,["policy","version","hash","limits"],"Native check receipt checker");let i=tn(t.limits,"Native check receipt limits");if(rn(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==no||t.version!==Hm||t.hash!==cE||i.maxFiles!==Ot.maxFiles||i.maxFileBytes!==Ot.maxFileBytes||i.maxTotalBytes!==Ot.maxTotalBytes||i.maxIssues!==Ot.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:no,version:Hm,hash:cE,limits:{...Ot}}}function aF(e){let t=tn(e,"Native check receipt contract");return rn(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:vr(t.expectedHash,"Native check expected contract hash"),beforeHash:vr(t.beforeHash,"Native check before contract hash"),afterHash:vr(t.afterHash,"Native check after contract hash")}}function oF(e){let t=tn(e,"Native check receipt implementation");return rn(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:vr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:vr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:vr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:vr(t.afterSnapshotHash,"Native check after snapshot hash")}}function sF(e,t){let i=tn(e,`Native check batch ${t}`);rn(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Gt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Gt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Gt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Gt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Gt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Gt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Ot.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Ot.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function cF(e){let t=tn(e,"Native check receipt counts");rn(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Gt(t.filesSelected,"Native check filesSelected"),filesScanned:Gt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Gt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Gt(t.bytesScanned,"Native check bytesScanned"),issueCount:Gt(t.issueCount,"Native check issueCount"),recordedIssueCount:Gt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(sF):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Ot.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Ot.maxFiles||i.bytesScanned>Ot.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function lF(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||lE.indexOf(e.kind)-lE.indexOf(t.kind)}function uF(e){if(!Array.isArray(e)||e.length>Ot.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=tn(r,`Native check issue ${n}`);if(rn(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!tF.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:rF(a.path,`Native check issue ${n} path`),line:fE(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(lF);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function dF(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!iF.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=dE.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function fF(e){return M(ZD,e)}function sd(e){let t=tn(e,"Native check receipt");if(rn(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==sE)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!XD.test(t.change))throw new Error("Native check receipt change name is invalid");let i=fE(t.sourceRevision,"Native check source revision"),r=nF(t.checker),n=aF(t.contract),a=oF(t.implementation),o=fF({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(vr(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=uE(t.startedAt,"Native check receipt startedAt"),c=uE(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=cF(t.counts),u=uF(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=dF(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Ot.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Ot.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:sE,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=vr(t.receiptHash,"Native check receipt content hash");if(M(KD,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}var Fm="comet.native.verification-receipt.v3",hF=Fm,pF="comet.native.declared-artifacts.v1",mF=/^[a-f0-9]{64}$/u,vF=/^acceptance-[a-f0-9]{64}$/u,gF=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wF=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,yF=4096,NF=256,bF=1024;function ao(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function nn(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function gr(e,t){if(typeof e!="string"||!mF.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Pi(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=yt(e).trim();if(!i||i.length>yF||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Dm(e,t){let i=Pi(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function pc(e,t,i=Pi,r=!1,n=NF){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function kF(e,t){if(typeof e!="string"||!vF.test(e))throw new Error(`${t} is invalid`);return e}function SF(e){let t=ao(e,"Native verification receipt bindings");if(nn(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!gF.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:gr(t.contractHash,"Native verification receipt contract hash"),scopeHash:gr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:gr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:gr(t.artifactHash,"Native verification receipt artifact hash")}}function EF(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=wF.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function PF(e,t,i,r){let n=ao(t,`Native ${e} evidence`);if(e==="automated-check"){if(nn(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=Dm(n.startedAt,"Native automated-check start time"),o=Dm(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(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=ao(n.worktree,"Native automated-check worktree");if(nn(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=ao(n.afterFence,"Native automated-check after fence");if(nn(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Pi(n.executable,"Native automated-check executable"),args:pc(n.args,"Native automated-check arguments",Pi,!0),cwd:Pi(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:Pi(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:gr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:gr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:gr(n.outputHash,"Native automated-check output hash"),outputSummary:Pi(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){nn(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=EF(n.checkReceiptRef);if(gr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:pc(n.subjects,"Native static inspection subjects",Pi,r==="required-check"),rule:Pi(n.rule,"Native static inspection rule"),resultSummary:Pi(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return nn(n,["steps","observations"],"Native manual-evidence evidence"),{steps:pc(n.steps,"Native manual evidence steps"),observations:pc(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function RF(e){let t=ao(e,"Native verification receipt");if(nn(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 i=t.kind,r=t.role,n=t.status,a=Pi(t.actor,"Native verification receipt actor"),o=pc(t.acceptanceIds,"Native receipt acceptance IDs",kF,r==="required-check",bF).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Fm,kind:i,role:r,status:n,bindings:SF(t.bindings),acceptanceIds:o,actor:a,issuedAt:Dm(t.issuedAt,"Native verification receipt issue time"),evidence:PF(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==no||s.actor!==`native-runtime:${no}`))throw new Error("Native required check policy identity is invalid");return s}function cd(e){let t=ao(e,"Native verification receipt");if(nn(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Fm)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=RF(r),a=gr(t.receiptHash,"Native verification receipt hash");if(M(hF,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Mm(e){return M(pF,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var vE=/^[a-f0-9]{64}$/u,an=Qn,LK=3*an;function Bm(e,t){let i=Gi.relative(e,t);return i===""||!Gi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Gi.sep}`)}function CF(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ld(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?L(i,r):L(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function hE(e){let t=await Ri.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Ri.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function AF(e,t){let i=Gi.resolve(e),r=Gi.resolve(t);if(!Bm(i,r))throw new Error("Native evidence path is outside its change");let n=[await hE(i)],a=i;for(let o of Gi.relative(i,r).split(Gi.sep).filter(Boolean)){a=Gi.join(a,o);let s=await hE(a);if(!Bm(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function pE(e){for(let t of e){let i=await Ri.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!CF(t,i)||await Ri.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function _F(e,t,i={}){let r=await AF(t,Gi.dirname(e));await i.afterParentChainCaptured?.();let n=await Ri.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Ri.realpath(e);if(!Bm(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Ri.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Ri.lstat(e),Ri.realpath(e)]);if(await pE(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ld(s,n)||!ld(s,c))throw new Error("Native evidence document changed while opening");if(s.size>an)throw new Error(`Native evidence document exceeds ${an} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=an+1-d,N=await o.read(f,0,Math.min(f.length,v),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>an)throw new Error(`Native evidence document exceeds ${an} bytes`);u.push(Buffer.from(f.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),Ri.lstat(e),Ri.realpath(e)]);if(await pE(r),!m.isFile()||m.isSymbolicLink()||p!==a||!ld(s,h)||!ld(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function so(e,t){if(!vE.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function gE(e){return so("reports",e)}async function TF(e,t,i,r,n){if(!vE.test(i))throw new Error("Native report evidence hash is invalid");let a=await Zn({paths:e,name:t,kind:"reports",hash:i,hooks:r,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!==i||typeof o.content!="string"||xF("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function oo(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function IF(e,t,i,r,n){let a=so(i,r);return n?Gi.join(n,...a.split("/")):Dr(D(e,t),a)}async function Zn(e){let t=IF(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),_F(t,i,e.hooks)}function mE(e,t){return to(e,t)}function jF(e,t){let i=io(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function $F(e,t,i){let r=od(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function OF(e,t,i){let r=hc(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function HF(e,t,i,r=!1,n){let a=await ud(e,t,i.implementationScopeRef,void 0,n);if(r&&await TF(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await wE(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function mc(e,t,i,r,n){let a=oo(i,"scopes"),o=jF(await Zn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=oo(o.baselineProjectionRef,"snapshots"),c=oo(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Zn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>mE(d,s)),Zn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>mE(d,c))]);return ZS({baseline:l,current:u,scope:o})}async function ud(e,t,i,r,n){return(await mc(e,t,i,r,n)).scope}async function wE(e,t,i,r,n){let a=oo(i,"allowances");return $F(await Zn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function vc(e,t,i,r,n){let a=oo(i,"receipts"),o=cd(await Zn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function co(e,t,i,r,n){let a=oo(i,"verifications"),o=OF(await Zn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await HF(e,t,o,!1,n),o}var DF=4096;async function FF(e,t=$t.maxChanges){try{let i=await Tt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function yE(e,t){let i=await Ie(e,t),[r,n]=await Promise.all([i.implementation_scope?ud(e,t,i.implementation_scope):null,lt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function dd(e,t,i={}){let n=(await FF(e,DF)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await yE(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await yE(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=$S([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as tM}from"fs";import iM from"path";import{isDeepStrictEqual as pd}from"util";var lo={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var MF=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function BF(e,t){return e<t?-1:e>t?1:0}function LF(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!MF.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(BF)}function Lm(e=[]){return LF(e,"Native repair failed check IDs",lo.maxFailedCheckIds,!0)}function NE(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function qF(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:NE(e.failedAcceptanceIds,t.failedAcceptanceIds)&&NE(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function qm(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(qF(r,a))break;i+=1,r=a}return i}function fd(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var bE="repairStagnation",Ut={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},WF=/^[a-f0-9]{64}$/u;var zF=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),JF=["data","runId","sequence","timestamp","type"],kE=["disposition","overrideSummaryHash","signatureHash"],GF=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],SE=12;function Wm(e,t){return e<t?-1:e>t?1:0}function EE(e,t,i){let r=Object.keys(e).sort(Wm);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function hd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function gc(e,t){if(typeof e!="string"||!WF.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function UF(e){if(!Array.isArray(e)||e.length>lo.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Wm)}function PE(e){if(typeof e!="string"||e.length===0||e.length>Ut.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Vm(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Ut.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ut.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Ut.maxTextCharacters&&(!n||e.length>Ut.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Ut.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Ut.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Vm(s,t+1,i,`${r}[${c}]`));return}let a=hd(e,r),o=Object.keys(a);if(o.length>Ut.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ut.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Ut.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Vm(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function KF(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function YF(e,t,i){let r=hd(e,`Native repair trajectory event ${t+1}`);if(EE(r,JF,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(KF(r.timestamp),typeof r.type!="string"||!zF.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(PE(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Vm(r.data,0,n,"Native trajectory event data"),hd(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function zm(e){let t=hd(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Wm),r=i.length===kE.length&&i.every((l,u)=>l===kE[u]);r||EE(t,GF,"Native repair trajectory projection");let n=gc(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:gc(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=gc(t.contractHash,"Native repair trajectory contract hash"),s=UF(t.failedAcceptanceIds),c=Lm(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function XF(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function QF(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??SE;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=qm({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<lo.warningAtConsecutiveFailures?"continue":a<lo.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function ZF(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??SE;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function RE(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ut.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=PE(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=YF(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ut.maxTotalDataNodes||c>Ut.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?gc(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?gc(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,bE)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=zm(f[bE]);if(XF(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),QF(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");ZF(m,i,r);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(r=m,i.length>lo.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function xE(e){return RE(e).history}function CE(e){let t=RE(e).latestProjection;return t?{...t}:null}var Ui={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:[]},wc=B("comet-native-runtime:v3:scope-reopen"),eM=[{skillVersion:"3",skillHash:B("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:B("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:B("comet-native-runtime:v1")}];function AE(e){return e.skillVersion===Ui.definition.metadata.version&&e.skillHash===wc||eM.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Jm={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function on(e){let i={sequence:(await wt(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Tb(e.changeDir,e.run.trajectoryRef,i),i}async function ea(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:B(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Ib(e.changeDir,e.run.checkpointRef,t),t}function _E(e){return B(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var FE=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],rM=new Set(FE),ME=new Set([...FE,"minimum_runtime_version","revision"]),nM=new Set([...ME,"operation"]),aM=512*1024,Gm=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),oM=new Set([...Gm,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),yc=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ft(e,t){return iM.join(D(e,t),"transition.json")}function sM(e){return`transition-${e}`}async function cM(e,t,i){let r=sM(t);return nr(e,r,i)}async function sn(e,t,i,r){let n=await cM(e,t,i);try{return await r()}finally{await ar(n)}}function vd(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Km(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function md(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ki(e,t){return pd(e,t)}function Um(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!oM.has(u)),a=[...Gm].find(u=>!Object.hasOwn(i,u)),o=Gm.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(fd(i.summary,"Native transition journal event summary"),yt(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(fd(i.noCodeReason,"Native transition journal event no-code reason"),yt(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?zm(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function lM(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Um({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Um(e,t)}function Ym(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?lM(e.eventData,e.evidenceHash):Um(e.eventData,e.evidenceHash),n=Ur(e.nextRun),a=e.previousRun===null?null:Ur(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function TE(e,t,i=!1){if(e.skill!==Ui.definition.metadata.name||(i?!AE(e):e.skillVersion!==Ui.definition.metadata.version||e.skillHash!==wc)||e.orchestration!==Ui.definition.orchestration.mode||e.pendingRef!==qt.pendingRef||e.trajectoryRef!==qt.trajectoryRef||e.contextRef!==qt.contextRef||e.artifactsRef!==qt.artifactsRef||e.checkpointRef!==qt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function IE(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function jE(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Xm(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(TE(o,"next Run",r||a!==null),jE(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(TE(a,"previous Run",!0),jE(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!pd(IE(a),IE(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function uM(e,t,i){return B(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function BE(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function $E(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Qm(e,t,i,r,n=!1){let a=i.eventData,o=$E(e),s=$E(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&pd(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&pd(e.spec_changes,t.spec_changes),l=_E({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=uM(e.name,a.summary,t.spec_changes),l=B(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Zm(e,t){let i=vd(e);if(Km(i,nM),i.schema!==Fr)throw new Error(`Expected Native transition schema ${Fr}`);let r=md(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${Fr} minimum_runtime_version must be ${3}`);let n=md(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Ym(i,t),o=_t(i.previousState),s=_t(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Qm(o,s,a,i.operation),Xm(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Fr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function dM(e,t){let i=vd(e);if(Km(i,rM),i.schema!==On)throw new Error(`Expected Native transition schema ${On}`);let r=Ym(i,t,!0),n=Hn(i.previousState),a=Hn(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Qm(n,a,r,BE(n,a,r.eventData),!0),Xm(n,a,r,!0),{schema:On,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function ev(e,t){let i=vd(e);if(Km(i,ME),i.schema!==sr)throw new Error(`Expected Native transition schema ${sr}`);if(md(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${sr} minimum_runtime_version must be 2`);let n=md(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ym(i,t,!0),o=Mi(i.previousState),s=Mi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Qm(o,s,a,BE(o,s,a.eventData),!0),Xm(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:sr,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function fM(e,t){let i=vd(e);if(i.schema===Fr)return{status:"current",journal:Zm(i,t)};if(i.schema===On)return{status:"migration-required",journal:dM(i,t)};if(i.schema===sr)return{status:"migration-required",journal:ev(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function tv(e,t){let i=ft(e,t),r=j(e,i);await T(r,i);try{let n=await ve({root:r,file:i,maxBytes:aM,label:`Native transition journal ${t}`});return fM(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function wr(e,t){let i=await tv(e,t);if(!i)return null;if(i.status==="migration-required")throw new yc(t);return i.journal}function OE(e,t){if(Ki(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Ki(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function HE(e,t){if(Ki(e,t.nextState))return"next";if(Ki(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function hM(e){let{journal:t}=e;return LE({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function LE(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function DE(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=hM({sequence:a.index+1,journal:t,type:a.event.type});if(!Ki(LE(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function Nc(e,t,i){if(await Ja(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Iu(e,t);let r=await wr(e,t);if(!r)return null;let n=D(e,t),a=DE(await wt(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([ze(n),Ie(e,t)]),c=OE(o,r),l=HE(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Bn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!Ki(await ze(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let v=await Ls(e,r.nextState,r.previousState.revision);if(!Ki(v,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!Ki(await Ie(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await wr(e,t);if(!u||!Ki(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=DE(await wt(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await on({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await on({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await ea({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,m]=await Promise.all([ze(n),Ie(e,t)]);OE(h,{...r,previousRun:r.nextRun}),HE(m,{...r,previousState:r.nextState});let p=await wr(e,t);if(!p||!Ki(p,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await tM.rm(ft(e,t),{force:!0}),r.nextState}async function qE(e,t,i){return F(e,`continue transition ${t}`,()=>sn(e,t,`continue transition ${t}`,()=>Nc(e,t,i)))}import VE from"node:path";var pM="comet.native.contract.v1",mM="comet.native.acceptance-set.v1",WE=/^[a-f0-9]{64}$/u,bc={maxAcceptanceCriteria:ys.maxCriteria};function zE(e,t){let i=VE.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||VE.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function JE(e){return M("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
268
|
-
`))}function vM(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(WE))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(WE))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=zE(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:JE(e.markdown)},markdown:e.markdown}}function gM(e,t){return GE(e.id,t.id)}function GE(e,t){return e<t?-1:e>t?1:0}function UE(e){let t=zE(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(vM).sort((d,f)=>GE(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Zl(e.briefMarkdown,t,bc.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...eu(f,d.source,bc.maxAcceptanceCriteria-a.length)),a.push(...tu(f,d.source,bc.maxAcceptanceCriteria-a.length)));if(a.sort(gM),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>bc.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${bc.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:JE(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=M(mM,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:M(pM,u)}}var xi={maxSpecs:64,maxFileBytes:Ro,maxTotalBytes:4*1024*1024};async function uo(e){if(e.specChanges.length>xi.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ne({root:e.changeDir,ref:e.briefRef,maxBytes:xi.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ne({root:e.changeDir,ref:n.source,maxBytes:xi.maxFileBytes});if(i+=a.size,i>xi.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:UE({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as jM}from"node:child_process";import{promisify as $M}from"node:util";import{promises as EM}from"fs";import fo from"path";var ln={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},ho=/^[a-f0-9]{64}$/u;function gd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wd(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function cn(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function KE(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function iv(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function wM(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||fo.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=fo.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function rv(e,t){return fo.join(D(e,t),"checkpoints","progress.json")}function un(e,t){return fo.join(D(e,t),"checkpoint-journal.json")}function nv(e,t,i){if(!ho.test(i))throw new Error("Native checkpoint manifest hash is invalid");return fo.join(D(e,t),"checkpoints","manifests",`${i}.json`)}function yM(e){if(!ho.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function av(e,t,i){let r=await ve({root:e,file:t,maxBytes:ln.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function NM(e,t){let i=gd(e,`checkpoint manifest artifact ${t}`);wd(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=wM(cn(i.path,`checkpoint artifact ${t} path`,4096)),n=Ii(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!ho.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:iv(i.size,`checkpoint artifact ${t} size`)}}function yd(e,t){let i=gd(e,"Native checkpoint manifest");if(wd(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>ln.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(NM),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=iv(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>ln.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function ov(e){return B(JSON.stringify(yd(e,e.change)))}function sv(e,t){let i=gd(e,"Native progress checkpoint");if(wd(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=KE(i.previousRevision,"Native checkpoint previousRevision"),a=KE(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=cn(i.manifestHash,"Native checkpoint manifestHash",64);if(!ho.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=yM(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=cn(i.inputHash,"Native checkpoint inputHash",64);if(!ho.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=cn(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=iv(i.artifactCount,"Native checkpoint artifactCount");if(u>ln.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=cn(i.summary,"Native checkpoint summary"),f=cn(i.nextAction,"Native checkpoint nextAction");if(yt(d)!==d||yt(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:cn(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function bM(e,t){let i=gd(e,"Native checkpoint journal");if(wd(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=_t(i.previousState),n=_t(i.nextState),a=sv(i.checkpoint,t),o=yd(i.manifest,t),s=cn(i.inputHash,"Native checkpoint journal inputHash",64),c=B(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!ho.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==ov(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function kM(e,t,i){let r=fo.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=Xd(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ve({root:e.projectRoot,file:r,maxBytes:ln.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function SM(e,t){let i=rv(e,t),r=j(e,i);await T(r,i);try{return sv(await av(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function cv(e,t,i){let r=nv(e,t,i),n=j(e,r);await T(n,r);let a=await av(n,r,"Native checkpoint manifest"),o=yd(a,t);if(lv(e,o),ov(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function dn(e,t){let i=un(e,t),r=j(e,i);await T(r,i);try{let n=bM(await av(r,i,"Native checkpoint journal"),t);return lv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function YE(e,t,i,r){let n=yd(i,t);lv(e,n);let a=ov(n),o=nv(e,t,a),s=j(e,o);await T(s,o);try{let c=await cv(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await me(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function lv(e,t){for(let i of t.artifacts){let r=Xd(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function XE(e,t){let i=sv(t,t.change),r=await cv(e,i.change,i.manifestHash),n=B(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=rv(e,t.change),o=j(e,a);await T(o,a),await me(a,i,{containedRoot:o})}async function QE(e){let t;try{t=await SM(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:rv(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await cv(e.paths,e.name,t.manifestHash);let a=B(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await kM(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:nv(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function ZE(e,t,i){let r=await dn(e,t);if(!r)return null;if(await YE(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Ls(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await XE(e,r.checkpoint),await i?.afterProgressWritten?.(r),await EM.rm(un(e,t),{force:!0}),r}async function eP(e,t,i){return F(e,`continue checkpoint ${t}`,()=>sn(e,t,`continue checkpoint ${t}`,async()=>(await Nc(e,t),ZE(e,t,i))))}import{constants as uv,promises as ci}from"node:fs";import po from"node:path";var PM=/^[a-f0-9]{64}$/u,RM=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,kc=512*1024;function xM(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Nd(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?L(i,r):L(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function CM(e,t){let i=po.resolve(e),r=po.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...po.relative(i,r).split(po.sep).filter(Boolean)]){o&&(a=po.join(a,o));let s=await ci.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await ci.realpath(a);if(n.length>0&&!$(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function tP(e){for(let t of e){let i=await ci.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xM(t,i)||await ci.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function AM(e){if(!PM.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function _M(e){let t=RM.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function TM(e,t,i){return Dr(D(e,t),AM(i))}async function IM(e,t,i){let r=await CM(i,po.dirname(e)),n=await ci.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>kc)throw new Error(`Native check receipt exceeds ${kc} bytes`);let[a,o]=await Promise.all([ci.realpath(t),ci.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":uv.O_RDONLY|uv.O_NOFOLLOW|uv.O_NONBLOCK,c=await ci.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),ci.lstat(e),ci.realpath(e)]);if(await tP(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Nd(n,l)||!Nd(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,m=Buffer.allocUnsafe(16*1024);for(;;){let y=kc+1-h,S=await c.read(m,0,Math.min(m.length,y),null);if(S.bytesRead===0)break;if(h+=S.bytesRead,h>kc)throw new Error(`Native check receipt exceeds ${kc} bytes`);f.push(Buffer.from(m.subarray(0,S.bytesRead)))}let[p,v,N]=await Promise.all([c.stat(),ci.lstat(e),ci.realpath(e)]);if(await tP(r),!v.isFile()||v.isSymbolicLink()||N!==o||!$(a,N)||!Nd(l,p)||!Nd(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function iP(e,t,i){let r=_M(i),n=D(e,t),a=TM(e,t,r),o=j(e,a);await T(o,a);let s=sd(await IM(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Sc=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var O6=64*1024;var H6=3600*1e3;var D6=$M(jM);var OM=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function nP(e,t){let i=[];for(let r of OM){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function aP(e){if(e.receipt.kind!=="static-inspection")return null;let t=await iP(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var fn=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function HM(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function DM(e){let t=HM(e.bundle.baseline),i=await xp(e.paths,t,{origin:"explicit",now:e.now});return Im({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function sP(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await mc(e.paths,e.state.name,e.state.implementation_scope),i=await uo({changeDir:ee(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await DM({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function cP(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await sP(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function FM(e){let t=await ne({root:ee(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:NN(t.text)}}function MM(e){let{receipt:t,implementationScope:i}=e,r=[],n=Tm({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function BM(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Mm(e.implementationScope.scope.declaredArtifacts)}}async function oP(e){let t=await vc(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=nP(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new fn([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await aP({paths:e.paths,state:e.state,receipt:t});if(n){let a=MM({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function LM(e){let t=BM({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await oP({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof fn)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await oP({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof fn)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new fn(i)}function dv(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function bd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:dv(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([sP(e),co(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:dv(e.state.verification_result,"stale"),envelope:null};let r=await FM({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await LM({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:dv(e.state.verification_result,"invalid"),envelope:null}}}function VM(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function uP(e){try{return await qM.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function WM(e,t){try{return(await ne({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function zM(e,t,i){let r=Kn(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=lP.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await WM(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ne({root:ee(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function JM(e,t){return uP(ft(e,t))}async function kd(e){let t=e.now??new Date,i=await Ie(e.paths,e.name),r=await lt(e.paths,e.name),n=await Y(e.paths.projectRoot),a=VM(i.name,t),o=lP.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(m=>zM(e.paths,i.name,m))),bd({paths:e.paths,state:i,now:t}),dd(e.paths,i.name),Ja(e.paths,i.name),Ga(e.paths,i.name),JM(e.paths,i.name),uP(o)]);return CS({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as fv}from"node:fs";import yr from"node:path";var GM="comet.native.archive-tree.v1",UM={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function hP(e){let t={...UM,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function dP(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function fP(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function pP(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await Tt({root:e,directory:t,label:`Native Archive content directory ${yr.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=dP(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=yr.join(t,u.name),f=yr.relative(e,d).replaceAll("\\","/"),h=await fv.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){fP(i,{ref:f,kind:"directory"},r,n),await pP(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await ve({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=m.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);fP(i,{ref:f,kind:"file",hash:m.hash,size:m.size},r,n),await o.verify()}await o.verify();let l=await Tt({root:e,directory:t,label:`Native Archive content directory ${yr.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(dP(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${yr.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function mP(e,t={}){let i=hP(t);e=yr.resolve(e);let r=await fv.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await pP(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return B(`${GM}\0${o}`)}async function Ci(e,t={}){let i=hP(t);e=yr.resolve(e);let r;try{r=await fv.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ve({root:yr.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${yr.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await mP(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as kt}from"node:fs";import Ve from"node:path";var pv=16*1024*1024,KM=256*1024,YM=16*1024,Ec="comet.native.archive-cas.v1";function XM(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Ve.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function tt(e,t){let i=XM(e,t);return T(j(e,i),i)}function hn(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function mo(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function Ht(e){let t=await Ci(e.target);if(!hn(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${mo(t)}`);return t}async function mv(e,t){let i=await Li(e,t),r=await ve({root:e.runtimeDir,file:i.journal,maxBytes:KM,label:`Native Archive transaction journal ${t}`}),n=vu(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Sd(e,t,i){let r=vu({...t,status:i}),n=await Li(e,r.id);return await me(n.journal,r,{containedRoot:e.runtimeDir}),r}function Ed(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function vP(e){return{...Ed(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function pn(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function QM(e,t){return pn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function he(e){try{return await kt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Yi(e){let t=await kt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=vP(t),r=await ve({root:j(e.paths,e.file),file:e.file,maxBytes:pv,label:e.label}),n=await kt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!QM(i,vP(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Ed(n),size:r.size}}function ZM(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==Ec||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Ec,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Xi(e,t,i,r){let n=await Li(e,t.id),a=Ve.join(n.backups,".cas"),o=`.${Ve.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Ve.join(a,`${i.id}.original.json`),postRecord:Ve.join(a,`${i.id}.post.json`),candidate:Ve.join(a,`${i.id}.candidate`),originalQuarantine:Ve.join(Ve.dirname(r),`${o}.original`),rollbackQuarantine:Ve.join(Ve.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function li(e){if(!await he(e.file))return null;let t=await ve({root:e.paths.runtimeDir,file:e.file,maxBytes:YM,label:`Archive CAS ${e.operation.id} ${e.role} record`});return ZM(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Pd(e){let t=await li(e);if(t){if(!pn(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Bi({root:e.paths.runtimeDir,directory:Ve.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Ec,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await me(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await li(e);if(!r||!pn(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Be(e){let t=await Yi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!pn(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function eB(e){let t=await Yi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Pd({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Be({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function tB(e){if(!await he(e.quarantine)||await he(e.target))return;let t=await Lt({root:j(e.paths,e.target),directory:Ve.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await kt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([kt.lstat(e.quarantine),kt.lstat(e.target)]);if(!pn(Ed(i),Ed(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await kt.unlink(e.quarantine),await t.verify()}async function NP(e){if(await he(e.quarantine)){await Be({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Lt({root:j(e.paths,e.target),directory:Ve.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Be({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Be({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await kt.rename(e.target,e.quarantine),await t.verify(),await Be({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await tB(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function ta(e){if(!await he(e.file))return;await Be(e);let t=await Lt({root:j(e.paths,e.file),directory:Ve.dirname(e.file),label:e.label});await t.verify(),await Be(e),await kt.unlink(e.file),await t.verify()}async function gP(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await tt(e,t.target),n=await tt(e,t.backup),a=await Ci(n);if(a!==null){if(!hn(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await Ht({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await qr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:pv,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await Ht({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function bP(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Xi(e.paths,e.journal,e.operation,e.target),r=await li({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await he(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Be({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await gP(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await he(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await eB({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Be({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await gP(e.paths,e.operation,e.hooks),await NP({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function wP(e){let t=await Xi(e.paths,e.journal,e.operation,e.target);return await he(t.candidate)?(await Yi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Bi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await qr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:pv,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function iB(e){let t=e.operation.stagedHash,i=await Xi(e.paths,e.journal,e.operation,e.target),r=await li({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await he(e.target))return await Be({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await he(i.candidate)&&await ta({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await he(e.target)){let c=await wP(e),l=await Yi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Yi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!pn(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Pd({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await ta({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await wP(e),a=await Yi({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Bi({root:j(e.paths,e.target),directory:Ve.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Lt({root:j(e.paths,e.target),directory:Ve.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Be({paths:e.paths,file:n,operation:e.operation,record:{schema:Ec,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await kt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Yi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!pn(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Pd({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await ta({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function rB(e,t,i,r){let n=await tt(e,i.target),a=await tt(e,i.staged);if(await Ht({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Xi(e,t,i,n);(!await li({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await he(n))&&await bP({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Ci(n);if(o!==null&&!hn(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${mo(o)}`)}await iB({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await Ht({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function nB(e,t,i,r){let n=await tt(e,i.target);await bP({paths:e,journal:t,operation:i,target:n,hooks:r}),await Ht({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function aB(e,t){let i=await tt(e,t.source),r=await tt(e,t.target),[n,a]=await Promise.all([Ci(i),Ci(r)]);if(!(n===null&&hn(a,t.expectedSourceHash,"directory"))){if(!hn(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${mo(n)}, target=${mo(a)}`);await kt.mkdir(Ve.dirname(r),{recursive:!0}),await kt.rename(i,r),await Ht({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function oB(e,t,i,r){return i.type==="write"?rB(e,t,i,r):i.type==="remove"?nB(e,t,i,r):aB(e,i)}function sB(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function cB(e,t,i,r){let n=await tt(e,i.target);if(i.type==="write"){let a=await tt(e,i.staged);await Ht({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Xi(e,t,i,n),s=await li({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Be({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await Ht({target:await tt(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await li({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await he(o.originalQuarantine))await Be({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await Ht({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await Ht({target:await tt(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Xi(e,t,i,n),o=await li({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await he(a.originalQuarantine))await Be({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await Ht({target:await tt(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await Ht({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function kP(e,t,i){let r=t.status==="prepared"?await Sd(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Wr(e,r.id),a=sB({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await cB(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await ii(e,r.id,"operation-started",l.id),await oB(e,r,l,i),await ii(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await mv(e,r.id),r}async function lB(e){try{return await Be(e),!0}catch{return!1}}async function uB(e){await Be({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Lt({root:j(e.paths,e.target),directory:Ve.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Be({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await kt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Be({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function hv(e){if(e.operation.type!=="write")return;let t=await Xi(e.paths,e.journal,e.operation,e.target);if(!await he(t.candidate))return;let i=await Yi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await ta({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Ec,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function dB(e,t,i,r){let n=await tt(e,i.target),a=await Xi(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await li({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await li({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await he(a.candidate)&&await he(n)){let l=await Yi({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Yi({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});pn(l.identity,u.identity)&&(c=await Pd({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await he(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Be({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await he(n)&&!(s!==null&&await lB({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Ci(n);if(hn(u,o)){await hv({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await NP({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await he(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await he(n)){if(!s||!await he(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await uB({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await he(a.originalQuarantine)&&await ta({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await he(a.rollbackQuarantine)&&await ta({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await hv({paths:e,journal:t,operation:i,target:n}),await Ht({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function fB(e,t){let i=await tt(e,t.source),r=await tt(e,t.target),[n,a]=await Promise.all([Ci(i),Ci(r)]);if(!(hn(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!hn(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${mo(n)}, target=${mo(a)}`);await kt.mkdir(Ve.dirname(i),{recursive:!0}),await kt.rename(r,i)}}async function SP(e,t,i){let r=await Wr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Sd(e,t,"rolling-back");await ii(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await fB(e,o):await dB(e,n,o,i));return await ii(e,n.id,"rollback-completed"),n=await Sd(e,n,"rolled-back"),n}async function yP(e,t,i){let r=await tt(e,i.target);if(i.type==="write"){let n=await Xi(e,t,i,r),a=await li({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Be({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await Ht({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function hB(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await tt(e,i.target),n=await Xi(e,t,i,r);if(await he(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await yP(e,t,i),i.expectedTargetHash!==null){let a=await li({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await he(n.originalQuarantine)&&await ta({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await hv({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await yP(e,t,i)}async function Rd(e,t,i){return i==="commit"&&await hB(e,t),await ii(e,t.id,i),i==="commit"?Sd(e,t,"committed"):t}var _4=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var a9=16*1024*1024,xd=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Pc=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function PP(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return vo.resolve(e.nativeRoot,...i.target.split("/"))}async function RP(e,t,i){let r=await Wr(e,t.id);if(r.some(v=>v.type==="archive-finalized"))return;let n=r.some(v=>v.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let v=t.operations.find(y=>y.id==="archive-change");if(!v||v.type!=="move"||!v.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let N=await Ci(PP(e,t));if(N?.kind!=="directory"||N.hash!==v.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=PP(e,t),o=vo.join(a,qe),s=await ik(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=D(e,s.name),l=await ze(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let v=ES(Ui,l,new Set,Jm,void 0);if(!v.action)throw new Error(v.reason??"Native archive produced no action");u=PS(Ui,v.state,{actionId:v.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Jm,void 0)}let d=B(`archive:${t.id}:${s.name}`),f=await wt(c,u.trajectoryRef),h=f.filter(v=>v.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(v=>v.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let m=h.find(v=>v.type==="state_transitioned"),p={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(m&&t.schema==="comet.native.transaction.v2"&&(!pB(m.data,p)||m.runId!==u.runId||m.timestamp!==t.createdAt||m!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await Rd(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await ja(e,t,"archive-finalization-started")),!s.archived){let v={...s,archived:!0};await tk(o,v)}m||(m=await on({changeDir:c,run:u,type:"state_transitioned",data:p,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await ea({changeDir:c,run:u,trajectoryOffset:m.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Bn(c,u),await ec(e,s.name),t.schema==="comet.native.transaction.v2"?await Rd(e,t,"archive-finalized"):await ja(e,t,"archive-finalized")}async function vv(e,t){let i=We(e,t);try{let r=await EP.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await EP.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function mB(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Wr(e,t.id)).some(c=>c.type==="operation-started")){let c=await kd({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new Pc(c,"Native Archive facts changed before the first transaction operation")}let o=await kP(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await Ie(e,t.change),u=await bd({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await RP(e,o,i);let s=await Rd(e,o,"commit");return{journal:s,runtimeCleanupWarning:await vv(e,s.change)}}let r=await UN(e,t);await RP(e,r,i);let n=await ja(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await vv(e,n.change):null}}function vB(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(vo.resolve(t.projectRoot)!==vo.resolve(e.projectRoot)||vo.resolve(t.nativeRoot)!==vo.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function xP(e){return F(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await nr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await It(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await mv(e.paths,e.transactionId):i;return vB(e.paths,r),r.status==="committed"?(r.change&&await vv(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await mB(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?SP(e.paths,r):wu(e.paths,r)}finally{await ar(t)}},{allowedTransactionId:e.transactionId})}import{promises as Cd}from"node:fs";import St from"node:path";var ia=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};function AP(e,t){let i=St.normalize(e),r=St.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function _P(e,t){let i=St.relative(e,t);return i===""||!St.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${St.sep}`)}function CP(e){return JSON.stringify(e.native)}async function gv(e,t){let i=await Y(e);if(i&&t){if(CP(i)!==CP(t))throw new Error(`Native worktree configuration differs from the source project: ${St.join(e,".comet","config.yaml")}`);return!1}return!i&&t?(await Bt(e,t),!0):!1}async function gB(e,t){if(!_P(e,t))return!1;let r=`/${St.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=xe(e,["rev-parse","--git-common-dir"]),a=St.resolve(e,n),o=St.join(a,"info","exclude"),s="";try{s=await Cd.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(r))return!1;await Cd.mkdir(St.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
260
|
+
`;function we(e,t){if(!pd.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=He.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function Ht(e,t){return He.join(we(e,t),VH)}function ae(e,t){return He.join(ze(e,t),WH)}async function ke(e,t){try{let i=await di.readFile(Ht(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function JH(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Et(e){return me(e).currentBranch}function GH(e,t){if(!t)return;let i=me(e);if(t.changeBranch!==null&&(!i.isGitWorktree||i.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Yk(e){return F(e.paths,`create portable change ${e.name}`,async()=>{if(!pd.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await Y(e.paths.projectRoot)===null&&await Vt(e.paths.projectRoot,e.initialProjectConfig),GH(e.paths.projectRoot,e.workspaceBinding);let t=(await kk(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new Qa(e.workspaceBinding?.isolation??"current",t);let i=we(e.paths,e.name),r=ze(e.paths,e.name);await Promise.all([T(e.paths.nativeRoot,i),T(e.paths.runtimeDir,r)]);let n=!1,a=!1;try{await di.mkdir(e.paths.changesDir,{recursive:!0}),await di.mkdir(i,{recursive:!1}),n=!0,await di.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await di.mkdir(r,{recursive:!1}),a=!0,await di.mkdir(He.join(i,"specs"),{recursive:!0}),await Ne(He.join(i,"brief.md"),zH);let o=VN({name:e.name,language:e.language,workspace:JH(e.workspaceBinding),createdAt:e.now,nextAction:"confirm-shape"});return await Rs(Ht(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await ce(ae(e.paths,e.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await di.rm(r,{recursive:!0,force:!0}),n&&await di.rm(i,{recursive:!0,force:!0}),o}})}async function K(e,t){return wt(Ht(e,t))}async function dt(e){let t=await Bn({file:Ht(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 i=He.join(we(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await di.rm(i,{force:!0})}return t}async function Xk(e){let t=we(e.paths,e.state.name),i=He.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await di.readdir(i,{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(!pd.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=He.join(t,...s.split("/")),l=await di.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=He.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await di.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Qk(e){let t=we(e.paths,e.state.name),i=await ee({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await ee({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return mu({briefMarkdown:i.text,specs:r})}async function Zk(e){return F(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await Xk({paths:e.paths,state:t}),r=await Qk({paths:e.paths,state:t,specChanges:i}),n=await Us({changeDir:we(e.paths,t.name),acceptanceIds:r.map(({id:s})=>s)});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=Fk({state:{...t,spec_changes:i},acceptance:r.map(s=>({...s}))});if(delete a.children_contract_hash,n){a.children_contract_hash=ed({acceptance:a.acceptance,children:n.contract});let s=[...t.history].reverse().find(({outcome:c})=>c==="pass"||c==="fail");if(s?.outcome==="fail"&&s.unresolved_ids.length>0){let c=await Gt({paths:e.paths,state:a}),l=new Set((c?.children??[]).filter(({status:d})=>d!=="done").flatMap(({covers:d})=>d)),u=s.unresolved_ids.filter(d=>!l.has(d));if(u.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${u.join(", ")}`)}}let o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}async function Zn(e){let t=await Xk(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await Qk({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!LN(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Us({changeDir:we(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?ed({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function gr(e){let t=await Zn(e);if(!t.drifted)return;let i=t.reason??"Native confirmed requirements changed";throw await md({paths:e.paths,state:e.state,reason:i}),new Error(`${i}; Native change returned to Shape and requires confirmation`)}async function eS(e){return F(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(await gr({paths:e.paths,state:t}),await Us({changeDir:we(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a)})||t.children_contract_hash)throw new Error("Native parent Build advances child changes instead of a parent Builder");let r=vm({state:t,input:e.input}),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function tS(e){return F(e.paths,`complete portable parent Build ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.phase!=="build"||t.status!=="active")throw new Error("Native parent integration can only complete from active Build");await gr({paths:e.paths,state:t});let i=await Gt({paths:e.paths,state:t});if(!i||!t.children_contract_hash)throw new Error(`Native change ${t.name} has no confirmed child contract`);if(!i.confirmed)throw new Error("Native parent child declarations require Shape confirmation");if(!i.allDone)throw new Error("Native parent cannot enter Verify before every child is merged");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; add and confirm a repair child");let n=Ys().captureExecutionIdentity({identityProvider:"skill-coordinated",executionRef:`native-parent-integration:${hd()}`}),a=vm({state:t,input:{identity:n,summary:e.summary,addressedAcceptanceIds:t.acceptance.map(({id:s})=>s),checks:[],knownLimits:[]}}),o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),Be({portableState:o,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o})}function km(e,t,i){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:id(i,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function iS(e,t,i,r){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...km(t,i,r),executionCount:e.executionCount}}function rS(e,t){let i=He.relative(He.resolve(e),He.resolve(t));if(He.isAbsolute(i)||i===".."||i.startsWith(`..${He.sep}`))throw new Error("Native local check cwd escaped the project root");let r=i.length===0?".":i.split(He.sep).join("/");return id(e,r),r}function bm(e,t){let[i,...r]=e.argv;if(!i)throw new Error(`Native local check ${e.id} has no executable`);return Ks({id:e.id,name:e.id,executable:i,argv:r,cwdRef:rS(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function UH(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function io(e){let t=new Map;for(let i of e.supplied){if(t.has(i.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${i.id}`);t.set(i.id,i)}return e.local.checks.map(i=>{if(i.status==="planned"||i.status==="running")throw new Error(`Native Runtime check ${i.id} has not completed`);let r=e.requestedNames?.get(i.id)??i.name;return{id:i.id,name:ue(r),argv_display:um(i.argv.slice(1)).map(n=>ue(n)),argv_truncated:!1,cwd_ref:rS(e.projectRoot,i.cwd),status:i.status,exit_code:i.exitCode,duration_ms:UH(i)}})}function KH(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function rc(e){if(e.local===null||e.local.change!==e.state.name)return Be({portableState:e.state,projectRoot:e.projectRoot,branch:Et(e.projectRoot)});let t=e.local.execution?.operationId??hd();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(i=>i.status==="running"||i.status==="planned"?{...i,operationId:t,status:"interrupted"}:{...i,operationId:t})}}async function ro(e){try{let t=await Ci(ae(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function nS(e){let{state:t,local:i,expected:r}=e;if(t.state_version!==r.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==r.iteration||t.loop.attempt!==r.attempt||t.builder_handoff===null||i===null||i.basedOnStateVersion!==t.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return i}function YH(e){let{state:t,local:i,envelope:r}=e;if(!nd(r))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(r.candidateId!==t.builder_handoff.candidate_id||r.identityProvider!==t.builder_handoff.identity_provider||r.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(i===null||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running"||i.execution.executionId!==null&&i.execution.executionId!==r.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return r}function XH(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function fd(e){let t=await ro({paths:e.paths,state:e.state}),i=zk({state:e.state,summary:e.summary}),r=await dt({paths:e.paths,previous:e.state,next:i});return await ce(ae(e.paths,e.state.name),rc({local:t,state:r,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),r}function Kk(e,t,i){return e.checks.length!==t.length?!1:e.checks.every((r,n)=>bm(r,i)===Ks(t[n]))}async function QH(e){return F(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(await gr({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let i=ae(e.paths,t.name),r=(await Nm({file:i,portableState:t,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(r.execution?.stage==="checking"&&r.execution.actor==="runtime"&&Kk(r,e.plans,e.paths.projectRoot)){let o=r.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=r.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:u})=>[l,u]));return{kind:"reuse",state:t,checks:io({local:r,projectRoot:e.paths.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=ec({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(u=>!u.repeatable).map(({id:u})=>u).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await dt({paths:e.paths,previous:t,next:c});throw await ce(ae(e.paths,t.name),Be({portableState:l,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(u=>!u.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(r.execution!==null&&r.checks.length>0){if(!(r.execution.stage==="checking"&&r.execution.actor==="runtime"&&r.checks.some(s=>s.status==="interrupted")&&Kk(r,e.plans,e.paths.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(r.execution!==null||r.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=hd(),a={...r,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=r.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?iS(s,o,n,e.paths.projectRoot):s?{...s,operationId:n}:km(o,n,e.paths.projectRoot)})};return await ce(i,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=r.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function ud(e){return F(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await K(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 i=ae(e.paths,t.name),r=await Ci(i);if(r===null||r.basedOnStateVersion!==t.state_version||r.execution?.operationId!==e.operationId||r.execution.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(r);return await ce(i,n,{containedRoot:e.paths.runtimeDir}),n})}async function aS(e){if(new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let t=[],i=new Set;for(let s of e.plans){rd(e.paths.projectRoot,s);let c=Ks(s);i.has(c)||(i.add(c),t.push(s))}let r=await QH({...e,plans:t});if(r.kind==="reuse")return r;let n=r.local.execution.operationId,a=ze(e.paths,r.state.name);try{for(let s of r.plans){let c=new Date().toISOString();await ud({paths:e.paths,state:r.state,operationId:n,update:u=>({...u,checks:u.checks.map(d=>d.id===s.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:c}:d)})});let l=await dm({projectRoot:e.paths.projectRoot,runtimeDir:a,operationId:n,plan:s});await ud({paths:e.paths,state:r.state,operationId:n,update:u=>({...u,checks:u.checks.map(d=>d.id===s.id?{...d,status:l.status,exitCode:l.exitCode,startedAt:l.startedAt,completedAt:l.completedAt,log:l.logRef}:d)})})}await ud({paths:e.paths,state:r.state,operationId:n,update:s=>({...s,execution:{...s.execution,status:"completed"}})})}catch(s){try{await ud({paths:e.paths,state:r.state,operationId:n,update:c=>({...c,execution:{...c.execution,status:"interrupted"},checks:c.checks.map(l=>l.status==="planned"||l.status==="running"?{...l,status:"interrupted"}:l)})})}catch{}throw s}let o=await Ci(ae(e.paths,r.state.name));if(o===null)throw new Error("Native Runtime check state disappeared after execution");return{state:r.state,checks:io({local:o,projectRoot:e.paths.projectRoot,supplied:[]})}}async function ZH(e){let t=ae(e.paths,e.state.name),i=e.local;if(i===null||i.change!==e.state.name||i.basedOnStateVersion!==e.state.state_version||i.execution===null||i.execution.stage!=="verifying"||i.execution.actor!=="verifier"||i.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(i.execution.executionId!==null&&i.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(i.execution.requestCheckRounds>=pm)throw new Error(`Native Verifier request-checks exceeded ${pm} rounds for this attempt`);let r=new Map,n=new Map,a=new Map;for(let h of i.checks){let m=bm(h,e.paths.projectRoot);n.set(m,h),h.status!=="interrupted"&&r.set(m,h),a.set(h.id,m)}let o=new Map,s=new Map;for(let h of e.response.checks){let m=KH(h);rd(e.paths.projectRoot,m);let p=Ks(m),v=s.get(m.id);if(v!==void 0&&v!==p)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let g=a.get(m.id);if(g!==void 0&&g!==p)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,p);let y=n.get(p);if(y?.status==="interrupted"&&!y.repeatable)throw new Error(`Native check ${y.id} was interrupted and is not repeatable; user resolution is required`);o.has(p)||o.set(p,m)}let c=[...o.entries()],l=c.filter(([h])=>!r.has(h));if(i.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=i.execution.requestCheckRounds+1,d=new Map(c.map(([,h])=>[h.id,h.name])),f={...i,execution:{...i.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...i.checks.map(h=>{let m=bm(h,e.paths.projectRoot),p=o.get(m);return p&&h.status==="interrupted"?iS(h,p,i.execution.operationId,e.paths.projectRoot):h}),...l.filter(([h])=>!n.has(h)).map(([,h])=>km(h,i.execution.operationId,e.paths.projectRoot))]};return await ce(t,f,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:f,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,h])=>h),requestedNames:d,reusedCheckIds:c.filter(([h])=>r.has(h)).map(([,h])=>h.id),suppliedChecks:e.suppliedChecks}}async function dd(e){return F(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await K(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 i=ae(e.paths,t.name),r=await Ci(i),n=r?.execution;if(r===null||r.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(r);return await ce(i,a,{containedRoot:e.paths.runtimeDir}),a})}async function eD(e){let t;try{for(let i of e.reservation.novelPlans){let r=new Date().toISOString();t=await dd({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:r}:o)})});let n=await dm({projectRoot:e.paths.projectRoot,runtimeDir:ze(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:i});t=await dd({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===i.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await dd({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(i){try{await dd({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,status:"interrupted"},checks:r.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw i}return{checks:io({local:t,projectRoot:e.paths.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:i})=>i)}}}async function oS(e){return F(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=(await Nm({file:ae(e.paths,t.name),portableState:t,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot),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");io({local:i,projectRoot:e.paths.projectRoot,supplied:e.checks});let r=Mk(t),n=await dt({paths:e.paths,previous:t,next:r}),a=ae(e.paths,t.name),o=hd();return await ce(a,{...i,basedOnStateVersion:n.state_version,execution:{operationId:o,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(s=>({...s,operationId:o}))},{containedRoot:e.paths.runtimeDir}),n})}async function sS(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await F(e.paths,`apply portable verifier ${e.name}`,async()=>{let i=await K(e.paths,e.name);await gr({paths:e.paths,state:i});let r=await ro({paths:e.paths,state:i}),n=YH({state:i,local:r,envelope:e.envelope}),a;try{a=hm(n.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,f=await fd({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${f.loop.execution_failure_count}/${Zs} was recorded`,{cause:u})}let o=XH(a);if(o.iteration!==i.loop.iteration||o.attempt!==i.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let s=[],c;try{r!==null&&(s=io({local:r,projectRoot:e.paths.projectRoot,supplied:e.checks}));let u=Bk({state:i,envelope:n,checks:s,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(r===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await ZH({paths:e.paths,state:i,local:r,envelope:n,response:u.response,suppliedChecks:s});return{kind:"request-checks",state:i,response:u.response,reservation:d}}if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==n.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");c=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,f=await fd({paths:e.paths,state:i,summary:d});throw new Error(`${d}; execution error ${f.loop.execution_failure_count}/${Zs} was recorded`,{cause:u})}let l=await dt({paths:e.paths,previous:i,next:c.state});return await ce(ae(e.paths,i.name),l.loop.next_action==="resolve-verifier-blocker"?rc({local:r,state:l,projectRoot:e.paths.projectRoot}):Be({portableState:l,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),l.verification!==null&&await vr({file:He.join(we(e.paths,i.name),"verification.md"),state:l}),{kind:"final-result",result:{state:l,response:c.response,checks:s,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let i=await eD({paths:e.paths,reservation:t.reservation});return{state:t.state,response:t.response,checks:i.checks,requestChecks:i.requestChecks}}catch(i){let r=`Native Verifier response was invalid: ${i.message}`,n=await F(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await K(e.paths,e.name);return a.state_version!==t.state.state_version?null:fd({paths:e.paths,state:a,summary:r})});throw new Error(n?`${r}; execution error ${n.loop.execution_failure_count}/${Zs} was recorded`:`${r}; the portable state changed before the execution error could be recorded`,{cause:i})}}async function cS(e){return F(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await ro({paths:e.paths,state:t});if(nS({state:t,local:i,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 fd({paths:e.paths,state:t,summary:e.summary})})}async function lS(e){return F(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=await ro({paths:e.paths,state:t}),r=nS({state:t,local:i,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=io({local:r,projectRoot:e.paths.projectRoot,supplied:[]}),a=qk({state:t,checks:n,verifierExecutionRef:r.execution.executionId,summary:e.summary}),o=await dt({paths:e.paths,previous:t,next:a});return await ce(ae(e.paths,t.name),rc({local:r,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:o}),o})}async function uS(e){return F(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=Lk(t),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function dS(e){return F(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=Vk({state:t,summary:e.summary}),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function fS(e){return F(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await K(e.paths,e.name);await gr({paths:e.paths,state:t});let i=await ro({paths:e.paths,state:t}),r=Wk(t),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),rc({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function hS(e){return F(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await K(e.paths,e.name),i=await ro({paths:e.paths,state:t}),r=Jk(t),n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),rc({local:i,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function no(e){return F(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await K(e.paths,e.name);if(t.phase==="build")return t;let i=ec({state:t,reason:e.reason}),r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r})}async function pS(e){if(!pd.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return F(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await K(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i=t.spec_changes.filter(({capability:a})=>a!==e.capability),r={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...i,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function mS(e){return F(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let i={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},r=await dt({paths:e.paths,previous:t,next:i});return await ce(ae(e.paths,t.name),Be({portableState:r,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),r.verification!==null&&await vr({file:He.join(we(e.paths,t.name),"verification.md"),state:r}),r})}async function nc(e){return F(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await K(e.paths,e.name);return t.phase==="shape"?t:md({paths:e.paths,state:t,reason:e.reason})})}async function md(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...ri(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ue(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:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await dt({paths:e.paths,previous:t,next:r});return await ce(ae(e.paths,t.name),Be({portableState:n,projectRoot:e.paths.projectRoot,branch:Et(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function vd(e){if(e.state.verification===null)return"not-applicable";let t=He.join(we(e.paths,e.state.name),"verification.md");return await ic({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await vr({file:t,state:e.state}),"rebuilt")}async function vS(e){let t=await K(e.paths,e.name),i=ae(e.paths,e.name);try{let r=await Ci(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}import{randomUUID as tD}from"crypto";import{promises as ac}from"fs";import wS from"path";var Sm="comet.selection.v2",iD=16*1024;function oc(e){return wS.join(e,".comet","current-change.json")}function rD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function gS(e){return e===null||typeof e=="string"}function yS(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!rD(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!gS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Sm,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Sm)throw new Error(`current change selection schema must be ${Sm}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!gS(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Em(e){let t;try{let r=oc(e),{bytes:n}=await jn(r,iD,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...yS(t)}}async function NS(e,t){let i=yS(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=oc(e),n=`${r}.${tD()}.tmp`;await ac.mkdir(wS.dirname(r),{recursive:!0});try{await ac.writeFile(n,`${JSON.stringify(i.selection,null,2)}
|
|
261
|
+
`,"utf8"),await ac.rename(n,r)}catch(a){throw await ac.rm(n,{force:!0}),a}}async function bS(e){await ac.rm(oc(e),{force:!0})}async function kS(e,t,i){let r=await Em(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await bS(e),!0)}var WU=16*1024;async function sc(e){let t=await Em(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Un(t.selection.change),t.selection)}function cc(e){return oc(e.projectRoot)}async function gd(e,t){return F(e,`select change ${t}`,async()=>{Un(t),await ke(e,t)?await K(e,t):await je(e,t),await NS(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function SS(e){let t=await sc(e);return t?(await ke(e,t.change)?await K(e,t.change):await je(e,t.change),t.change):null}async function lc(e,t){return await Ia(e.projectRoot),kS(e.projectRoot,"native",t)}var uc=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function Pm(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Rm(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=Pt.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function wd(e){try{return await tt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ES(e,t){let i=Pt.normalize(Pt.resolve(e)),r=Pt.normalize(Pt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function PS(e,t){let i;try{i=await tt.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=Pt.join(e.archiveDir,n.name);try{let o=await wt(Pt.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function Cm(e,t){let i=await Ha(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function RS(e,t){return await Cm(e,t)!==null||await PS(e,t)!==null}async function ea(e,t){await tt.mkdir(e.transactionsDir,{recursive:!0}),await ve(Vr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function CS(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Zt(e.paths.projectRoot);i.some(a=>ES(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Y(a);if(!o)continue;let s=await re(a,o.native.artifact_root);r.some(c=>ES(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await tt.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await wt(Pt.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Kn(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function aD(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function oD(e){let t=Pt.join(e.paths.specsDir,e.change.capability),i=Pt.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await tt.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await tt.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([tt.realpath(e.paths.specsDir),tt.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await tt.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await tt.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await tt.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=Pt.join(we(e.paths,e.state.name),e.change.source);await Ne(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await tt.mkdir(t,{recursive:!0}),await Ne(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function xm(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function sD(e,t){let i=we(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await ee({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function cD(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(xm(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Am(e){let t=await K(e.paths,e.name),i=[];try{xm(t)}catch(o){i.push(o.message)}if(await Cm(e.paths,e.name)===null)try{let o=await Zn({paths:e.paths,state:t});o.drifted&&i.push(o.reason??"Native confirmed requirements changed")}catch(o){i.push(o.message)}let n=t.verification===null?"missing":await ic({file:Pt.join(we(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await CS({paths:e.paths,state:t});return a.length>0&&i.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:i.length===0,blockers:i,capabilityPeers:a,archiveDir:Rm(e.paths,Pm(t)),stateVersion:t.state_version}}async function dc(e){return F(e.paths,`archive portable change ${e.name}`,async()=>{let t=aD(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await Cm(e.paths,e.name),r=we(e.paths,e.name),n=await wd(r),a=n?null:await PS(e.paths,e.name),o;if(n)o=await K(e.paths,e.name);else if(i)o=await wt(Pt.join(Rm(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await Zn({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await md({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=Rm(e.paths,i?.archive_ref??Pm(o)),c=await wd(s);if(i&&cD(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await lc(e.paths,o.name),await tt.rm(ze(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)xm(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await CS({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new uc(l);i={schema:ku,id:nD(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Pm(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await sD(e.paths,o),created_at:new Date().toISOString()},await ea(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await ea(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await oD({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await ea(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await ea(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Bn({file:Ht(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await ea(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await wd(r)?r:s;if(await vr({file:Pt.join(l,"verification.md"),state:o}),await ic({file:Pt.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await ea(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await tt.mkdir(e.paths.archiveDir,{recursive:!0}),await wd(s))throw new Error(`Native Archive target already exists: ${s}`);await tt.rename(r,s),i={...i,status:"moved"},await ea(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await lc(e.paths,o.name),await tt.rm(ze(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await tt.rm(Vr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function de(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?["comet","native","next",e.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,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:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,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:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,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}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|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:"<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:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as lD}from"node:crypto";import{promises as ao}from"node:fs";import $S from"node:path";var OS=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function uD(e){try{return await ao.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function _m(e,t){let i=te(e,t),r=[Vr(e,{kind:"migration",change:t}),On(e,t),...OS.map(n=>$S.join(i,n))];return(await Promise.all(r.map(uD))).some(Boolean)}async function dD(e,t){let i=await Ha(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function xS(e,t){await ao.mkdir(e.transactionsDir,{recursive:!0}),await ve(Vr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function AS(e,t){await Promise.all([ao.rm(ze(e,t),{recursive:!0,force:!0}),ao.rm(On(e,t),{recursive:!0,force:!0}),...OS.map(i=>ao.rm($S.join(te(e,t),i),{force:!0}))])}async function _S(e,t){await ce(ae(e,t.name),Be({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function TS(e,t){try{let i=await lt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function IS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=me(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function fD(e){let t=te(e.paths,e.state.name),i=await ee({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await ee({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return mu({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function jS(e,t){let i=await Kn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function xi(e){return F(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await dD(e.paths,e.name),i=await ke(e.paths,e.name)?await wt(Ht(e.paths,e.name)):null;if(!t&&i)return await AS(e.paths,e.name),await _S(e.paths,i),i;let r=null,n=null;for(t||(r=await jS(e.paths,e.name),n=await TS(e.paths,e.name),IS(e.paths,n),t={schema:bu,id:lD(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await xS(e.paths,t));;){let a=zN(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await jS(e.paths,e.name),n??=await TS(e.paths,e.name),IS(e.paths,n),i=WN({state:r,acceptance:await fD({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Rs(Ht(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await AS(e.paths,e.name):a.action==="commit-transaction"&&(i??=await wt(Ht(e.paths,e.name)),await _S(e.paths,i)),t={...t,status:a.nextStatus},await xS(e.paths,t)}return await ao.rm(Vr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??wt(Ht(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as HS}from"node:fs";import DS from"node:path";function hD(e,t){let i=me(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function pD(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function mD(e,t){let i=new Date().toISOString(),r=e.verification===null?e:ri(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ue(t),completed_at:i});return X({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:pD(e),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 vD(e){try{let t=await Ci(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 ta(e){return F(e.paths,`recover portable change ${e.name}`,async()=>{let t=await K(e.paths,e.name);if(t.status==="done")return await vd({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 i=hD(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=ae(e.paths,e.name),n=await vD(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await ce(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await vd({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=ec({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Bn({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await HS.rm(DS.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Be({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await ce(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=mD(t,l?"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.");t=await Bn({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=Be({portableState:t,projectRoot:e.paths.projectRoot,branch:me(e.paths.projectRoot).currentBranch});return await HS.mkdir(DS.dirname(ae(e.paths,t.name)),{recursive:!0}),await ce(r,d,{containedRoot:e.paths.runtimeDir}),await vd({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"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{promises as SD}from"node:fs";import oo from"node:path";import{execFileSync as gD}from"node:child_process";var wD=6e4,yD=8*1024*1024,Tm=class extends Error{constructor(i,r,n,a){super(`${i} ${r.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=i;this.args=r;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function Im(e,t,i={}){let r=i.timeoutMs??wD,n=i.maxBufferBytes??yD;if(!Number.isSafeInteger(r)||r<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");try{return gD(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r,maxBuffer:n,windowsHide:!0,shell:!1})}catch(a){let o=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new Tm(e,t,o,{cause:a})}}import{promises as jm}from"fs";import FS from"path";var MS=["Outcome","Scope","Non-goals","Acceptance examples"],ND=[...MS,"Constraints and invariants","Decisions","Open questions","Verification expectations"],bD=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],BS={maxFileBytes:$o};function LS(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
262
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function kD(e,t){let i=FS.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await jm.realpath(e),n=await jm.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await jm.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function fc(e){return{valid:e.length===0,findings:e}}async function $m(e,t){let i=[],r;try{r=(await ee({root:e,ref:t,maxBytes:BS.maxFileBytes})).text}catch(o){return fc([{code:"brief-missing",message:o.message,path:t}])}let n=LS(r);for(let o of ND)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of MS)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),fc(i)}async function Om(e,t){let i=[],r;try{r=(await ee({root:e,ref:t,maxBytes:BS.maxFileBytes})).text}catch(a){return fc([{code:"verification-missing",message:a.message,path:t}])}let n=LS(r);for(let a of bD)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return fc(i)}function ia(e,t){return FS.join(e.specsDir,t,"spec.md")}async function qS(e,t){let i=[],r=te(e,t.name);for(let n of t.spec_changes){let a=ia(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await oi(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await kD(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return fc(i)}var hc=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function ED(e,t){let i=oo.relative(e,t);return i===""||!oo.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${oo.sep}`)}function ra(e,t){let i=oo.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||oo.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function VS(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function PD(e){try{if(he(e,["config","--get","user.name"])&&he(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function RD(e,t){for(let i of Zt(e))if(me(i).currentBranch===t)return i;return null}function CD(e,t){try{Im(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function Hm(e){let{paths:t,state:i}=e,r=i.workspace;if(r.isolation==="current")return null;if(!r.finish||!r.change_branch||!r.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(r.change_branch===r.target_branch)throw new Error("Native change and target branches must be different for workspace finish");let n=me(t.projectRoot);if(!n.primaryWorktreeRoot||n.currentBranch!==r.change_branch)throw new Error(`Native workspace finish requires branch ${r.change_branch} in the current registered worktree`);PD(t.projectRoot);let a=[ra(t.projectRoot,cc(t))];e.archiveDir&&a.push(ra(t.projectRoot,te(t,i.name)),ra(t.projectRoot,e.archiveDir));let o=im(t.projectRoot).filter(l=>!VS(l,a));if(o.length>0)throw new Error(`Native workspace finish is blocked until change-owned implementation and artifacts are committed; remaining paths: ${o.slice(0,20).join(", ")}${o.length>20?", ...":""}`);let s=r.isolation==="branch"?t.projectRoot:RD(n.primaryWorktreeRoot,r.target_branch);if(r.finish==="merge"&&r.isolation==="worktree"){if(!s)throw new Error(`Native merge finish requires a registered worktree on target branch ${r.target_branch}`);if(!Gs(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?Ek(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&CD("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function xD(e,t){try{return Im("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function AD(e){try{return await SD.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function _D(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function WS(e){let t=_D(e.plan),i=null;try{let r=[ra(e.paths.projectRoot,te(e.paths,e.name)),ra(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(c=>ra(e.paths.projectRoot,ia(e.paths,c.capability))),ra(e.paths.projectRoot,cc(e.paths))],n=im(e.plan.changeRoot).filter(c=>!VS(c,r));if(n.length>0)throw new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.slice(0,20).join(", ")}${n.length>20?", ...":""}`);let a=[];for(let c of r){let l=oo.resolve(e.paths.projectRoot,...c.split("/")),u=he(e.plan.changeRoot,["ls-files","--",c])!=="";(await AD(l)||u)&&a.push(c)}if(a.length>0&&he(e.plan.changeRoot,["add","-A","--",...a]),he(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&he(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=he(e.plan.changeRoot,["rev-parse","HEAD"]),!Gs(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){if(he(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=xD(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(l=>/^https?:\/\//u.test(l.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let c=ED(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!c?(he(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let s=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(he(s,["switch",e.plan.targetBranch]),i=s),he(s,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=s,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(i!==null){let n;try{he(i,["merge","--abort"])}catch{}try{me(i).currentBranch===e.plan.targetBranch&&he(i,["switch",e.plan.changeBranch]),n=me(i).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=i)}throw t.status="blocked",t.message=r.message,t.recoveryArgs=e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new hc(t)}}import Fv from"path";import{promises as UP}from"fs";import Eo from"path";import{isDeepStrictEqual as tL}from"util";import{createHash as TD}from"crypto";function zS(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function JS(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))JS(e[t]);return Object.freeze(e)}function tn(e){return JS(structuredClone(e))}function Dm(e,t,i,r){return e.resolveStep({pkg:tn(t),state:tn(i),context:tn(r)})}function GS(e,t,i,r,n,a){return e.resolveNext({pkg:tn(t),state:tn(i),step:tn(r),outcome:tn(n),context:tn(a)})}function ID(e,t,i){return TD("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Fm(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function US(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Dm(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Fm(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:ID(s.runId,s.iteration,o.id),stepId:o.id};return jD(e,s,c,i)}function jD(e,t,i,r){let n=zS(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function KS(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Dm(r,e,t,n):void 0,o=a?Fm(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?GS(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Fm(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as AB}from"node:fs";import jP from"node:path";import YS from"node:path";var $D="comet.native.archive-preflight.v1",OD="comet.native.archive-preflight.v1",HD="comet.native.archive-operation.v1",DD=/^[a-f0-9]{64}$/u,XS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function yd(e,t){return e<t?-1:e>t?1:0}function MD(e,t){if(typeof e!="string"||!DD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function wr(e,t){return e===null?null:MD(e,t)}function BD(e,t){let i=YS.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||YS.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function LD(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function qD(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function VD(e,t){if(!XS.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=wr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=wr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=wr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function WD(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:wr(e.contractHash,"Native archive contract hash"),acceptanceHash:wr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:wr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:wr(e.reportHash,"Native archive report hash"),envelopeHash:wr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:wr(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function zD(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!FD.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(yd);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function JD(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(yd)}function QS(e){if(!XS.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(VD).sort((l,u)=>yd(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D(HD,l)})),r=WD(e.evidence),n=qD(e.workspace),a=[...new Set([...zD(e.findingCodes??[]),...JD({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(yd),o=LD(e.revision),s=BD(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:$D,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:D(OD,c)}}import{createHash as GD}from"node:crypto";import ZS from"node:path";var UD="comet.native.conflict-radar.v1",Dt=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}),KD="comet.native.conflict-radar.v1",YD="comet.native.conflict-radar-signals.v1",XD=/^[a-f0-9]{64}$/u,iE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QD=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),ZD=new Set(["capability","operation","baseHash"]),eF=new Set(["path","kind"]);function so(e,t){return e<t?-1:e>t?1:0}function Mm(e){return Buffer.byteLength(e,"utf8")}function Bm(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Lm(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Mm(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function tF(e,t){let i=Lm(e,t,Dt.maxArtifactPathBytes),r=ZS.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||ZS.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function rE(e,t){if(typeof e!="string"||!XD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function iF(e,t){let i=Bm(e,ZD,t),r=Lm(i.capability,`${t} capability`,Dt.maxCapabilityBytes);if(!iE.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:rE(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function rF(e,t){let i=Bm(e,eF,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:tF(i.path,`${t} path`),kind:i.kind}}function nF(e,t){let i=Bm(e,QD,`Conflict radar change ${t}`),r=Lm(i.name,`Conflict radar change ${t} name`,Dt.maxNameBytes);if(!iE.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>Dt.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>Dt.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>iF(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>so(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>rF(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>so(c.path,l.path)||so(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:rE(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function aF(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Dt.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(nF).sort((n,a)=>so(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Dt.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Dt.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function oF(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function sF(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function cF(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function lF(e,t){let i=[],r=GD("sha256").update(`${YD}
|
|
263
|
+
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(ks(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Dt.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(oF(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=sF(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:cF(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function eE(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function uF(e,t){return eE(e.classification)-eE(t.classification)||so(e.left,t.left)||so(e.right,t.right)}function tE(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:UD,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function nE(e){let t=aF(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(lF(t[s],t[c]));i.sort(uF);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=D(KD,{changes:t,relationships:r}),a=i.slice(0,Dt.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=tE(t,i,a,n);for(;a.length>0&&Mm(JSON.stringify(o))>Dt.maxSerializedBytes;)a=a.slice(0,-1),o=tE(t,i,a,n);if(Mm(JSON.stringify(o))>Dt.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as pM}from"node:crypto";import{promises as _i}from"node:fs";import Xi from"node:path";import{createHash as fE}from"node:crypto";import aE from"path";var qm="comet.native.implementation-scope.v2",hE="comet.native.content-snapshot-projection.v1",pc="comet.native.content-snapshot-projection.v1",pE="comet.native.implementation-scope.v2",dF="comet.native.unresolved-scope-id.v1",fF="comet.native.scope-detail-overflow.v1",hF="comet.native.snapshot-projection-overflow.v2",Jm=/^[a-f0-9]{64}$/u,aa=1024*1024,pF=128,mF=128;function ft(e,t){return e<t?-1:e>t?1:0}function Vm(e){if(!Jm.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function vF(e,t){return e===t?0:e===null?-1:t===null?1:ft(e,t)}function nn(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 i=aE.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||aE.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function mE(e,t){return e==="."?e:nn(e,t)}function co(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function gF(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:nn(e.path,`${t} path`),hash:e.hash,size:co(e.size,`${t} size`),type:"file"}}function wF(e,t){return{path:mE(e.path,`${t} path`),size:e.size===null?null:co(e.size,`${t} size`),type:e.type,reason:e.reason}}function yF(e,t){return ft(e.path,t.path)||ft(e.hash,t.hash)||e.size-t.size}function NF(e,t){return ft(e.path,t.path)||ft(e.reason,t.reason)||ft(e.type,t.type)||(e.size??-1)-(t.size??-1)}function vc(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
264
|
+
`,"utf8")}function rn(e,t,i){let r=`${t}
|
|
265
|
+
${ks(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function bF(e){if(vc(e)<=aa)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=fE("sha256");a.update(`${hF}
|
|
266
|
+
`),e.omissionOverflow&&rn(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,rn(a,"omission",f)},s=f=>{r+=1,n+=1,rn(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;vc(u)>aa;){if(i.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(i.length/4));for(let m=0;m<h;m+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-h))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function Wm(e){let t=fr(e),i=t.entries.map((n,a)=>gF(n,`Snapshot entry ${a}`));if(i.sort(yF),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>wF(n,`Snapshot omission ${a}`));return r.sort(NF),bF({schema:hE,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:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function gc(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:nn(r.path,`Declared artifact ${i} path`),kind:r.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((i,r)=>ft(i.path,r.path)||ft(i.kind,r.kind))}function wc(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function oE(e){return e?{hash:e.hash,size:e.size}:null}function Gm(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:ft(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=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&&i({path:u,kind:c?l?"modified":"removed":"added",before:oE(c),after:oE(l)})}}function vE(e,t){return{...e,attributedTo:t.filter(i=>wc(i,e.path))}}function Um(e){let t=gc(e.declaredArtifacts),i=[];return Gm(e.baseline,e.current,r=>{i.push(vE(r,t))}),i}function yr(e,t){return{id:`scope:${D(dF,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function kF(e,t){let i=t.omitted.map(r=>yr({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(yr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(yr({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`)),i}function sE(e,t){return kF(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function zm(e,t){return ft(e.kind,t.kind)||ft(e.source,t.source)||vF(e.path,t.path)||ft(e.id,t.id)}function SF(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(zm)}function gE(e){return[...new Set(e.map((t,i)=>nn(t,`Git path ${i}`)))].sort(ft)}function cE(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 EF(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 wE(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=gE(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:cE(e.baseCommit,"Native external drift base commit"),targetBranch:EF(e.targetBranch,"Native external drift target branch"),targetCommit:cE(e.targetCommit,"Native external drift target commit"),paths:t}}function yE(e){if(typeof e.contractHash!="string"||!Jm.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:gc(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:gE(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:wE(e.externalDrift)}}}function PF(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Gm(e,t,h=>{let m=i.some(p=>wc(p,h.path));if(d+=1,c.push(h.path),!m&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<pF){let p=vE(h,i),v=vc(p);l+v<=aa?(a.push(p),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function NE(e,t){return yr({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 RF(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 i={changes:co(Number(t[1]),"Scope overflow change count"),unresolved:co(Number(t[2]),"Scope overflow unresolved count"),unattributed:co(Number(t[3]),"Scope overflow unattributed count")},r=na(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(NE(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function CF(e){let t=fE("sha256");t.update(`${fF}
|
|
267
|
+
`);let i=0;Gm(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){rn(t,"change",n);let a=0;for(let o of e.declaredArtifacts)wc(o,n.path)&&(a+=1,rn(t,"change-attribution",o));rn(t,"change-end",{attributionCount:a}),a===0&&rn(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&rn(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function bE(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=PF(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(L=>wc(L,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(pc,e),c=D(pc,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=mF)break;l.push(yr({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...sE("baseline",e),...sE("current",t),...o.totalChanges===0&&a===null?[yr({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(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},m=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(vi=>vi.attributedTo.length===0&&!u.has(vi.path)),P=o.totalChanges-N.length,L=o.totalUnattributed-w.length,H=d-R.detailedOmissionCount,nt=L+H,Pe=[...w.map(vi=>yr({kind:"unattributed-change",source:"implementation-scope",path:vi.path,evidence:{after:vi.after,before:vi.before,changeKind:vi.kind}},`Changed path is not covered by a declared artifact: ${vi.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...nt>0?[NE(R.overflowHash,{changes:P,unattributed:L,unresolved:nt})]:[]],fe=SF(Pe),Oi=R.includeGitAdvisory?h():void 0;return{schema:qm,contractHash:r,baselineProjectionRef:Vm(s),baselineProjectionHash:s,currentProjectionRef:Vm(c),currentProjectionHash:c,complete:fe.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:fe,noCodeReason:a,...Oi?{gitAdvisory:Oi}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},p=o.candidates.length,v=l.length,g=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:y});if(vc({...R,scopeHash:y})<=aa)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let S=o.totalChanges>p||d>v?CF({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:v}):y,k=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:S}),b={...k,scopeHash:D(pE,k)};if(vc(b)>aa)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Km(e){let t=Wm(e.baseline),i=Wm(e.current),r=yE(e);return{authority:r,baseline:t,current:i,scope:bE(t,i,r)}}var xF=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function Ki(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function na(e,t){if(typeof e!="string"||!Jm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function lE(e,t,i){let r=Vm(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function lo(e,t){let i=Ki(e,"Native snapshot projection");if(Yi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==hE)throw new Error("Native snapshot projection schema is invalid");let r=fr({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=Wm(r);if(D(pc,i)!==D(pc,n))throw new Error("Native snapshot projection is not canonical");let a=D(pc,n);if(t!==void 0&&na(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Ym(e,t){let i=Ki(e,`Declared artifact ${t}`);if(Yi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:nn(i.path,`Declared artifact ${t} path`),kind:i.kind}}function uE(e,t){if(e===null)return null;let i=Ki(e,t);return Yi(i,["hash","size"],[],t),{hash:na(i.hash,`${t} hash`),size:co(i.size,`${t} size`)}}function dE(e,t){let i=Ki(e,`Implementation change ${t}`);if(Yi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Ym),n=gc(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=uE(i.before,`Implementation change ${t} before`),o=uE(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.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:nn(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function AF(e,t){let i=Ki(e,`Unresolved scope ${t}`);Yi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?mE(i.path,`Unresolved scope ${t} path`):nn(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function mc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>nn(n,`${t} ${a}`)),r=[...new Set(i)].sort(ft);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function kE(e){let t=Ki(e,"Native implementation external drift");if(Yi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=mc(t.paths,"Native external drift paths");return wE({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function uo(e){let t=Ki(e,"Native implementation scope"),i=[...xF].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(Yi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==qm)throw new Error("Native implementation scope schema is invalid");let r=na(t.contractHash,"Implementation scope contractHash"),n=na(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=lE(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=na(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=lE(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(Ym);if(JSON.stringify(c)!==JSON.stringify(gc(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(dE),u=[...l].sort((w,P)=>ft(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>wc(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(dE),h=t.externalDrift===void 0?void 0:kE(t.externalDrift),m=new Set(h?.paths??[]),p=l.filter(w=>w.attributedTo.length===0&&!m.has(w.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(AF),g=v.filter(w=>w.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=g[0]===void 0?null:RF(g[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,S=[...p.map(w=>yr({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(y?.changes??0)===0&&E===null?[yr({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")]:[]],k=v.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(zm))||new Set(v.map(w=>w.id)).size!==v.length||JSON.stringify(k)!==JSON.stringify(S.sort(zm))||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 w=Ki(t.gitAdvisory,"Implementation scope Git advisory");if(Yi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=mc(w.changedPaths,"Git changed paths"),L=mc(w.pathsPresentInSnapshotChanges,"Git present paths"),H=mc(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),nt=[...L,...H].sort(ft);if(JSON.stringify(nt)!==JSON.stringify(P)||H.some(Pe=>l.some(fe=>fe.path===Pe)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:L,pathsAbsentFromSnapshotChanges:H}}let R={schema:qm,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:E,...b?{gitAdvisory:b}:{},...h?{externalDrift:h}:{}},N=na(t.scopeHash,"Implementation scope scopeHash");if(D(pE,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function _F(e){let t=Ki(e,"Native implementation scope authority");if(Yi(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 i=t.declaredArtifacts.map(Ym);if(JSON.stringify(i)!==JSON.stringify(gc(i)))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 r;t.gitChangedPaths!==void 0&&(r=mc(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:kE(t.externalDrift),a=yE({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...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 yc(e){let t=Ki(e,"Native implementation scope bundle");Yi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=_F(t.authority),r=lo(t.baseline),n=lo(t.current),a=uo(t.scope),o=bE(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function SE(e){let t=uo(e.scope);return yc({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})}import EE from"node:path";var RE=/^[a-f0-9]{64}$/u;var TF="comet.native.acceptance-trace.v2",IF="comet.native.partial-allowance.v1",jF="comet.native.verification-evidence.v2";function Nr(e,t){if(!RE.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function CE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function xE(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 Xm(e,t,i=2e3){let r=St(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Nc(e,t){let i=EE.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||EE.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function $F(e,t,i){let r=Nc(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=Hi(r),a=r.toLowerCase(),o=i?Nc(i,"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"}): ${r}`);return r}function Qm(e){let t=Nc(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 fo(e,t){return e<t?-1:e>t?1:0}function Nd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function bd(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function AE(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function PE(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function OF(e){let t=Nd(e,"Native acceptance trace");if(bd(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"||!RE.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 i=Nc(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=Nd(o,`Native acceptance trace entry ${s}`);if(bd(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=>Qm(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(fo))||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:Nc(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Xm(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>fo(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Nr(t.traceHash,"Native acceptance trace hash");if(D(TF,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function kd(e){let t=Nd(e,"Native partial allowance");if(bd(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(fo))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:xE(t.change),scopeHash:Nr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Xm(t.reason,"Partial allowance reason"),confirmedSummary:Xm(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:CE(t.sourceRevision),confirmedAt:AE(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Nr(t.allowanceHash,"Native partial allowance hash");if(D(IF,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function bc(e){let t=Nd(e,"Native verification evidence");if(bd(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 i=Nr(t.implementationScopeHash,"Native verification implementation scope hash"),r=OF(t.acceptanceTrace),n=Nr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.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:Nr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Qm(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(fo)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(fo);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Qm(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(fo)))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:xE(t.change),sourceRevision:CE(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Nr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:PE(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:$F(t.reportRef,"Native verification report ref"),reportHash:Nr(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:PE(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:AE(t.createdAt,"Native verification timestamp")},d=Nr(t.envelopeHash,"Native verification envelope hash");if(D(jF,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import _E from"node:path";var TE="comet.native.check-receipt.v1",HF="comet.native.check-receipt.v1",ho="scoped-text-safety",Zm=1,Ft=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),DF=/^[a-f0-9]{64}$/u,FF=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MF="comet.native.checker-policy.v1",BF="comet.native.check-input.v1",LF=2048,IE=D(MF,{policy:ho,version:Zm,limits:Ft,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),qF=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),jE=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],OE=["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"],VF=new Set(OE);function an(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function on(e,t,i,r=[]){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 br(e,t){if(typeof e!="string"||!DF.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function HE(e,t){let i=Yt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function $E(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function WF(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>LF||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=_E.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||_E.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function zF(e){let t=an(e,"Native check receipt checker");on(t,["policy","version","hash","limits"],"Native check receipt checker");let i=an(t.limits,"Native check receipt limits");if(on(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ho||t.version!==Zm||t.hash!==IE||i.maxFiles!==Ft.maxFiles||i.maxFileBytes!==Ft.maxFileBytes||i.maxTotalBytes!==Ft.maxTotalBytes||i.maxIssues!==Ft.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ho,version:Zm,hash:IE,limits:{...Ft}}}function JF(e){let t=an(e,"Native check receipt contract");return on(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:br(t.expectedHash,"Native check expected contract hash"),beforeHash:br(t.beforeHash,"Native check before contract hash"),afterHash:br(t.afterHash,"Native check after contract hash")}}function GF(e){let t=an(e,"Native check receipt implementation");return on(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:br(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:br(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:br(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:br(t.afterSnapshotHash,"Native check after snapshot hash")}}function UF(e,t){let i=an(e,`Native check batch ${t}`);on(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Yt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Yt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Yt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Yt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Yt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Yt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Ft.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Ft.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function KF(e){let t=an(e,"Native check receipt counts");on(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Yt(t.filesSelected,"Native check filesSelected"),filesScanned:Yt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Yt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Yt(t.bytesScanned,"Native check bytesScanned"),issueCount:Yt(t.issueCount,"Native check issueCount"),recordedIssueCount:Yt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(UF):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Ft.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Ft.maxFiles||i.bytesScanned>Ft.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function YF(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||jE.indexOf(e.kind)-jE.indexOf(t.kind)}function XF(e){if(!Array.isArray(e)||e.length>Ft.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=an(r,`Native check issue ${n}`);if(on(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!qF.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:WF(a.path,`Native check issue ${n} path`),line:HE(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(YF);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function QF(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!VF.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=OE.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function ZF(e){return D(BF,e)}function Sd(e){let t=an(e,"Native check receipt");if(on(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==TE)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!FF.test(t.change))throw new Error("Native check receipt change name is invalid");let i=HE(t.sourceRevision,"Native check source revision"),r=zF(t.checker),n=JF(t.contract),a=GF(t.implementation),o=ZF({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(br(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=$E(t.startedAt,"Native check receipt startedAt"),c=$E(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=KF(t.counts),u=XF(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=QF(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Ft.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Ft.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:TE,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=br(t.receiptHash,"Native check receipt content hash");if(D(HF,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}var tv="comet.native.verification-receipt.v3",eM=tv,tM="comet.native.declared-artifacts.v1",iM=/^[a-f0-9]{64}$/u,rM=/^acceptance-[a-f0-9]{64}$/u,nM=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aM=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,oM=4096,sM=256,cM=1024;function po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function sn(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function kr(e,t){if(typeof e!="string"||!iM.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ai(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=St(e).trim();if(!i||i.length>oM||i!==e.trim())throw new Error(`${t} is invalid`);return i}function ev(e,t){let i=Ai(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function kc(e,t,i=Ai,r=!1,n=sM){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function lM(e,t){if(typeof e!="string"||!rM.test(e))throw new Error(`${t} is invalid`);return e}function uM(e){let t=po(e,"Native verification receipt bindings");if(sn(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!nM.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:kr(t.contractHash,"Native verification receipt contract hash"),scopeHash:kr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:kr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:kr(t.artifactHash,"Native verification receipt artifact hash")}}function dM(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=aM.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function fM(e,t,i,r){let n=po(t,`Native ${e} evidence`);if(e==="automated-check"){if(sn(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=ev(n.startedAt,"Native automated-check start time"),o=ev(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(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=po(n.worktree,"Native automated-check worktree");if(sn(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=po(n.afterFence,"Native automated-check after fence");if(sn(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ai(n.executable,"Native automated-check executable"),args:kc(n.args,"Native automated-check arguments",Ai,!0),cwd:Ai(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:Ai(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:kr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:kr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:kr(n.outputHash,"Native automated-check output hash"),outputSummary:Ai(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){sn(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=dM(n.checkReceiptRef);if(kr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:kc(n.subjects,"Native static inspection subjects",Ai,r==="required-check"),rule:Ai(n.rule,"Native static inspection rule"),resultSummary:Ai(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return sn(n,["steps","observations"],"Native manual-evidence evidence"),{steps:kc(n.steps,"Native manual evidence steps"),observations:kc(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function hM(e){let t=po(e,"Native verification receipt");if(sn(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 i=t.kind,r=t.role,n=t.status,a=Ai(t.actor,"Native verification receipt actor"),o=kc(t.acceptanceIds,"Native receipt acceptance IDs",lM,r==="required-check",cM).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:tv,kind:i,role:r,status:n,bindings:uM(t.bindings),acceptanceIds:o,actor:a,issuedAt:ev(t.issuedAt,"Native verification receipt issue time"),evidence:fM(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==ho||s.actor!==`native-runtime:${ho}`))throw new Error("Native required check policy identity is invalid");return s}function Ed(e){let t=po(e,"Native verification receipt");if(sn(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==tv)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=hM(r),a=kr(t.receiptHash,"Native verification receipt hash");if(D(eM,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function iv(e){return D(tM,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var BE=/^[a-f0-9]{64}$/u,cn=aa,qY=3*cn;function rv(e,t){let i=Xi.relative(e,t);return i===""||!Xi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xi.sep}`)}function mM(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pd(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function DE(e){let t=await _i.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await _i.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function vM(e,t){let i=Xi.resolve(e),r=Xi.resolve(t);if(!rv(i,r))throw new Error("Native evidence path is outside its change");let n=[await DE(i)],a=i;for(let o of Xi.relative(i,r).split(Xi.sep).filter(Boolean)){a=Xi.join(a,o);let s=await DE(a);if(!rv(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function FE(e){for(let t of e){let i=await _i.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!mM(t,i)||await _i.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function gM(e,t,i={}){let r=await vM(t,Xi.dirname(e));await i.afterParentChainCaptured?.();let n=await _i.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await _i.realpath(e);if(!rv(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await _i.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),_i.lstat(e),_i.realpath(e)]);if(await FE(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Pd(s,n)||!Pd(s,c))throw new Error("Native evidence document changed while opening");if(s.size>cn)throw new Error(`Native evidence document exceeds ${cn} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=cn+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>cn)throw new Error(`Native evidence document exceeds ${cn} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await i.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),_i.lstat(e),_i.realpath(e)]);if(await FE(r),!m.isFile()||m.isSymbolicLink()||p!==a||!Pd(s,h)||!Pd(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function vo(e,t){if(!BE.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function LE(e){return vo("reports",e)}async function wM(e,t,i,r,n){if(!BE.test(i))throw new Error("Native report evidence hash is invalid");let a=await oa({paths:e,name:t,kind:"reports",hash:i,hooks:r,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!==i||typeof o.content!="string"||pM("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function mo(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function yM(e,t,i,r,n){let a=vo(i,r);return n?Xi.join(n,...a.split("/")):Lr(M(e,t),a)}async function oa(e){let t=yM(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),gM(t,i,e.hooks)}function ME(e,t){return lo(e,t)}function NM(e,t){let i=uo(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function bM(e,t,i){let r=kd(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function kM(e,t,i){let r=bc(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function SM(e,t,i,r=!1,n){let a=await Rd(e,t,i.implementationScopeRef,void 0,n);if(r&&await wM(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await qE(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Sc(e,t,i,r,n){let a=mo(i,"scopes"),o=NM(await oa({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=mo(o.baselineProjectionRef,"snapshots"),c=mo(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([oa({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ME(d,s)),oa({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ME(d,c))]);return SE({baseline:l,current:u,scope:o})}async function Rd(e,t,i,r,n){return(await Sc(e,t,i,r,n)).scope}async function qE(e,t,i,r,n){let a=mo(i,"allowances");return bM(await oa({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Ec(e,t,i,r,n){let a=mo(i,"receipts"),o=Ed(await oa({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function go(e,t,i,r,n){let a=mo(i,"verifications"),o=kM(await oa({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await SM(e,t,o,!1,n),o}var EM=4096;async function PM(e,t=Dt.maxChanges){try{let i=await $t({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function VE(e,t){let i=await je(e,t),[r,n]=await Promise.all([i.implementation_scope?Rd(e,t,i.implementation_scope):null,lt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Cd(e,t,i={}){let n=(await PM(e,EM)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await VE(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await VE(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=nE([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as qM}from"fs";import VM from"path";import{isDeepStrictEqual as _d}from"util";var wo={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var RM=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function CM(e,t){return e<t?-1:e>t?1:0}function xM(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!RM.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(CM)}function nv(e=[]){return xM(e,"Native repair failed check IDs",wo.maxFailedCheckIds,!0)}function WE(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function AM(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:WE(e.failedAcceptanceIds,t.failedAcceptanceIds)&&WE(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function av(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(AM(r,a))break;i+=1,r=a}return i}function xd(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var zE="repairStagnation",Xt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},TM=/^[a-f0-9]{64}$/u;var IM=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),jM=["data","runId","sequence","timestamp","type"],JE=["disposition","overrideSummaryHash","signatureHash"],$M=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],GE=12;function sv(e,t){return e<t?-1:e>t?1:0}function UE(e,t,i){let r=Object.keys(e).sort(sv);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Ad(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Pc(e,t){if(typeof e!="string"||!TM.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function OM(e){if(!Array.isArray(e)||e.length>wo.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(sv)}function KE(e){if(typeof e!="string"||e.length===0||e.length>Xt.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function ov(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Xt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Xt.maxTextCharacters&&(!n||e.length>Xt.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Xt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Xt.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>ov(s,t+1,i,`${r}[${c}]`));return}let a=Ad(e,r),o=Object.keys(a);if(o.length>Xt.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xt.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Xt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");ov(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function HM(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function DM(e,t,i){let r=Ad(e,`Native repair trajectory event ${t+1}`);if(UE(r,jM,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(HM(r.timestamp),typeof r.type!="string"||!IM.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(KE(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return ov(r.data,0,n,"Native trajectory event data"),Ad(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function cv(e){let t=Ad(e,"Native repair trajectory projection"),i=Object.keys(t).sort(sv),r=i.length===JE.length&&i.every((l,u)=>l===JE[u]);r||UE(t,$M,"Native repair trajectory projection");let n=Pc(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Pc(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Pc(t.contractHash,"Native repair trajectory contract hash"),s=OM(t.failedAcceptanceIds),c=nv(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function FM(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function MM(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??GE;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=av({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<wo.warningAtConsecutiveFailures?"continue":a<wo.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function BM(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??GE;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function YE(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=KE(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=DM(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Xt.maxTotalDataNodes||c>Xt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?Pc(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Pc(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,zE)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=cv(f[zE]);if(FM(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),MM(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");BM(m,i,r);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(r=m,i.length>wo.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function XE(e){return YE(e).history}function QE(e){let t=YE(e).latestProjection;return t?{...t}:null}var Qi={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:[]},Rc=B("comet-native-runtime:v3:scope-reopen"),LM=[{skillVersion:"3",skillHash:B("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:B("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:B("comet-native-runtime:v1")}];function ZE(e){return e.skillVersion===Qi.definition.metadata.version&&e.skillHash===Rc||LM.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var lv={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function ln(e){let i={sequence:(await kt(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Yb(e.changeDir,e.run.trajectoryRef,i),i}async function sa(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:B(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Xb(e.changeDir,e.run.checkpointRef,t),t}function eP(e){return B(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var cP=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],WM=new Set(cP),lP=new Set([...cP,"minimum_runtime_version","revision"]),zM=new Set([...lP,"operation"]),JM=512*1024,uv=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),GM=new Set([...uv,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Cc=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function ht(e,t){return VM.join(M(e,t),"transition.json")}function UM(e){return`transition-${e}`}async function KM(e,t,i){let r=UM(t);return cr(e,r,i)}async function un(e,t,i,r){let n=await KM(e,t,i);try{return await r()}finally{await lr(n)}}function Id(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function fv(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Td(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Zi(e,t){return _d(e,t)}function dv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!GM.has(u)),a=[...uv].find(u=>!Object.hasOwn(i,u)),o=uv.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(xd(i.summary,"Native transition journal event summary"),St(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(xd(i.noCodeReason,"Native transition journal event no-code reason"),St(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?cv(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function YM(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return dv({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return dv(e,t)}function hv(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?YM(e.eventData,e.evidenceHash):dv(e.eventData,e.evidenceHash),n=Qr(e.nextRun),a=e.previousRun===null?null:Qr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function tP(e,t,i=!1){if(e.skill!==Qi.definition.metadata.name||(i?!ZE(e):e.skillVersion!==Qi.definition.metadata.version||e.skillHash!==Rc)||e.orchestration!==Qi.definition.orchestration.mode||e.pendingRef!==zt.pendingRef||e.trajectoryRef!==zt.trajectoryRef||e.contextRef!==zt.contextRef||e.artifactsRef!==zt.artifactsRef||e.checkpointRef!==zt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function iP(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function rP(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function pv(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(tP(o,"next Run",r||a!==null),rP(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(tP(a,"previous Run",!0),rP(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!_d(iP(a),iP(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function XM(e,t,i){return B(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function uP(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function nP(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function mv(e,t,i,r,n=!1){let a=i.eventData,o=nP(e),s=nP(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&_d(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&_d(e.spec_changes,t.spec_changes),l=eP({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=XM(e.name,a.summary,t.spec_changes),l=B(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function vv(e,t){let i=Id(e);if(fv(i,zM),i.schema!==qr)throw new Error(`Expected Native transition schema ${qr}`);let r=Td(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${qr} minimum_runtime_version must be ${3}`);let n=Td(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=hv(i,t),o=jt(i.previousState),s=jt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(mv(o,s,a,i.operation),pv(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:qr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function QM(e,t){let i=Id(e);if(fv(i,WM),i.schema!==Ln)throw new Error(`Expected Native transition schema ${Ln}`);let r=hv(i,t,!0),n=qn(i.previousState),a=qn(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return mv(n,a,r,uP(n,a,r.eventData),!0),pv(n,a,r,!0),{schema:Ln,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function gv(e,t){let i=Id(e);if(fv(i,lP),i.schema!==dr)throw new Error(`Expected Native transition schema ${dr}`);if(Td(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${dr} minimum_runtime_version must be 2`);let n=Td(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=hv(i,t,!0),o=Vi(i.previousState),s=Vi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(mv(o,s,a,uP(o,s,a.eventData),!0),pv(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:dr,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function ZM(e,t){let i=Id(e);if(i.schema===qr)return{status:"current",journal:vv(i,t)};if(i.schema===Ln)return{status:"migration-required",journal:QM(i,t)};if(i.schema===dr)return{status:"migration-required",journal:gv(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function wv(e,t){let i=ht(e,t),r=j(e,i);await T(r,i);try{let n=await ge({root:r,file:i,maxBytes:JM,label:`Native transition journal ${t}`});return ZM(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Sr(e,t){let i=await wv(e,t);if(!i)return null;if(i.status==="migration-required")throw new Cc(t);return i.journal}function aP(e,t){if(Zi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Zi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function oP(e,t){if(Zi(e,t.nextState))return"next";if(Zi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function eB(e){let{journal:t}=e;return dP({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function dP(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function sP(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=eB({sequence:a.index+1,journal:t,type:a.event.type});if(!Zi(dP(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function xc(e,t,i){if(await eo(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Gu(e,t);let r=await Sr(e,t);if(!r)return null;let n=M(e,t),a=sP(await kt(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Je(n),je(e,t)]),c=aP(o,r),l=oP(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Jn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!Zi(await Je(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let v=await Js(e,r.nextState,r.previousState.revision);if(!Zi(v,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!Zi(await je(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Sr(e,t);if(!u||!Zi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=sP(await kt(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await ln({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await ln({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await sa({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,m]=await Promise.all([Je(n),je(e,t)]);aP(h,{...r,previousRun:r.nextRun}),oP(m,{...r,previousState:r.nextState});let p=await Sr(e,t);if(!p||!Zi(p,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await qM.rm(ht(e,t),{force:!0}),r.nextState}async function fP(e,t,i){return F(e,`continue transition ${t}`,()=>un(e,t,`continue transition ${t}`,()=>xc(e,t,i)))}import hP from"node:path";var tB="comet.native.contract.v1",iB="comet.native.acceptance-set.v1",pP=/^[a-f0-9]{64}$/u,Ac={maxAcceptanceCriteria:Es.maxCriteria};function mP(e,t){let i=hP.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||hP.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function vP(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
268
|
+
`))}function rB(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(pP))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(pP))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=mP(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:vP(e.markdown)},markdown:e.markdown}}function nB(e,t){return gP(e.id,t.id)}function gP(e,t){return e<t?-1:e>t?1:0}function wP(e){let t=mP(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(rB).sort((d,f)=>gP(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=fu(e.briefMarkdown,t,Ac.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...hu(f,d.source,Ac.maxAcceptanceCriteria-a.length)),a.push(...pu(f,d.source,Ac.maxAcceptanceCriteria-a.length)));if(a.sort(nB),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ac.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ac.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:vP(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(iB,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(tB,u)}}var Ti={maxSpecs:64,maxFileBytes:$o,maxTotalBytes:4*1024*1024};async function yo(e){if(e.specChanges.length>Ti.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ee({root:e.changeDir,ref:e.briefRef,maxBytes:Ti.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ee({root:e.changeDir,ref:n.source,maxBytes:Ti.maxFileBytes});if(i+=a.size,i>Ti.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:wP({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as NB}from"node:child_process";import{promisify as bB}from"node:util";import{promises as dB}from"fs";import No from"path";var fn={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},bo=/^[a-f0-9]{64}$/u;function jd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $d(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function dn(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function yP(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function yv(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function aB(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||No.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=No.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Nv(e,t){return No.join(M(e,t),"checkpoints","progress.json")}function hn(e,t){return No.join(M(e,t),"checkpoint-journal.json")}function bv(e,t,i){if(!bo.test(i))throw new Error("Native checkpoint manifest hash is invalid");return No.join(M(e,t),"checkpoints","manifests",`${i}.json`)}function oB(e){if(!bo.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function kv(e,t,i){let r=await ge({root:e,file:t,maxBytes:fn.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function sB(e,t){let i=jd(e,`checkpoint manifest artifact ${t}`);$d(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=aB(dn(i.path,`checkpoint artifact ${t} path`,4096)),n=Hi(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!bo.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:yv(i.size,`checkpoint artifact ${t} size`)}}function Od(e,t){let i=jd(e,"Native checkpoint manifest");if($d(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>fn.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(sB),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=yv(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>fn.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Sv(e){return B(JSON.stringify(Od(e,e.change)))}function Ev(e,t){let i=jd(e,"Native progress checkpoint");if($d(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=yP(i.previousRevision,"Native checkpoint previousRevision"),a=yP(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=dn(i.manifestHash,"Native checkpoint manifestHash",64);if(!bo.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=oB(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=dn(i.inputHash,"Native checkpoint inputHash",64);if(!bo.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=dn(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=yv(i.artifactCount,"Native checkpoint artifactCount");if(u>fn.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=dn(i.summary,"Native checkpoint summary"),f=dn(i.nextAction,"Native checkpoint nextAction");if(St(d)!==d||St(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:dn(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function cB(e,t){let i=jd(e,"Native checkpoint journal");if($d(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=jt(i.previousState),n=jt(i.nextState),a=Ev(i.checkpoint,t),o=Od(i.manifest,t),s=dn(i.inputHash,"Native checkpoint journal inputHash",64),c=B(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!bo.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Sv(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function lB(e,t,i){let r=No.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=pf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ge({root:e.projectRoot,file:r,maxBytes:fn.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function uB(e,t){let i=Nv(e,t),r=j(e,i);await T(r,i);try{return Ev(await kv(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Pv(e,t,i){let r=bv(e,t,i),n=j(e,r);await T(n,r);let a=await kv(n,r,"Native checkpoint manifest"),o=Od(a,t);if(Rv(e,o),Sv(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function pn(e,t){let i=hn(e,t),r=j(e,i);await T(r,i);try{let n=cB(await kv(r,i,"Native checkpoint journal"),t);return Rv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function NP(e,t,i,r){let n=Od(i,t);Rv(e,n);let a=Sv(n),o=bv(e,t,a),s=j(e,o);await T(s,o);try{let c=await Pv(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await ve(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function Rv(e,t){for(let i of t.artifacts){let r=pf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function bP(e,t){let i=Ev(t,t.change),r=await Pv(e,i.change,i.manifestHash),n=B(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Nv(e,t.change),o=j(e,a);await T(o,a),await ve(a,i,{containedRoot:o})}async function kP(e){let t;try{t=await uB(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Nv(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Pv(e.paths,e.name,t.manifestHash);let a=B(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await lB(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:bv(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function SP(e,t,i){let r=await pn(e,t);if(!r)return null;if(await NP(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Js(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await bP(e,r.checkpoint),await i?.afterProgressWritten?.(r),await dB.rm(hn(e,t),{force:!0}),r}async function EP(e,t,i){return F(e,`continue checkpoint ${t}`,()=>un(e,t,`continue checkpoint ${t}`,async()=>(await xc(e,t),SP(e,t,i))))}import{constants as Cv,promises as fi}from"node:fs";import ko from"node:path";var fB=/^[a-f0-9]{64}$/u,hB=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,_c=512*1024;function pB(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Hd(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ye(i,r)?q(i,r):q(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mB(e,t){let i=ko.resolve(e),r=ko.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...ko.relative(i,r).split(ko.sep).filter(Boolean)]){o&&(a=ko.join(a,o));let s=await fi.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await fi.realpath(a);if(n.length>0&&!$(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function PP(e){for(let t of e){let i=await fi.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!pB(t,i)||await fi.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function vB(e){if(!fB.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function gB(e){let t=hB.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function wB(e,t,i){return Lr(M(e,t),vB(i))}async function yB(e,t,i){let r=await mB(i,ko.dirname(e)),n=await fi.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>_c)throw new Error(`Native check receipt exceeds ${_c} bytes`);let[a,o]=await Promise.all([fi.realpath(t),fi.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Cv.O_RDONLY|Cv.O_NOFOLLOW|Cv.O_NONBLOCK,c=await fi.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),fi.lstat(e),fi.realpath(e)]);if(await PP(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Hd(n,l)||!Hd(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,m=Buffer.allocUnsafe(16*1024);for(;;){let y=_c+1-h,E=await c.read(m,0,Math.min(m.length,y),null);if(E.bytesRead===0)break;if(h+=E.bytesRead,h>_c)throw new Error(`Native check receipt exceeds ${_c} bytes`);f.push(Buffer.from(m.subarray(0,E.bytesRead)))}let[p,v,g]=await Promise.all([c.stat(),fi.lstat(e),fi.realpath(e)]);if(await PP(r),!v.isFile()||v.isSymbolicLink()||g!==o||!$(a,g)||!Hd(l,p)||!Hd(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function RP(e,t,i){let r=gB(i),n=M(e,t),a=wB(e,t,r),o=j(e,a);await T(o,a);let s=Sd(await yB(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Tc=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var H4=64*1024;var D4=3600*1e3;var F4=bB(NB);var kB=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function xP(e,t){let i=[];for(let r of kB){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function AP(e){if(e.receipt.kind!=="static-inspection")return null;let t=await RP(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var mn=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function SB(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function EB(e){let t=SB(e.bundle.baseline),i=await qp(e.paths,t,{origin:"explicit",now:e.now});return Km({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function TP(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Sc(e.paths,e.state.name,e.state.implementation_scope),i=await yo({changeDir:te(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await EB({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function IP(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await TP(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function PB(e){let t=await ee({root:te(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:DN(t.text)}}function RB(e){let{receipt:t,implementationScope:i}=e,r=[],n=Um({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function CB(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:iv(e.implementationScope.scope.declaredArtifacts)}}async function _P(e){let t=await Ec(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=xP(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new mn([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await AP({paths:e.paths,state:e.state,receipt:t});if(n){let a=RB({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function xB(e){let t=CB({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await _P({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof mn)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await _P({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof mn)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new mn(i)}function xv(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Dd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:xv(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([TP(e),go(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:xv(e.state.verification_result,"stale"),envelope:null};let r=await PB({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await xB({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:xv(e.state.verification_result,"invalid"),envelope:null}}}function _B(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function $P(e){try{return await AB.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function TB(e,t){try{return(await ee({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function IB(e,t,i){let r=ia(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=jP.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await TB(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ee({root:te(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function jB(e,t){return $P(ht(e,t))}async function Fd(e){let t=e.now??new Date,i=await je(e.paths,e.name),r=await lt(e.paths,e.name),n=await Y(e.paths.projectRoot),a=_B(i.name,t),o=jP.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(m=>IB(e.paths,i.name,m))),Dd({paths:e.paths,state:i,now:t}),Cd(e.paths,i.name),eo(e.paths,i.name),to(e.paths,i.name),jB(e.paths,i.name),$P(o)]);return QS({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Av}from"node:fs";import Er from"node:path";var $B="comet.native.archive-tree.v1",OB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function DP(e){let t={...OB,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function OP(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function HP(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function FP(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await $t({root:e,directory:t,label:`Native Archive content directory ${Er.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=OP(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Er.join(t,u.name),f=Er.relative(e,d).replaceAll("\\","/"),h=await Av.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){HP(i,{ref:f,kind:"directory"},r,n),await FP(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await ge({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=m.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);HP(i,{ref:f,kind:"file",hash:m.hash,size:m.size},r,n),await o.verify()}await o.verify();let l=await $t({root:e,directory:t,label:`Native Archive content directory ${Er.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(OP(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Er.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function MP(e,t={}){let i=DP(t);e=Er.resolve(e);let r=await Av.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await FP(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return B(`${$B}\0${o}`)}async function Ii(e,t={}){let i=DP(t);e=Er.resolve(e);let r;try{r=await Av.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ge({root:Er.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Er.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await MP(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Rt}from"node:fs";import We from"node:path";var Tv=16*1024*1024,HB=256*1024,DB=16*1024,Ic="comet.native.archive-cas.v1";function FB(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=We.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function it(e,t){let i=FB(e,t);return T(j(e,i),i)}function vn(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function So(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function Mt(e){let t=await Ii(e.target);if(!vn(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${So(t)}`);return t}async function Iv(e,t){let i=await zi(e,t),r=await ge({root:e.runtimeDir,file:i.journal,maxBytes:HB,label:`Native Archive transaction journal ${t}`}),n=Au(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Md(e,t,i){let r=Au({...t,status:i}),n=await zi(e,r.id);return await ve(n.journal,r,{containedRoot:e.runtimeDir}),r}function Bd(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function BP(e){return{...Bd(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function gn(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function MB(e,t){return gn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pe(e){try{return await Rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function er(e){let t=await Rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=BP(t),r=await ge({root:j(e.paths,e.file),file:e.file,maxBytes:Tv,label:e.label}),n=await Rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!MB(i,BP(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Bd(n),size:r.size}}function BB(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==Ic||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Ic,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function tr(e,t,i,r){let n=await zi(e,t.id),a=We.join(n.backups,".cas"),o=`.${We.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:We.join(a,`${i.id}.original.json`),postRecord:We.join(a,`${i.id}.post.json`),candidate:We.join(a,`${i.id}.candidate`),originalQuarantine:We.join(We.dirname(r),`${o}.original`),rollbackQuarantine:We.join(We.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function hi(e){if(!await pe(e.file))return null;let t=await ge({root:e.paths.runtimeDir,file:e.file,maxBytes:DB,label:`Archive CAS ${e.operation.id} ${e.role} record`});return BB(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Ld(e){let t=await hi(e);if(t){if(!gn(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Wi({root:e.paths.runtimeDir,directory:We.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Ic,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ve(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await hi(e);if(!r||!gn(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Le(e){let t=await er({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!gn(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function LB(e){let t=await er({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Ld({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Le({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function qB(e){if(!await pe(e.quarantine)||await pe(e.target))return;let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([Rt.lstat(e.quarantine),Rt.lstat(e.target)]);if(!gn(Bd(i),Bd(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Rt.unlink(e.quarantine),await t.verify()}async function WP(e){if(await pe(e.quarantine)){await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Rt.rename(e.target,e.quarantine),await t.verify(),await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await qB(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function ca(e){if(!await pe(e.file))return;await Le(e);let t=await Wt({root:j(e.paths,e.file),directory:We.dirname(e.file),label:e.label});await t.verify(),await Le(e),await Rt.unlink(e.file),await t.verify()}async function LP(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await it(e,t.target),n=await it(e,t.backup),a=await Ii(n);if(a!==null){if(!vn(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await Mt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Jr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Tv,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await Mt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function zP(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await tr(e.paths,e.journal,e.operation,e.target),r=await hi({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await pe(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Le({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await LP(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await pe(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await LB({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Le({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await LP(e.paths,e.operation,e.hooks),await WP({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function qP(e){let t=await tr(e.paths,e.journal,e.operation,e.target);return await pe(t.candidate)?(await er({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Wi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Jr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Tv,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function VB(e){let t=e.operation.stagedHash,i=await tr(e.paths,e.journal,e.operation,e.target),r=await hi({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await pe(e.target))return await Le({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await pe(i.candidate)&&await ca({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await pe(e.target)){let c=await qP(e),l=await er({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await er({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!gn(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Ld({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await ca({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await qP(e),a=await er({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Wi({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Le({paths:e.paths,file:n,operation:e.operation,record:{schema:Ic,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Rt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await er({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!gn(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Ld({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await ca({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function WB(e,t,i,r){let n=await it(e,i.target),a=await it(e,i.staged);if(await Mt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await tr(e,t,i,n);(!await hi({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await pe(n))&&await zP({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Ii(n);if(o!==null&&!vn(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${So(o)}`)}await VB({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await Mt({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function zB(e,t,i,r){let n=await it(e,i.target);await zP({paths:e,journal:t,operation:i,target:n,hooks:r}),await Mt({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function JB(e,t){let i=await it(e,t.source),r=await it(e,t.target),[n,a]=await Promise.all([Ii(i),Ii(r)]);if(!(n===null&&vn(a,t.expectedSourceHash,"directory"))){if(!vn(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${So(n)}, target=${So(a)}`);await Rt.mkdir(We.dirname(r),{recursive:!0}),await Rt.rename(i,r),await Mt({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function GB(e,t,i,r){return i.type==="write"?WB(e,t,i,r):i.type==="remove"?zB(e,t,i,r):JB(e,i)}function UB(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function KB(e,t,i,r){let n=await it(e,i.target);if(i.type==="write"){let a=await it(e,i.staged);await Mt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await tr(e,t,i,n),s=await hi({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Le({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await Mt({target:await it(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await hi({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await pe(o.originalQuarantine))await Le({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await Mt({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await Mt({target:await it(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await tr(e,t,i,n),o=await hi({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await pe(a.originalQuarantine))await Le({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await Mt({target:await it(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await Mt({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function JP(e,t,i){let r=t.status==="prepared"?await Md(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Ur(e,r.id),a=UB({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await KB(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await ai(e,r.id,"operation-started",l.id),await GB(e,r,l,i),await ai(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Iv(e,r.id),r}async function YB(e){try{return await Le(e),!0}catch{return!1}}async function XB(e){await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Wt({root:j(e.paths,e.target),directory:We.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Le({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Rt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Le({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function _v(e){if(e.operation.type!=="write")return;let t=await tr(e.paths,e.journal,e.operation,e.target);if(!await pe(t.candidate))return;let i=await er({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await ca({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Ic,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function QB(e,t,i,r){let n=await it(e,i.target),a=await tr(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await hi({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await hi({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await pe(a.candidate)&&await pe(n)){let l=await er({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await er({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});gn(l.identity,u.identity)&&(c=await Ld({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await pe(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Le({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await pe(n)&&!(s!==null&&await YB({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Ii(n);if(vn(u,o)){await _v({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await WP({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await pe(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await pe(n)){if(!s||!await pe(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await XB({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await pe(a.originalQuarantine)&&await ca({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await pe(a.rollbackQuarantine)&&await ca({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await _v({paths:e,journal:t,operation:i,target:n}),await Mt({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function ZB(e,t){let i=await it(e,t.source),r=await it(e,t.target),[n,a]=await Promise.all([Ii(i),Ii(r)]);if(!(vn(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!vn(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${So(n)}, target=${So(a)}`);await Rt.mkdir(We.dirname(i),{recursive:!0}),await Rt.rename(r,i)}}async function GP(e,t,i){let r=await Ur(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Md(e,t,"rolling-back");await ai(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await ZB(e,o):await QB(e,n,o,i));return await ai(e,n.id,"rollback-completed"),n=await Md(e,n,"rolled-back"),n}async function VP(e,t,i){let r=await it(e,i.target);if(i.type==="write"){let n=await tr(e,t,i,r),a=await hi({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Le({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await Mt({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function eL(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await it(e,i.target),n=await tr(e,t,i,r);if(await pe(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await VP(e,t,i),i.expectedTargetHash!==null){let a=await hi({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await pe(n.originalQuarantine)&&await ca({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await _v({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await VP(e,t,i)}async function qd(e,t,i){return i==="commit"&&await eL(e,t),await ai(e,t.id,i),i==="commit"?Md(e,t,"committed"):t}var T9=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var o8=16*1024*1024,Vd=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},jc=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function KP(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Eo.resolve(e.nativeRoot,...i.target.split("/"))}async function YP(e,t,i){let r=await Ur(e,t.id);if(r.some(v=>v.type==="archive-finalized"))return;let n=r.some(v=>v.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let v=t.operations.find(y=>y.id==="archive-change");if(!v||v.type!=="move"||!v.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await Ii(KP(e,t));if(g?.kind!=="directory"||g.hash!==v.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=KP(e,t),o=Eo.join(a,Ve),s=await bk(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=M(e,s.name),l=await Je(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let v=US(Qi,l,new Set,lv,void 0);if(!v.action)throw new Error(v.reason??"Native archive produced no action");u=KS(Qi,v.state,{actionId:v.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},lv,void 0)}let d=B(`archive:${t.id}:${s.name}`),f=await kt(c,u.trajectoryRef),h=f.filter(v=>v.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(v=>v.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let m=h.find(v=>v.type==="state_transitioned"),p={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(m&&t.schema==="comet.native.transaction.v2"&&(!tL(m.data,p)||m.runId!==u.runId||m.timestamp!==t.createdAt||m!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await qd(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await La(e,t,"archive-finalization-started")),!s.archived){let v={...s,archived:!0};await Nk(o,v)}m||(m=await ln({changeDir:c,run:u,type:"state_transitioned",data:p,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await sa({changeDir:c,run:u,trajectoryOffset:m.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Jn(c,u),await lc(e,s.name),t.schema==="comet.native.transaction.v2"?await qd(e,t,"archive-finalized"):await La(e,t,"archive-finalized")}async function jv(e,t){let i=ze(e,t);try{let r=await UP.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await UP.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function iL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Ur(e,t.id)).some(c=>c.type==="operation-started")){let c=await Fd({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new jc(c,"Native Archive facts changed before the first transaction operation")}let o=await JP(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await je(e,t.change),u=await Dd({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await YP(e,o,i);let s=await qd(e,o,"commit");return{journal:s,runtimeCleanupWarning:await jv(e,s.change)}}let r=await db(e,t);await YP(e,r,i);let n=await La(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await jv(e,n.change):null}}function rL(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Eo.resolve(t.projectRoot)!==Eo.resolve(e.projectRoot)||Eo.resolve(t.nativeRoot)!==Eo.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function XP(e){return F(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await cr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await Ot(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Iv(e.paths,e.transactionId):i;return rL(e.paths,r),r.status==="committed"?(r.change&&await jv(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await iL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?GP(e.paths,r):Tu(e.paths,r)}finally{await lr(t)}},{allowedTransactionId:e.transactionId})}import{promises as $c}from"node:fs";import pt from"node:path";var wn=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};function $v(e,t){let i=pt.normalize(e),r=pt.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function eR(e,t){let i=pt.relative(e,t);return i===""||!pt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${pt.sep}`)}function QP(e){return JSON.stringify(e.native)}async function Wd(e,t){let i=await Y(e);if(i&&t){if(QP(i)!==QP(t))throw new Error(`Native worktree configuration differs from the source project: ${pt.join(e,".comet","config.yaml")}`);return!1}return!i&&t?(await Vt(e,t),!0):!1}async function nL(e,t){if(!eR(e,t))return!1;let r=`/${pt.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=he(e,["rev-parse","--git-common-dir"]),a=pt.resolve(e,n),o=pt.join(a,"info","exclude"),s="";try{s=await $c.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(r))return!1;await $c.mkdir(pt.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
269
269
|
`)?"":`
|
|
270
|
-
`;return await
|
|
271
|
-
`,"utf8"),!0}function wB(e,t,i){let r=St.resolve(e,i??St.join(".worktrees",t)),n=St.resolve(e,xe(e,["rev-parse","--git-common-dir"]));if(_P(n,r))throw new Error("Native worktree path cannot be inside the Git common directory");if(Ti(e).some(a=>AP(a,r)))throw new Error(`Native worktree path is already registered: ${r}`);return r}async function yB(e){try{throw await Cd.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function TP(e){let t=St.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 l=pe(t);if(l.isGitWorktree&&l.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:l.currentBranch,targetBranch:l.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:l.currentBranch,targetBranch:l.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let i=pe(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 r=e.changeBranch??`comet/${e.name}`;pm(t,r);let n=i.currentBranch===r,a=e.targetBranch??(n?void 0:i.currentBranch);if(!a)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(pm(t,a),!Eo(t,a))throw new Error(`Native target branch is not a verified local branch: ${a}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let l=!1;if(!n){if(!rc(t))throw new Error("Native branch isolation requires a clean current working directory");if(Eo(t,r))throw new Error(`Native change branch already exists: ${r}`);xe(t,["switch","-c",r,a]),l=!0}let u;try{u=await gv(t,e.sourceConfig)}catch(d){throw new ia(`Native branch preparation is incomplete: ${d.message}`,{isolation:"branch",projectRoot:t,changeBranch:r,targetBranch:a,worktreePath:null,createdBranch:l,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:d})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:r,targetBranch:a},preparation:{isolation:"branch",projectRoot:t,changeBranch:r,targetBranch:a,worktreePath:null,createdBranch:l,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:u}}}if(n){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let l=e.worktreePath?St.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(l&&!AP(l,i.currentWorktreeRoot))throw new Error(`Native worktree path ${l} does not match the current worktree ${i.currentWorktreeRoot}`);let u;try{u=await gv(t,e.sourceConfig)}catch(d){throw new ia(`Native worktree preparation is incomplete: ${d.message}`,{isolation:"worktree",projectRoot:t,changeBranch:r,targetBranch:a,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:d})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:r,targetBranch:a},preparation:{isolation:"worktree",projectRoot:t,changeBranch:r,targetBranch:a,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:u}}}if(Eo(t,r))throw new Error(`Native change branch already exists: ${r}`);let o=wB(i.primaryWorktreeRoot,e.name,e.worktreePath);await yB(o);let s=await gB(i.primaryWorktreeRoot,o),c={isolation:"worktree",projectRoot:o,changeBranch:r,targetBranch:a,worktreePath:o,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:s,configInitialized:!1};try{xe(i.primaryWorktreeRoot,["worktree","add","-b",r,o,a]),c.createdBranch=!0,c.createdWorktree=!0,c.configInitialized=await gv(o,e.sourceConfig)}catch(l){throw new ia(`Native worktree preparation is incomplete: ${l.message}`,c,{cause:l})}return{projectRoot:o,binding:{isolation:"worktree",changeBranch:r,targetBranch:a},preparation:c}}var IP=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],yv=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",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 remove Record a complete capability removal intent.","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:IP,output:"Human-readable text by default; use --json for a structured command envelope.",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] [--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.","--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, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","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 remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],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."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries or inspect the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction.",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> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
|
|
272
|
-
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, 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 Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," 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."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. 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','comet native next session-timeout --summary "Implementation changed" --return-to-build','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]
|
|
273
|
-
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 Inspect readiness without rerunning verification.","--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 plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function
|
|
270
|
+
`;return await $c.appendFile(o,`${c}${r}
|
|
271
|
+
`,"utf8"),!0}function aL(e,t,i){let r=pt.resolve(e,i??pt.join(".worktrees",t)),n=pt.resolve(e,he(e,["rev-parse","--git-common-dir"]));if(eR(n,r))throw new Error("Native worktree path cannot be inside the Git common directory");if(Zt(e).some(a=>$v(a,r)))throw new Error(`Native worktree path is already registered: ${r}`);return r}async function oL(e){try{throw await $c.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function ZP(e){try{return await $c.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function tR(e){let t=pt.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 r=me(t);if(r.isGitWorktree&&r.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:r.currentBranch,targetBranch:r.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:r.currentBranch,targetBranch:r.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let i=await re(t,e.sourceConfig?.native.artifact_root??"docs");return Dn([{runtimeDir:i.runtimeDir,locksDir:i.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let r=me(t);if(!r.isGitWorktree||r.currentBranch===null||r.primaryWorktreeRoot===null||r.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;tm(t,n);let a=r.currentBranch===n,o=e.targetBranch??(a?void 0:r.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(tm(t,o),!Io(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(!Gs(t))throw new Error("Native branch isolation requires a clean current working directory");if(Io(t,n))throw new Error(`Native change branch already exists: ${n}`);he(t,["switch","-c",n,o]),h=!0}let m;try{m=await Wd(t,e.sourceConfig)}catch(p){throw new wn(`Native branch preparation is incomplete: ${p.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:h,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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:m}}}if(a){if(!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let h=e.worktreePath?pt.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!$v(h,r.currentWorktreeRoot))throw new Error(`Native worktree path ${h} does not match the current worktree ${r.currentWorktreeRoot}`);let m;try{m=await Wd(t,e.sourceConfig)}catch(p){throw new wn(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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=Jc(r.primaryWorktreeRoot),c=s.find(h=>h.branch===n);if(c&&await ZP(c.root)){let h=e.worktreePath?pt.resolve(r.primaryWorktreeRoot,e.worktreePath):void 0;if(h&&!$v(h,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await Wd(c.root,e.sourceConfig)}catch(p){throw new wn(`Native worktree preparation is incomplete: ${p.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:p})}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 ZP(c.root)&&(he(r.primaryWorktreeRoot,["worktree","prune"]),s=Jc(r.primaryWorktreeRoot));let l=Io(t,n);if(s.some(h=>h.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=aL(r.primaryWorktreeRoot,e.name,e.worktreePath);await oL(u);let d=await nL(r.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{he(r.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Wd(u,e.sourceConfig)}catch(h){throw new wn(`Native worktree preparation is incomplete: ${h.message}`,f,{cause:h})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var iR=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],Hv=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",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 remove Record a complete capability removal intent.","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:iR,output:"Human-readable text by default; use --json for a structured command envelope.",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] [--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.","--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, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","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 remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],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."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},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.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children 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> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
|
|
272
|
+
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, 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 Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," 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."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. 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','comet native next session-timeout --summary "Implementation changed" --return-to-build','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]
|
|
273
|
+
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 Inspect readiness without rerunning verification.","--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 plus continuation, or the completed Archive transaction and workspace finish result; 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 Ov(e,t){return`${e}:
|
|
274
274
|
${t.map(i=>` ${i}`).join(`
|
|
275
|
-
`)}`}function
|
|
276
|
-
${i.output}`),i.examples&&r.push("",
|
|
275
|
+
`)}`}function sL(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Hv[i]||t.length>1&&Hv[t[0]]?.subcommands?i:t[0]}function Dv(e=[]){let t=sL(e),i=Hv[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Ov("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...iR];return n&&n.length>0&&r.push("",Ov("Options",n)),r.push("",`Output:
|
|
276
|
+
${i.output}`),i.examples&&r.push("",Ov("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
277
277
|
`)}
|
|
278
|
-
`}}var
|
|
279
|
-
`}}function
|
|
280
|
-
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function
|
|
281
|
-
`);if(r){if(!p)return
|
|
282
|
-
`);if(c)p=await
|
|
283
|
-
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new O("archive requires --confirmed when native.archive_confirmation is required");if(p&&p.workspace.isolation!=="current"&&p.workspace.finish===null)throw new O("Native branch and worktree isolation require a persisted --finish preview");let v=p?await
|
|
284
|
-
`)}if(s)throw new O("--serial-first is only valid for portable Native changes");if(!r&&c)throw new O("--finish is only valid with --dry-run");if(
|
|
285
|
-
`)}import{promises as kR}from"node:fs";import zd from"node:path";import{promises as qd}from"fs";import Ke from"path";import{promises as DB}from"fs";async function MP(e,t){let i=[],r=D(e,t.name),n=Dr(r,qt.stateRef),a;try{a=await ze(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Dr(r,a.trajectoryRef),s=await La(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await wt(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Dr(r,a.checkpointRef);try{let u=await Ba(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var SB=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function EB(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function PB(e){return e?e.map(EB).join(" "):null}function RB(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function ui(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function xB(e){return e.map(t=>ui(t,[],null))}function CB(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[ui("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(ui("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(ui("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),ui("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(ui("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(ui("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),ui("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ht(e,t){let i=t.commandArgs===void 0?RB(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?PB(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??xB(t.requiredInputs??[])}}function _d(e){let i=(e.findings??[]).filter(d=>!qa(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||SB.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ht(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ht(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[ui("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ht(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ht(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ht(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ht(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[ui("summary",["--summary"],"<summary>")]});if(n)return ht(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ht(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[ui("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ht(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ht(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ht(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ht(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ht(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[ui("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ht(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ht(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=CB(e.state);return ht(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Rc from"path";var BP=8,AB={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function _B(e){let t=AB[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:qa(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function TB(e,t,i){if(!i.path)return null;let r;if(Rc.isAbsolute(i.path)?r=Rc.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Rc.resolve(ee(e,t.name),...i.path.split(/[\\/]/u)):r=Rc.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=Rc.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function IB(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Sv(e){return e.findings.map(t=>{let i=_B(t.code);return{code:t.code,message:t.message,severity:i.severity,path:TB(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:IB(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Ev(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,BP),truncated:t.length>BP}}var LP=240,qP=8,Td=50;function VP(e){let t=Array.from(e);return t.length<=LP?e:`${t.slice(0,LP-1).join("")}…`}function jB(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function $B(e){let t=[...new Set(e.map(jB))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,qP),reasonCount:e.length,codesTruncated:t.length>qP};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Td),reasonsTruncated:e.length>Td}}}async function WP(e){let t=null;try{let s=await dn(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:un(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:un(e.paths,e.state.name)}}let i=await QE({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=$B(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ln.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:VP(i.checkpoint.summary),nextAction:VP(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ln.maxArtifacts}}async function OB(e,t){let i=D(e,t.name),r=await ze(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Ba(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await wt(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function HB(e,t){let i=await OB(e,t);return{committed:i,latest:CE(i),history:xE(i)}}async function zP(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await HB(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var FB=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Kt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Pv(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function MB(e){return(await Qs(e))?.change??null}function BB(e,t,i=!1,r){return _d({state:e,archiveReady:t,evidenceRetreat:i}).command}async function LB(e,t){let i=ee(e,t.name),r=[...(await gm(i,t.brief)).findings,...(await wS(e,t)).findings,...await MP(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ma(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Pu(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await uo({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await wr(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await wm(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function mn(e,t,i){let r=await MB(e)===t,n=await ps(e,t),a=await $u(e,t),o;try{let g=await oi(e,t);if(g.status==="migration-required"&&g.state)return{name:t,phase:g.state.phase,revision:"revision"in g.state?g.state.revision:null,approval:g.state.approval,verificationResult:g.state.verification_result,specChanges:g.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,migrationRequired:!0,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message};if(g.status!=="current"||!g.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message??`Native change ${t} is incompatible`};o=g.state}catch(g){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:g.message}}if(n.status!=="available"){let g={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Sv({paths:e,state:o,findings:[g]}),z=_d({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:z.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Ev(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:z,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await WP({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await zP(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let g=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:g,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let g=await uo({changeDir:ee(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let rt=await co(e,o.name,o.verification_evidence);for(let Se of rt.acceptanceTrace.entries)P.set(Se.acceptanceId,Se.status==="failed"?"failed":Se.status==="missing"?"missing":"satisfied")}let z=wN({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),H=z.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",z.nextCursor,"--project-root",e.projectRoot]:null;u={...z,...H?{nextPageCommand:Pv(H),nextPageArgs:H}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await dd(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await lt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let P=await Vi({paths:e,identity:g});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Kr({paths:e,identity:g});f.push(...P.findingCodes.map(z=>({code:z,message:`Native workspace advisory changed: ${z} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],m=!1;if(o.phase==="verify"){let g=await cP({paths:e,state:o});m=g.freshness!=="fresh",h.push(...g.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let p=null,v=[];if(o.phase==="archive")try{p=await kd({paths:e,name:o.name}),v.push(...p.findingCodes.map(g=>({code:g,message:`Native Archive is blocked: ${g}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let N=[...await LB(e,o),...s.findings,...d,...f,...h,...l,...v].filter((g,P,z)=>z.findIndex(H=>H.code===g.code&&H.path===g.path)===P),y=Sv({paths:e,state:o,findings:N}),S=y.filter(g=>!qa(g.code)),E=o.phase==="archive"&&p?.ready===!0&&S.length===0,k=m||o.phase==="archive"&&(p?.findingCodes??[]).some(g=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(g)),b=y.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",w=y.find(g=>g.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||R?null:BB(o,E,k,i?.clarificationMode),archiveReady:E,inspection:s.inspection,findingSummary:Ev(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:_d({state:o,findings:y,archiveReady:E,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Td,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...w?{error:w.message}:{}}}async function Rv(e){let t;try{t=await Lt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await DB.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Kt.maxChanges))throw new Error(`Native status exceeds ${Kt.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Id(e,t){let i=t.toString(36),r=M("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function qB(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=FB.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=M("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function VB(e,t){let i=await Rv(e),r=M("comet.native.status-names.v1",i),n=qB({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Kt.maxItems).map(u=>mn(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?Id(r,f):null,nextPageCommand:f<i.length?Pv(["comet","native","status","--cursor",Id(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",Id(r,f)]:null,limits:{...Kt}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Kt.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?Id(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?Pv(l):null,nextPageArgs:l,limits:{...Kt}}}async function xv(e,t){return(await VB(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as cL,randomUUID as lL}from"node:crypto";import{constants as Iv,promises as se}from"node:fs";import ke from"node:path";var Od=ko(Na(),1);import{randomUUID as WB}from"crypto";import{promises as YP}from"fs";import Av from"path";import{isDeepStrictEqual as _v}from"util";var ra=/^[a-f0-9]{64}$/u,zB=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),JB=new Set(["sourceHash","targetHash","nextJournal"]),GB=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),JP=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),UB=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function jd(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function GP(e){return JSON.stringify(e,null,2)+`
|
|
286
|
-
`}function
|
|
287
|
-
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===Oe?go(a,u.previousState)||go(a,u.nextState):a.schema===$e&&(KP(a,u.previousState)||KP(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==$e)throw new Error("Schema migration transition supersede target schema is invalid");s=XB(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");jd(i.runRetreat,UB,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Ur(l.previousRun),d=Ur(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!ra.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==$e||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Cc(e,t){let i=xc(e,t),r=j(e,i);await T(r,i);try{let n=await du({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return QB(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ZB(e,t,i){let r=await Ma(e,t),n=r?await Pu(e,r):await Ru(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Pp(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new za(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Cp(e,t,n)}async function XP(e){try{return await ri(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function eL(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function QP(e,t){let i=t.transitionSupersede,r=D(e,t.change),n=await wt(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!_v(o.event,eL(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function tL(e,t,i){if(!t.transitionSupersede)return;let r=ft(e,t.change),n=await XP(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=D(e,t.change),o=await ze(a),s=await QP(e,t),c=await Ba(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Nr(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==B(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function iL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=D(e,t.change),a=await ze(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Nr(a,r.nextRun)){if(!Nr(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Bn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Nr(await ze(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await QP(e,t);if(o.sequence===null){let l=await on({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await ea({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=ft(e,t.change),c=await XP(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await YP.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function rL(e,t,i){if(!t.runRetreat)return;let r=D(e,t.change),n=await ze(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Nr(n,t.runRetreat.nextRun)){if(!Nr(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Bn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await wt(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await on({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await ea({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function nL(e,t,i){let r=await Cc(e,t);if(!r)return null;if(await Ga(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Av.join(ee(e,t),qe),a=await ri(n);if(await tL(e,r,a===r.targetHash),await ZB(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await we(n,(0,Od.stringify)(Tv(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=ft(e,t),s=await ri(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await me(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await iL(e,r,i),await rL(e,r,i),await YP.rm(xc(e,t),{force:!0}),r.nextState}async function aL(e){let t=D(e.paths,e.state.name),i=await ze(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=B(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:Oe,toSchema:$e,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function oL(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=go(i,t.previousState),a=go(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=D(e.paths,i.name),s=await ze(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Nr(s,t.previousRun),l=Nr(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await wt(o,t.nextRun.trajectoryRef)).map((N,y)=>({event:N,index:y})).filter(({event:N})=>N.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let N={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!_v(f.event,N)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...$d(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=B(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await ri(ft(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:p,evidenceHash:v,eventData:{fromSchema:Oe,toSchema:$e,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function sL(e){let t,i,r,n;if(e.state.schema===vt){if(t=Cv(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==On)throw new Error("Native v1 change has a transition from another schema generation");let s=KB(e.pendingTransition.journal);if(UP(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(UP(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=ft(e.paths,e.name);i={sourceHash:await ri(c),targetHash:B(GP(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==sr)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await oL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=YB(s);if(go(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(go(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=ft(e.paths,e.name);i={sourceHash:await ri(u),targetHash:B(GP(l)),nextJournal:l}}}else t=$d(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await aL({paths:e.paths,state:e.state,migrationId:e.id}));let a=Av.join(ee(e.paths,e.name),qe),o=(0,Od.stringify)(Tv(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===vt?Oe:$e,sourceHash:await ri(a),targetHash:B(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function ZP(e){return F(e.paths,`migrate schema for ${e.name}`,()=>sn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await nL(e.paths,e.name,e.hooks);if(i?.schema===$e)return i;let r=await oi(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await Ga(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==vt&&n.schema!==Oe)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await tv(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await sL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??WB()}),s=xc(e.paths,e.name),c=j(e.paths,s);await T(c,s),await me(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var br=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),uL=512*1024,na=/^([a-f0-9]{64})\.json$/u,dL=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,fL=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Hd=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function $v(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Zi(e,t){return $v(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function nR(e,t){return $v(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function wo(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Et(e,t){return e<t?-1:e>t?1:0}function hL(e,t){let i=ke.relative(e.projectRoot,t);if(i.length===0||ke.isAbsolute(i)||i===".."||i.startsWith(`..${ke.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(ke.sep).join("/")}function aR(e,t){return ke.join(D(e,t),"evidence")}function Dd(e,t){return hL(e,aR(e,t))}async function Fd(e,t){let i=ke.resolve(e),r=ke.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=ke.relative(i,r).split(ke.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=ke.join(o,s));let c=await se.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await se.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...wo(c)})}return a}async function di(e){for(let t of e){let i=await se.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!$v(t,i)||await se.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function oR(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:so(e,t)}function eR(e){return e!==null&&fL.test(e)?[e]:[]}function pL(e,t,i,r){if(e==="snapshots")return{canonical:to(i,t),dependencies:[]};if(e==="scopes"){let a=io(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=od(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[so("scopes",a.scopeHash)]}}if(e==="verifications"){let a=hc(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(eR));return{canonical:a,dependencies:[a.implementationScopeRef,gE(a.reportHash),...eR(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||cL("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=cd(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=sd(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function vn(e){let t=await se.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?uL:an;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await se.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Iv.O_RDONLY|Iv.O_NOFOLLOW|Iv.O_NONBLOCK,a=await se.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),se.lstat(e.file),se.realpath(e.file)]);if(await di(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Zi(wo(t),o)||!Zi(wo(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,S=await a.read(u,0,Math.min(u.length,y),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,S.bytesRead)))}let[f,h,m]=await Promise.all([a.stat(),se.lstat(e.file),se.realpath(e.file)]);if(await di(e.directoryChain),!h.isFile()||h.isSymbolicLink()||m!==r||!Zi(wo(o),f)||!Zi(wo(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(p)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let N=pL(e.kind,e.hash,v,e.name);if(p!==JSON.stringify(N.canonical,null,2)+`
|
|
288
|
-
`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:wo(f),directoryChain:e.directoryChain,dependencies:[...new Set(N.dependencies)].sort(Et)}}finally{await a.close()}}async function tR(e){try{return await se.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function mL(e){let t=D(e.paths,e.name),i=t,r=aR(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Fd(t,r);n=await se.readdir(r,{withFileTypes:!0}),await di(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Hd){if(!n.some(f=>f.name===s))continue;let c=ke.join(r,s),l=await Fd(t,c),u=(await se.readdir(c,{withFileTypes:!0})).sort((f,h)=>Et(f.name,h.name)),d=new Map;for(let f of u){let h=dL.exec(f.name);if(!h)continue;let m=d.get(h[1])??[];m.push(f),d.set(h[1],m)}for(let[f,h]of[...d.entries()].sort(([m],[p])=>Et(m,p))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let m=h[0];if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${m.name}`);let p=ke.join(c,f),v=na.exec(f)?.[1];if(!v)throw new Error(`Native evidence cleanup quarantine name is invalid: ${m.name}`);let N=oR(s,v),y=ke.join(c,m.name),S=await vn({changeRoot:i,file:y,ref:N,kind:s,hash:v,name:e.name,directoryChain:l}),E=await tR(p),k=E?null:await vn({changeRoot:i,file:p,ref:N,kind:s,hash:v,name:e.name,directoryChain:l});a.push({ref:N,original:p,quarantine:y,document:S,action:E?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Et);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:yo(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Md(o)}`),path:Dd(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Et(c.ref,l.ref))){if(await di(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await vn({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:na.exec(ke.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await vn({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:na.exec(ke.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Zi(s.originalDocument.identity,d.identity)||!Zi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await se.rm(s.quarantine),await di(s.document.directoryChain);continue}if(!await tR(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await se.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Zi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await se.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await vn({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:na.exec(ke.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await vn({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:na.exec(ke.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!nR(s.document.identity,l.identity)||!Zi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await se.rm(s.quarantine),await di(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:yo(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Md(o)}`),path:Dd(e.paths,e.name)}]}}async function vL(e,t){let i=D(e,t),r=i,n=ke.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Fd(i,n);a=await se.readdir(n,{withFileTypes:!0}),await di(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Hd.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Et);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Md(o)}`);let s=[],c=0;for(let l of Hd){if(!a.some(h=>h.name===l))continue;let u=ke.join(n,l),d=await Fd(r,u),f=(await se.readdir(u,{withFileTypes:!0})).sort((h,m)=>Et(h.name,m.name));await di(d);for(let h of f){if(s.length>=br.maxDocuments)throw new Error(`Native evidence store exceeds ${br.maxDocuments} documents`);let m=na.exec(h.name);if(!m||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let p=oR(l,m[1]),v=ke.join(u,h.name);await T(j(e,v),v);let N=await vn({changeRoot:r,file:v,ref:p,kind:l,hash:m[1],name:t,directoryChain:d});if(c+=N.size,c>br.maxScannedBytes)throw new Error(`Native evidence store exceeds ${br.maxScannedBytes} scanned bytes`);s.push(N)}await di(d)}return s}function iR(e,t){let i=new Set,r=[...e].sort(Et).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Et).reverse())i.has(o)||r.push(o)}return i}function gL(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Et),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Et))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function wL(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=iR(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<br.minimumAgeMs&&a.add(c.ref);for(let c of Hd){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Et(u.ref,d.ref)).slice(0,br.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=iR(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=br.minimumAgeMs).sort((c,l)=>Et(c.ref,l.ref));return{candidates:gL(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Md(e){let t=e.slice(0,br.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function yo(e){let t=br.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function jv(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Et);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:yo(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Md(n)}`),path:r}}async function rR(e,t){try{await se.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await se.rename(e,t)}catch{}}async function yL(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await di(e.directoryChain);let i=await vn({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:na.exec(ke.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await se.lstat(e.file),n=await se.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Zi(e.identity,r)||!Zi(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=ke.join(ke.dirname(e.file),`.${ke.basename(e.file)}.${lL()}.gc`);await se.rename(e.file,a);try{let[o,s]=await Promise.all([se.lstat(a),se.realpath(a)]);if(await di(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!nR(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await rR(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await se.rm(a),await di(e.directoryChain)}catch(o){throw await rR(a,e.file),o}}async function NL(e){if((await Y(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await se.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await It(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function bL(e,t){if(t)return[t];let i;try{i=await se.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Et)}async function kL(e,t){let i=await oi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([wr(e,t),Cc(e,t),dn(e,t)]);return r!==null||n!==null||a!==null}async function SL(e){if(await kL(e.paths,e.name))return[];let t=await oi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await mL({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await vL(e.paths,e.name),a=wL(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Dd(e.paths,e.name);if(!e.repair)return[...i.findings,jv(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await yL(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[jv(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:yo(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,jv(e.name,a,!0,o)]}async function sR(e){if(e.deferAll||await NL(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await bL(e.paths,e.name))try{a.push(...await SL({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:yo(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Dd(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await F(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:yo(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as EL,randomUUID as PL}from"crypto";import{promises as gn}from"fs";import le from"path";var Hv=64*1024*1024,RL=256*1024,dR=16*1024*1024;async function Ue(e){try{return await gn.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xL(e){let t;try{t=await gn.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let r;try{r=await It(e,i.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:n}):n}if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${r.id} is unfinished; recover it before moving`)}}async function CL(e,t){for(let i of await gn.readdir(e.locksDir,{withFileTypes:!0})){let r=le.join(e.locksDir,i.name);if(le.resolve(r)!==le.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${r}`)}}async function AL(e){let t;try{t=await gn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await lt(e,i.name);if(r){await Ou({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function _L(e){let t;try{t=await gn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name)))if(!(!i.isDirectory()||i.isSymbolicLink()))try{let r=await lt(e,i.name);if(r?.schema==="comet.native.workspace.v3"){let n=await Vi({paths:e,identity:r});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(r){let n=await Kr({paths:e,identity:r});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(r){throw new Error(`Native workspace identity for ${i.name} must be aligned and repaired before moving the root`,{cause:r})}}async function _c(e,t){let i=[];async function r(n){let a=await Tt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=le.join(n,s.name);if(t.excludedFiles?.has(le.resolve(c))){await a.verify();continue}let l=await gn.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:le.relative(e,c).split(le.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ve({root:e,file:c,maxBytes:Hv,label:`Native root file ${le.relative(e,c)}`});i.push({ref:le.relative(e,c).split(le.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function TL(e,t,i,r){await Bi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await Tt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=le.join(a,l.name);if(le.resolve(u)===le.resolve(i)){await s.verify();continue}let d=await gn.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=le.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Bi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await qr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Hv,label:`Native root move file ${le.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function No(e,t,i,r){let n=await _c(e,{rejectSymlinks:!0,excludedFiles:i?new Set([le.resolve(i)]):void 0}),a=await _c(t,{rejectSymlinks:!0,excludedFiles:r?new Set([le.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function fR(e,t){return le.join(e.artifactRoot,`.comet-native-move-${t}`)}function IL(e,t){return le.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function jL(e){return`${e}.removing`}function cR(e,t){return le.join(le.dirname(e),`.${le.basename(e)}.${t}.rollback-removing`)}function hR(e,t,i){return le.join(gu(e,t).directory,`root-move-cleanup-${i}.json`)}function $L(e){return JSON.stringify(e,null,2)+`
|
|
289
|
-
`}function OL(e){return EL("sha256").update(e).digest("hex")}function HL(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||le.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function DL(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(HL);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=le.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function FL(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=$L(t);if(Buffer.byteLength(i,"utf8")>dR)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await we(hR(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),OL(i)}async function ML(e){let t=await ve({root:e.paths.runtimeDir,file:hR(e.paths,e.id,e.cleanup.kind),maxBytes:dR,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return DL(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Ov(e){let t=await _c(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function lR(e){return e.ref.split("/").length}async function BL(e){let i=[...await Ov({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>lR(a)-lR(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=le.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await fu({root:e.projectRoot,file:a,maxBytes:Hv,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await cp({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Ov({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await cp({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function Bd(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function pR(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function LL(e,t,i,r){for(let a of[e,t])try{let o=await It(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=le.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ve({root:i,file:n,maxBytes:RL,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function uR(e){let t=Bd(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Bt(e.projectRoot,t),t}async function Ac(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=Bd(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Bt(e.projectRoot,i),i}async function Ld(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await Ue(e.target),a=await Ue(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await FL({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await _c(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Ac({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await ML({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await Ue(e.target),a=await Ue(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await DN({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Ac({projectRoot:e.projectRoot,config:t,id:e.id})}return await Ov({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Ac({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Ac({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await BL({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Ac({projectRoot:e.projectRoot,config:t,id:e.id})}async function mR(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Ue(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=jL(e.staging);t=await Ld({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await _c(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([le.resolve(e.lockFile)])}),await TL(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await No(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await uR({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Ue(e.destinationPaths.nativeRoot)){if(await Ue(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await No(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Ue(e.staging))throw new Error("Native move staging tree is missing");await No(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await gn.rename(e.staging,e.destinationPaths.nativeRoot)}t=await uR({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Ue(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=IL(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Ue(e.sourcePaths.nativeRoot)&&await No(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Ld({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await AL(e.destinationPaths);let n=await It(e.destinationPaths,e.pending.id);await ja(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Bt(e.projectRoot,o),o}async function vR(e){let t=await Y(e.projectRoot)??Tn("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=Hr(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let r=await ce(e.projectRoot,t.native.artifact_root),n=await ce(e.projectRoot,i);if($(r.nativeRoot,n.nativeRoot)||$(n.nativeRoot,r.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Ue(r.nativeRoot))throw new Error(`Native source root does not exist: ${r.nativeRoot}`);if(await xL(r),await Ue(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await nr(r,"root-move",`move root to ${i}`),o=PL(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=pR({id:o,paths:r,now:e.now??new Date}),l=fR(n,o);try{if(await CL(r,a.file),await _L(r),await Ue(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Bt(e.projectRoot,Bd(t,s)),await mp(r,c),await e.hooks?.afterRootMoveStage?.("copying",c),await mR({projectRoot:e.projectRoot,config:Bd(t,s),pending:s,sourcePaths:r,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:r.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await ar(a)}}async function gR(e){let t=await Y(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await ce(e.projectRoot,i.fromArtifactRoot),n=await ce(e.projectRoot,i.toArtifactRoot),a=fR(n,i.id),o=await Ue(r.nativeRoot)?r:n,s=await nr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await LL(r,n,a,i.id)}catch(m){if(i.stage!=="copying"||!await Ue(r.nativeRoot))throw m;let p=pR({id:i.id,paths:r,now:new Date});await mp(r,p),c={journal:p,paths:r}}if(e.strategy==="continue"){let m=await mR({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:m}}if(!await Ue(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=cR(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Ue(n.nativeRoot)&&await No(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Ld({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=cR(a,i.id);!t.native.pending_root_move?.cleanup&&await Ue(a)&&await No(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Ld({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await It(r,i.id);await wu(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await Bt(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await ar(s)}}var bo=4096,qL=4096,VL=1024;async function wn(e,t,i){try{let r=await Tt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Vd(e,t){let i=new Map(e.map(r=>[Ke.resolve(r.file),{...r,file:Ke.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await vs(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Xh(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function WL(e,t){let i=Zs(e),r;try{await T(e.projectRoot,i);let n=await Qs(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await Ne(e,r.change)?[]:(await Ie(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await qd.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function zL(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function JL(e,t){let i=[],r=[];for(let n of await wn(e,e.transactionsDir,qL)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await It(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ke.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await ms([e],`doctor archive recovery ${a.id}`,async()=>await Vd([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,"archive.lock")}],i)?(await xP({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function GL(e,t,i){let r=[];for(let n of await wn(e,e.locksDir,VL)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ke.join(e.locksDir,n.name);try{let o=await vs(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await Xh(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function UL(e,t,i=5){let r=[],n=t?await xv(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await xv(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Ke.join(e.changesDir,a.name,qe)});continue}let o=await mn(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Ke.join(e.projectRoot,s.path)}:{}})}return r}async function KL(e,t){let i=[],r=t.name?[t.name]:(await wn(e,e.changesDir,bo)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await La(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await $b(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Ke.join(D(e,n),"trajectory.jsonl")})}return i}async function YL(e,t){let i=[],r=t.name?[t.name]:(await wn(e,e.changesDir,bo)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await ps(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=_n(e,n),s=We(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await ms([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Lt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await qd.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Lt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await qd.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await qd.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function XL(e,t){let i=[],r=t.name?[t.name]:(await wn(e,e.changesDir,bo)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Op(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:Va(e,n),repair:"migrate"});continue}let a=await Ie(e,n);await Wb({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:Va(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Va(e,n)})}return i}async function QL(e,t){let i=[],r=t.name?[t.name]:(await wn(e,e.changesDir,bo)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=xc(e,n);try{let o=await Cc(e,n),s=await oi(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Ke.join(e.changesDir,n,qe)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:Ke.join(e.changesDir,n,qe),repair:"migrate"});continue}await ZP({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Ke.join(e.changesDir,n,qe)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function ZL(e,t){let i=[],r=t.name?[t.name]:(await wn(e,e.changesDir,bo)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await wr(e,n)}catch(o){if(o instanceof yc)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:ft(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await ms([e],`doctor transition recovery ${n}`,async()=>await Vd([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,`transition-${n}.lock`)}],i)?(await qE(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:ft(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:ft(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:ft(e,n),repair:"continue"})}}return i}async function e1(e,t){let i=[],r=t.name?[t.name]:(await wn(e,e.changesDir,bo)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=un(e,n),o;try{o=await dn(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await ms([e],`doctor checkpoint recovery ${n}`,async()=>await Vd([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,`transition-${n}.lock`)}],i)?(await eP(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Tc(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Y(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([ce(r.projectRoot,c.fromArtifactRoot),ce(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Vd([{paths:l,file:Ke.join(l.locksDir,"root-move.lock")},{paths:u,file:Ke.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await gR({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await ce(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await zL(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await JL(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await YL(r,{name:e.name,repair:t})),i.push(...await QL(r,{name:e.name,repair:t})),i.push(...await XL(r,{name:e.name,repair:t})),i.push(...await KL(r,{name:e.name,repair:t})),i.push(...await ZL(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await e1(r,{name:e.name,repair:t})),i.push(...await sR({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await GL(r,t,s.unfinished)),i.push(...await WL(r,t)),e.projectOnly||i.push(...await UL(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{promises as wR}from"node:fs";function t1(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function i1(e,t){let i=pe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function Ai(e){let t=await Wk(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=i1(e.paths,t.state),n=re(t.state),a=r.bindingState==="mismatch"?{...n,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...n.runnerAction,kind:"none"}}:n;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:t1(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},continuation:a,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function yR(e){let t;try{t=await wR.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await wR.readFile(`${je(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}async function r1(e){let t;try{t=await kR.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function n1(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function NR(e,t){let i;try{i=await kR.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n1(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:zd.join(e.archiveDir,n.name)}:null}function a1(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function Wd(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function bR(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:zd.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function o1(e,t){let i=[],r=[];for(let n of await jN(e)){let a=Dn(n);if(t&&a.change!==t)continue;let o=zd.join(e.transactionsDir,n);try{let s=await ks(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function Dv(e,t){let i=Dt(e,"--repair"),r=Ce(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new O("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();be(e);let a=await HP(t),o=await o1(a,n);if(n&&o.findings.length>0){if(r)throw new O("--strategy is only available to the legacy transaction doctor");let d=await Ne(a,n)?await Ai({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let m=await ic({paths:a,name:n});return U("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:m.transactionId},state:m.state,continuation:re(m.state)})}let h=await Ei({paths:a,name:n});return U("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:re(h)})}return Wd({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await Ne(a,n)){if(r)throw new O("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([NR(a,n),um(a,n)]);if(u){let h=await Ai({paths:a,name:n,details:!0});return Wd({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await Ai({paths:a,name:n,details:!0});return Wd({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[bR(a,n)],continuation:h.continuation})}if(i){if(d){let m=await Ei({paths:a,name:n});return U("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:m.schema,stateVersion:m.state_version},state:m,continuation:re(m)})}let h=await Un({paths:a,name:n});return U("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:re(h.state)})}let f=await Ai({paths:a,name:n,details:!0});return U("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await Ei({paths:a,name:n});return U("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:re(u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await yR(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new O("--strategy is only available to the legacy transaction doctor");if(i){let k=await Tc({paths:a,repair:!0,projectOnly:!0}),b=[];for(let g of c.transactions)g.kind==="archive"?await ic({paths:a,name:g.change}):await Ei({paths:a,name:g.change}),b.push({kind:g.kind,change:g.change,transactionId:g.journal.id});let R=await Dv([],t),w=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...w,repaired:!0,repairedPortableTransactions:b,repairFindings:k.findings}}}let u=await r1(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[m,p,v,N,y]=await Promise.all([Promise.all(s.map(k=>Ai({paths:a,name:k}))),Promise.all(s.map(k=>NR(a,k))),Promise.all(s.map(k=>um(a,k))),Promise.all(h.map(k=>Tc({paths:a,name:k}))),Tc({paths:a,projectOnly:!0})]),S=a1([...p.filter(k=>k!==null),...s.flatMap((k,b)=>v[b]&&!f.has(k)?[bR(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:zd.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...N.flatMap(({findings:k})=>k),...y.findings]),E={healthy:S.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:m,legacyChanges:h,findings:S};return E.healthy?U("doctor",E):Wd(E)}let l=await Tc({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?U("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}import{promises as w1}from"fs";import kr from"path";var s1=null;function c1(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function SR(e,t){return(...i)=>{let r=s1;if(r===null)return t(...i);let n=c1(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}import{readFileSync as l1}from"fs";import ER from"path";var u1=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),d1=new Set(["glob","grep","listfiles","read","readfile","search","view"]),RR=["file_path","filePath","path","target_file","targetFile"],xR=["file_paths","filePaths","paths","files","targets"],CR=["operations","edits"],f1=["patch","diff","patchText","patch_text","changes"];function Mv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function PR(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function h1(e){for(let t of["tool_name","toolName","tool","name"]){let i=e[t];if(typeof i=="string"&&i.trim())return i.trim()}return null}function p1(e){for(let t of["cwd","working_directory","workspaceRoot"]){let i=e[t];if(!(typeof i!="string"||!i.trim()||!ER.isAbsolute(i.trim())))return ER.resolve(i.trim())}}function m1(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function v1(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return m1(e[t]);return e}function Fv(e){let t=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let r of i)for(let n of e.matchAll(r)){let a=n[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function aa(e,t){if(typeof t=="string"){let i=t.trim();i&&e.push(i);return}if(Array.isArray(t)){for(let i of t)aa(e,i);return}if(Mv(t)){for(let i of RR)aa(e,t[i]);for(let i of xR)aa(e,t[i]);for(let i of CR)aa(e,t[i])}}function g1(e,t){let i=[],r=[t,e].filter(Mv);for(let n of r){for(let a of RR)aa(i,n[a]);for(let a of xR)aa(i,n[a]);for(let a of CR)aa(i,n[a]);for(let a of f1){let o=n[a];typeof o=="string"&&i.push(...Fv(o))}}return typeof t=="string"&&i.push(...Fv(t)),[...new Set(i)]}function Ic(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(e)}catch{let o=Fv(e);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!Mv(i))return{intent:"unknown",targets:[],toolName:null};let r=h1(i),n=g1(i,v1(i)),a=p1(i);return r&&u1.has(PR(r))?{intent:n.length>0?"write":"unknown",targets:n,toolName:r,...a?{cwd:a}:{}}:r&&d1.has(PR(r))?{intent:"non-write",targets:[],toolName:r,...a?{cwd:a}:{}}:r?{intent:"unknown",targets:n,toolName:r,...a?{cwd:a}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{}}}function AR(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return Ic("",e);try{return Ic(l1(0,"utf8"),e)}catch{return Ic("",e)}}async function y1(e){let{projectRoot:t,paths:i,state:r,request:n}=e,a=je(i,r.name),o=[],s=[],c=!1,l=!1;for(let u of n.targets){let d=kr.resolve(t,u);if(!oa(t,d)){l=!0;continue}let f=kr.relative(t,d).replaceAll("\\","/");if(f===".comet/config.yaml"){c=!0;continue}if(!oa(i.nativeRoot,d)){s.push(f);continue}if(!oa(a,d))return{allowed:!1,reason:"Portable Native control state is Runtime-owned",workflow:"native",phase:r.phase,change:r.name};let h=kr.relative(a,d).replaceAll("\\","/");if(h==="brief.md"||h.startsWith("specs/")){o.push(h);continue}return{allowed:!1,reason:`${h||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:r.phase,change:r.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:r.phase,change:r.name}:o.length>0?r.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await Vk({paths:i,name:r.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:r.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:r.phase,change:r.name}:s.length>0?r.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name}:r.phase==="verify"||r.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await Ya({paths:i,name:r.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:r.name}:{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in Build`,workflow:"native",phase:r.phase,change:r.name}:{allowed:!0,reason:c?"Native control artifact write":l?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}function oa(e,t){let i=kr.relative(e,t);return i===""||!i.startsWith("..")&&!kr.isAbsolute(i)}function N1(e,t,i){return i.targets.length>0&&i.targets.every(r=>{let n=kr.resolve(e,r);return oa(e,n)?kr.relative(e,n).replaceAll("\\","/")===".comet/config.yaml"||oa(t,n):!0})}async function b1(e){let t=await Y(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let i=await ce(e,t.native.artifact_root),r;try{r=await w1.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let n=[];for(let a of r.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await Ne(i,a.name)){let o=await K(i,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await Ie(i,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:i,changes:n}}var k1=SR("nativeActiveContext",e=>b1(e));async function _R(){let{intent:e,targets:t}=await AR();return{intent:e,targets:t}}async function TR(e,t,i){let r=await k1(e);if(!r)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.changes.length===0)return{allowed:!0,reason:N1(e,r.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"};let n;if(i){if(n=r.changes.find(c=>c.state.name===i),!n)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(r.changes.length===1)n=r.changes[0];else{let c=await Xk(r.paths);if(n=r.changes.find(l=>l.state.name===c),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return y1({projectRoot:e,paths:r.paths,state:n.state,request:t});let o=!1,s=!1;for(let c of t.targets){let l=kr.resolve(e,c);if(!oa(e,l)){s=!0;continue}if(kr.relative(e,l).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(oa(r.paths.nativeRoot,l)){o=!0;continue}return{allowed:!1,reason:`Native change ${a.name} is in ${a.phase}; implementation writes are only allowed in build. If this belongs to the current change, confirm the scope and run comet native next ${a.name} --summary "<reason>" --return-to-build; otherwise create or select a separate Native change`,workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}async function IR(e,t){let i=Ce(e,"--hook-output");if(i!==void 0&&i!=="copilot")throw new O("--hook-output must be copilot");be(e);let r=await TR(t,await _R());return i==="copilot"?{command:"hook-guard",exitCode:0,data:r,text:r.allowed?`{}
|
|
278
|
+
`}}var cL=Dv().usage;var nR=10*1024*1024,O=class extends Error{};function Bt(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new O(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Ae(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new O(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new O(`${t} requires a value`);return e.splice(r,2),n}function Se(e){if(e.length>0)throw new O(`Unexpected argument: ${e[0]}`)}function rt(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new O(`${t} is required`);return i}function zd(e,t="en"){let i=Ae(e,"--language")??t;if(i!=="en"&&i!=="zh-CN")throw new O("--language must be en or zh-CN");return i}function rR(e,t){let i=Fv.normalize(e),r=Fv.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function lL(e){let t=Fv.resolve(e),i=me(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=me(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!rR(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||rR(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function aR(e){return e?lL(e):au(process.cwd())}async function ir(e){let t=await NN({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function oR(e){let t=await Y(e);return re(e,t?.native.artifact_root??"docs")}function W(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
279
|
+
`}}function sR(e,t){if(t instanceof O)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Vd)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 jc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Vs)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 Qa)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 wn)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Za)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 mn)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Tc)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Mv(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
280
|
+
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function cR(e,t){let i=rt(e,"change name"),r=Bt(e,"--dry-run"),n=Ae(e,"--expect-preflight"),a=Bt(e,"--confirmed"),o=Ae(e,"--finish"),s=Ae(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new O("--serial-first must be one Native change name");let c=o;if(c!==void 0&&c!=="merge"&&c!=="push"&&c!=="pull-request"&&c!=="keep")throw new O("--finish must be merge, push, pull-request, or keep");let l=await ir(t),u=await ke(l.paths,i),d=u?await Ha(l.paths,{kind:"archive",change:i}):null,f=u?!1:await RS(l.paths,i);if(u||f){if(n)throw new O("Portable Native Archive does not use preflight hashes");if(r&&a)throw new O("--confirmed is only valid when executing Archive");if(r&&s)throw new O("--serial-first is only valid when executing Archive");if(!r&&c)throw new O("--finish is only valid with --dry-run");Se(e);let m=u&&!r&&d?.kind!=="archive"?await ta({paths:l.paths,name:i}):null,p=m?.state??(u?await K(l.paths,i):null);if(m?.action==="reverify"||m?.action==="await-user")return W(r?"archive --dry-run":"archive",{archived:!1,state:m.state,recovery:m,continuation:de(m.state)},`${m.message}
|
|
281
|
+
`);if(r){if(!p)return W("archive --dry-run",{change:i,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",i,"--confirmed"],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${i}
|
|
282
|
+
`);if(c)p=await mS({paths:l.paths,name:i,finish:c});else if(p.workspace.isolation!=="current"&&p.workspace.finish===null)throw new O("Native branch and worktree isolation require --finish with --dry-run");let E=await Am({paths:l.paths,name:i}),S=de(p),k=E.capabilityPeers.length>0?{...S,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],runnerAction:{...S.runnerAction,kind:"none"}}:S;return W("archive --dry-run",{...E,workspaceFinish:p.workspace.finish,continuation:k},`Native Archive preview: ${E.ready?"ready":"blocked"}
|
|
283
|
+
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new O("archive requires --confirmed when native.archive_confirmation is required");if(p&&p.workspace.isolation!=="current"&&p.workspace.finish===null)throw new O("Native branch and worktree isolation require a persisted --finish preview");let v=p?await Hm({paths:l.paths,state:p}):null,g;try{g=await dc({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(E){if(!(E instanceof uc)||!p)throw E;let S=await Am({paths:l.paths,name:i}),k=E.peers.length>0?["comet","native","archive",i,"--confirmed","--serial-first",i]:["comet","native","archive",i,"--confirmed"];return{command:"archive",exitCode:73,data:{...S,workspaceFinish:p.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:E.message,commandArgs:k,inputOptions:E.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:E.message}}}p=g.state,!v&&p.workspace.isolation!=="current"&&(v=await Hm({paths:l.paths,state:p,archiveDir:g.archiveDir}));let y=null;if(v)try{y=await WS({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:v})}catch(E){if(!(E instanceof hc))throw E;return{command:"archive",exitCode:73,data:{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:E.result,continuation:{disposition:"blocked",reason:E.message,commandArgs:E.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:E.message}}}return W("archive",{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:y,continuation:de(g.state)},`Archived Native change ${i} to ${g.archiveDir}
|
|
284
|
+
`)}if(s)throw new O("--serial-first is only valid for portable Native changes");if(!r&&c)throw new O("--finish is only valid with --dry-run");if(Se(e),r)return{command:"archive --dry-run",exitCode:65,data:{change:i,migrationRequired:!0,repairCommand:`comet native doctor ${i} --repair`},error:{code:"invalid-data",message:`Native active change ${i} must migrate before Archive preview`}};let h=await xi({paths:l.paths,name:i});return W("archive",{migration:{from:"legacy",to:h.schema,completed:!0},state:h,continuation:de(h)},`Migrated Native change ${i}; follow the returned portable continuation before Archive
|
|
285
|
+
`)}import{promises as JR}from"node:fs";import cf from"node:path";import{promises as af}from"fs";import Ke from"path";import{promises as EL}from"fs";async function lR(e,t){let i=[],r=M(e,t.name),n=Lr(r,zt.stateRef),a;try{a=await Je(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Lr(r,a.trajectoryRef),s=await Ka(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await kt(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Lr(r,a.checkpointRef);try{let u=await Ua(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var uL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function dL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function fL(e){return e?e.map(dL).join(" "):null}function hL(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function pi(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function pL(e){return e.map(t=>pi(t,[],null))}function mL(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[pi("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(pi("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(pi("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),pi("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(pi("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(pi("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),pi("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function mt(e,t){let i=t.commandArgs===void 0?hL(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?fL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??pL(t.requiredInputs??[])}}function Jd(e){let i=(e.findings??[]).filter(d=>!Ya(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||uL.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return mt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return mt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[pi("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return mt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return mt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return mt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[pi("summary",["--summary"],"<summary>")]});if(n)return mt(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[pi("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?mt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):mt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),mt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[pi("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):mt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return mt(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=mL(e.state);return mt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Oc from"path";var uR=8,vL={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function gL(e){let t=vL[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Ya(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function wL(e,t,i){if(!i.path)return null;let r;if(Oc.isAbsolute(i.path)?r=Oc.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Oc.resolve(te(e,t.name),...i.path.split(/[\\/]/u)):r=Oc.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=Oc.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function yL(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Bv(e){return e.findings.map(t=>{let i=gL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:wL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:yL(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Lv(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,uR),truncated:t.length>uR}}var dR=240,fR=8,Gd=50;function hR(e){let t=Array.from(e);return t.length<=dR?e:`${t.slice(0,dR-1).join("")}…`}function NL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function bL(e){let t=[...new Set(e.map(NL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,fR),reasonCount:e.length,codesTruncated:t.length>fR};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Gd),reasonsTruncated:e.length>Gd}}}async function pR(e){let t=null;try{let s=await pn(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:hn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:hn(e.paths,e.state.name)}}let i=await kP({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=bL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:fn.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:hR(i.checkpoint.summary),nextAction:hR(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:fn.maxArtifacts}}async function kL(e,t){let i=M(e,t.name),r=await Je(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Ua(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await kt(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function SL(e,t){let i=await kL(e,t);return{committed:i,latest:QE(i),history:XE(i)}}async function mR(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await SL(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var PL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Qt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function qv(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function RL(e){return(await sc(e))?.change??null}function CL(e,t,i=!1,r){return Jd({state:e,archiveReady:t,evidenceRetreat:i}).command}async function xL(e,t){let i=te(e,t.name),r=[...(await $m(i,t.brief)).findings,...(await qS(e,t)).findings,...await lR(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ga(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Fu(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await yo({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Sr(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await Om(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function yn(e,t,i){let r=await RL(e)===t,n=await Ns(e,t),a=await Ku(e,t),o;try{let w=await li(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Bv({paths:e,state:o,findings:[w]}),L=Jd({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:L.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:Lv(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:L,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await pR({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await mR(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await yo({changeDir:te(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let nt=await go(e,o.name,o.verification_evidence);for(let Pe of nt.acceptanceTrace.entries)P.set(Pe.acceptanceId,Pe.status==="failed"?"failed":Pe.status==="missing"?"missing":"satisfied")}let L=ON({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),H=L.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",L.nextCursor,"--project-root",e.projectRoot]:null;u={...L,...H?{nextPageCommand:qv(H),nextPageArgs:H}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await Cd(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await lt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await Gi({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Zr({paths:e,identity:w});f.push(...P.findingCodes.map(L=>({code:L,message:`Native workspace advisory changed: ${L} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],m=!1;if(o.phase==="verify"){let w=await IP({paths:e,state:o});m=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let p=null,v=[];if(o.phase==="archive")try{p=await Fd({paths:e,name:o.name}),v.push(...p.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await xL(e,o),...s.findings,...d,...f,...h,...l,...v].filter((w,P,L)=>L.findIndex(H=>H.code===w.code&&H.path===w.path)===P),y=Bv({paths:e,state:o,findings:g}),E=y.filter(w=>!Ya(w.code)),S=o.phase==="archive"&&p?.ready===!0&&E.length===0,k=m||o.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=y.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||R?null:CL(o,S,k,i?.clarificationMode),archiveReady:S,inspection:s.inspection,findingSummary:Lv(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Jd({state:o,findings:y,archiveReady:S,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Gd,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function Vv(e){let t;try{t=await Wt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await EL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Qt.maxChanges))throw new Error(`Native status exceeds ${Qt.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Ud(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function AL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=PL.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function _L(e,t){let i=await Vv(e),r=D("comet.native.status-names.v1",i),n=AL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Qt.maxItems).map(u=>yn(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?Ud(r,f):null,nextPageCommand:f<i.length?qv(["comet","native","status","--cursor",Ud(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",Ud(r,f)]:null,limits:{...Qt}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Qt.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?Ud(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?qv(l):null,nextPageArgs:l,limits:{...Qt}}}async function Wv(e,t){return(await _L(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as KL,randomUUID as YL}from"node:crypto";import{constants as Kv,promises as se}from"node:fs";import Ee from"node:path";var Xd=ma(_n(),1);import{randomUUID as TL}from"crypto";import{promises as NR}from"fs";import Jv from"path";import{isDeepStrictEqual as Gv}from"util";var la=/^[a-f0-9]{64}$/u,IL=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),jL=new Set(["sourceHash","targetHash","nextJournal"]),$L=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),vR=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),OL=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Kd(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function gR(e){return JSON.stringify(e,null,2)+`
|
|
286
|
+
`}function Uv(e){return e.schema===Oe?Qu(e):Gn(e)}function zv(e,t){return{...e,schema:Oe,minimum_runtime_version:2,revision:t}}function HL(e){return{...e,schema:dr,minimum_runtime_version:2,revision:1,previousState:zv(e.previousState,1),nextState:zv(e.nextState,2)}}function Yd(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:$e,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function DL(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?B(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:qr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Yd(e.previousState),nextState:{...Yd(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Qi.definition.metadata.version,skillHash:Rc}:e.nextRun}}function wR(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Po(e,t){return JSON.stringify(Qu(e))===JSON.stringify(Qu(t))}function yR(e,t){return JSON.stringify(Gn(e))===JSON.stringify(Gn(t))}function Pr(e,t){return Gv(e,t)}function FL(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Kd(n,$L,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!la.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!la.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Qr(n.previousRun),o=Qr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Pr(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==vR.size||u.some(f=>!vR.has(f))||l.fromSchema!==Oe||l.toSchema!==$e||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=B(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function Hc(e,t){return Jv.join(M(e,t),"schema-migration.json")}function ML(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Kd(e,IL,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===yt&&i.toSchema===Oe,n=i.fromSchema===Oe&&i.toSchema===$e;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!la.test(i.sourceHash)||typeof i.targetHash!="string"||!la.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?Vi(i.nextState):jt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(B((0,Xd.stringify)(Uv(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");Kd(i.transition,jL,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!la.test(l.sourceHash)||typeof l.targetHash!="string"||!la.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?gv(l.nextJournal,t):vv(l.nextJournal,t);if(B(JSON.stringify(l.nextJournal,null,2)+`
|
|
287
|
+
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===Oe?Po(a,u.previousState)||Po(a,u.nextState):a.schema===$e&&(yR(a,u.previousState)||yR(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==$e)throw new Error("Schema migration transition supersede target schema is invalid");s=FL(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Kd(i.runRetreat,OL,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Qr(l.previousRun),d=Qr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!la.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==$e||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Dc(e,t){let i=Hc(e,t),r=j(e,i);await T(r,i);try{let n=await Eu({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return ML(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function BL(e,t,i){let r=await Ga(e,t),n=r?await Fu(e,r):await Mu(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Bp(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new Za(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Vp(e,t,n)}async function bR(e){try{return await oi(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function LL(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function kR(e,t){let i=t.transitionSupersede,r=M(e,t.change),n=await kt(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Gv(o.event,LL(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function qL(e,t,i){if(!t.transitionSupersede)return;let r=ht(e,t.change),n=await bR(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=M(e,t.change),o=await Je(a),s=await kR(e,t),c=await Ua(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Pr(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==B(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function VL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=M(e,t.change),a=await Je(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Pr(a,r.nextRun)){if(!Pr(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Jn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Pr(await Je(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await kR(e,t);if(o.sequence===null){let l=await ln({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await sa({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=ht(e,t.change),c=await bR(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await NR.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function WL(e,t,i){if(!t.runRetreat)return;let r=M(e,t.change),n=await Je(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Pr(n,t.runRetreat.nextRun)){if(!Pr(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Jn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await kt(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await ln({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await sa({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function zL(e,t,i){let r=await Dc(e,t);if(!r)return null;if(await to(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Jv.join(te(e,t),Ve),a=await oi(n);if(await qL(e,r,a===r.targetHash),await BL(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await Ne(n,(0,Xd.stringify)(Uv(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=ht(e,t),s=await oi(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await ve(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await VL(e,r,i),await WL(e,r,i),await NR.rm(Hc(e,t),{force:!0}),r.nextState}async function JL(e){let t=M(e.paths,e.state.name),i=await Je(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=B(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:Oe,toSchema:$e,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function GL(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Po(i,t.previousState),a=Po(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=M(e.paths,i.name),s=await Je(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Pr(s,t.previousRun),l=Pr(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await kt(o,t.nextRun.trajectoryRef)).map((g,y)=>({event:g,index:y})).filter(({event:g})=>g.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let g={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Gv(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...Yd(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=B(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await oi(ht(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:p,evidenceHash:v,eventData:{fromSchema:Oe,toSchema:$e,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function UL(e){let t,i,r,n;if(e.state.schema===yt){if(t=zv(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Ln)throw new Error("Native v1 change has a transition from another schema generation");let s=HL(e.pendingTransition.journal);if(wR(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(wR(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=ht(e.paths,e.name);i={sourceHash:await oi(c),targetHash:B(gR(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==dr)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await GL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=DL(s);if(Po(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Po(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=ht(e.paths,e.name);i={sourceHash:await oi(u),targetHash:B(gR(l)),nextJournal:l}}}else t=Yd(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await JL({paths:e.paths,state:e.state,migrationId:e.id}));let a=Jv.join(te(e.paths,e.name),Ve),o=(0,Xd.stringify)(Uv(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===yt?Oe:$e,sourceHash:await oi(a),targetHash:B(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function SR(e){return F(e.paths,`migrate schema for ${e.name}`,()=>un(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await zL(e.paths,e.name,e.hooks);if(i?.schema===$e)return i;let r=await li(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await to(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==yt&&n.schema!==Oe)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await wv(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await UL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??TL()}),s=Hc(e.paths,e.name),c=j(e.paths,s);await T(c,s),await ve(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Rr=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),XL=512*1024,ua=/^([a-f0-9]{64})\.json$/u,QL=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,ZL=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Qd=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Xv(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function rr(e,t){return Xv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function xR(e,t){return Xv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ro(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ct(e,t){return e<t?-1:e>t?1:0}function eq(e,t){let i=Ee.relative(e.projectRoot,t);if(i.length===0||Ee.isAbsolute(i)||i===".."||i.startsWith(`..${Ee.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(Ee.sep).join("/")}function AR(e,t){return Ee.join(M(e,t),"evidence")}function Zd(e,t){return eq(e,AR(e,t))}async function ef(e,t){let i=Ee.resolve(e),r=Ee.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=Ee.relative(i,r).split(Ee.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=Ee.join(o,s));let c=await se.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await se.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ro(c)})}return a}async function mi(e){for(let t of e){let i=await se.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Xv(t,i)||await se.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function _R(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:vo(e,t)}function ER(e){return e!==null&&ZL.test(e)?[e]:[]}function tq(e,t,i,r){if(e==="snapshots")return{canonical:lo(i,t),dependencies:[]};if(e==="scopes"){let a=uo(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=kd(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[vo("scopes",a.scopeHash)]}}if(e==="verifications"){let a=bc(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(ER));return{canonical:a,dependencies:[a.implementationScopeRef,LE(a.reportHash),...ER(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||KL("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Ed(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=Sd(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Nn(e){let t=await se.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?XL:cn;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await se.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Kv.O_RDONLY|Kv.O_NOFOLLOW|Kv.O_NONBLOCK,a=await se.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),se.lstat(e.file),se.realpath(e.file)]);if(await mi(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!rr(Ro(t),o)||!rr(Ro(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,E=await a.read(u,0,Math.min(u.length,y),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,h,m]=await Promise.all([a.stat(),se.lstat(e.file),se.realpath(e.file)]);if(await mi(e.directoryChain),!h.isFile()||h.isSymbolicLink()||m!==r||!rr(Ro(o),f)||!rr(Ro(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(p)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let g=tq(e.kind,e.hash,v,e.name);if(p!==JSON.stringify(g.canonical,null,2)+`
|
|
288
|
+
`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ro(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(Ct)}}finally{await a.close()}}async function PR(e){try{return await se.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function iq(e){let t=M(e.paths,e.name),i=t,r=AR(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await ef(t,r);n=await se.readdir(r,{withFileTypes:!0}),await mi(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Qd){if(!n.some(f=>f.name===s))continue;let c=Ee.join(r,s),l=await ef(t,c),u=(await se.readdir(c,{withFileTypes:!0})).sort((f,h)=>Ct(f.name,h.name)),d=new Map;for(let f of u){let h=QL.exec(f.name);if(!h)continue;let m=d.get(h[1])??[];m.push(f),d.set(h[1],m)}for(let[f,h]of[...d.entries()].sort(([m],[p])=>Ct(m,p))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let m=h[0];if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${m.name}`);let p=Ee.join(c,f),v=ua.exec(f)?.[1];if(!v)throw new Error(`Native evidence cleanup quarantine name is invalid: ${m.name}`);let g=_R(s,v),y=Ee.join(c,m.name),E=await Nn({changeRoot:i,file:y,ref:g,kind:s,hash:v,name:e.name,directoryChain:l}),S=await PR(p),k=S?null:await Nn({changeRoot:i,file:p,ref:g,kind:s,hash:v,name:e.name,directoryChain:l});a.push({ref:g,original:p,quarantine:y,document:E,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Ct);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Co(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${tf(o)}`),path:Zd(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Ct(c.ref,l.ref))){if(await mi(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Nn({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Nn({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!rr(s.originalDocument.identity,d.identity)||!rr(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await se.rm(s.quarantine),await mi(s.document.directoryChain);continue}if(!await PR(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await se.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!rr(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await se.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Nn({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Nn({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:ua.exec(Ee.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!xR(s.document.identity,l.identity)||!rr(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await se.rm(s.quarantine),await mi(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Co(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${tf(o)}`),path:Zd(e.paths,e.name)}]}}async function rq(e,t){let i=M(e,t),r=i,n=Ee.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await ef(i,n);a=await se.readdir(n,{withFileTypes:!0}),await mi(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Qd.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Ct);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${tf(o)}`);let s=[],c=0;for(let l of Qd){if(!a.some(h=>h.name===l))continue;let u=Ee.join(n,l),d=await ef(r,u),f=(await se.readdir(u,{withFileTypes:!0})).sort((h,m)=>Ct(h.name,m.name));await mi(d);for(let h of f){if(s.length>=Rr.maxDocuments)throw new Error(`Native evidence store exceeds ${Rr.maxDocuments} documents`);let m=ua.exec(h.name);if(!m||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let p=_R(l,m[1]),v=Ee.join(u,h.name);await T(j(e,v),v);let g=await Nn({changeRoot:r,file:v,ref:p,kind:l,hash:m[1],name:t,directoryChain:d});if(c+=g.size,c>Rr.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Rr.maxScannedBytes} scanned bytes`);s.push(g)}await mi(d)}return s}function RR(e,t){let i=new Set,r=[...e].sort(Ct).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Ct).reverse())i.has(o)||r.push(o)}return i}function nq(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Ct),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Ct))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function aq(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=RR(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<Rr.minimumAgeMs&&a.add(c.ref);for(let c of Qd){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Ct(u.ref,d.ref)).slice(0,Rr.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=RR(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Rr.minimumAgeMs).sort((c,l)=>Ct(c.ref,l.ref));return{candidates:nq(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function tf(e){let t=e.slice(0,Rr.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Co(e){let t=Rr.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Yv(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Ct);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Co(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${tf(n)}`),path:r}}async function CR(e,t){try{await se.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await se.rename(e,t)}catch{}}async function oq(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await mi(e.directoryChain);let i=await Nn({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:ua.exec(Ee.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await se.lstat(e.file),n=await se.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!rr(e.identity,r)||!rr(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=Ee.join(Ee.dirname(e.file),`.${Ee.basename(e.file)}.${YL()}.gc`);await se.rename(e.file,a);try{let[o,s]=await Promise.all([se.lstat(a),se.realpath(a)]);if(await mi(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!xR(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await CR(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await se.rm(a),await mi(e.directoryChain)}catch(o){throw await CR(a,e.file),o}}async function sq(e){if((await Y(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await se.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await Ot(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function cq(e,t){if(t)return[t];let i;try{i=await se.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Ct)}async function lq(e,t){let i=await li(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Sr(e,t),Dc(e,t),pn(e,t)]);return r!==null||n!==null||a!==null}async function uq(e){if(await lq(e.paths,e.name))return[];let t=await li(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await iq({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await rq(e.paths,e.name),a=aq(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Zd(e.paths,e.name);if(!e.repair)return[...i.findings,Yv(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await oq(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Yv(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Co(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Yv(e.name,a,!0,o)]}async function TR(e){if(e.deferAll||await sq(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await cq(e.paths,e.name))try{a.push(...await uq({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Co(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Zd(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await F(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Co(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as dq,randomUUID as fq}from"crypto";import{promises as bn}from"fs";import le from"path";var Zv=64*1024*1024,hq=256*1024,OR=16*1024*1024;async function Ue(e){try{return await bn.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pq(e){let t;try{t=await bn.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let r;try{r=await Ot(e,i.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:n}):n}if(r.status!=="committed"&&r.status!=="rolled-back")throw new Error(`Native transaction ${r.id} is unfinished; recover it before moving`)}}async function mq(e,t){for(let i of await bn.readdir(e.locksDir,{withFileTypes:!0})){let r=le.join(e.locksDir,i.name);if(le.resolve(r)!==le.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${r}`)}}async function vq(e){let t;try{t=await bn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await lt(e,i.name);if(r){await Yu({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function gq(e){let t;try{t=await bn.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name)))if(!(!i.isDirectory()||i.isSymbolicLink()))try{let r=await lt(e,i.name);if(r?.schema==="comet.native.workspace.v3"){let n=await Gi({paths:e,identity:r});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(r){let n=await Zr({paths:e,identity:r});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(r){throw new Error(`Native workspace identity for ${i.name} must be aligned and repaired before moving the root`,{cause:r})}}async function Mc(e,t){let i=[];async function r(n){let a=await $t({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=le.join(n,s.name);if(t.excludedFiles?.has(le.resolve(c))){await a.verify();continue}let l=await bn.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:le.relative(e,c).split(le.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ge({root:e,file:c,maxBytes:Zv,label:`Native root file ${le.relative(e,c)}`});i.push({ref:le.relative(e,c).split(le.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function wq(e,t,i,r){await Wi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await $t({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=le.join(a,l.name);if(le.resolve(u)===le.resolve(i)){await s.verify();continue}let d=await bn.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=le.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Wi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Jr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Zv,label:`Native root move file ${le.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function xo(e,t,i,r){let n=await Mc(e,{rejectSymlinks:!0,excludedFiles:i?new Set([le.resolve(i)]):void 0}),a=await Mc(t,{rejectSymlinks:!0,excludedFiles:r?new Set([le.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function HR(e,t){return le.join(e.artifactRoot,`.comet-native-move-${t}`)}function yq(e,t){return le.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function Nq(e){return`${e}.removing`}function IR(e,t){return le.join(le.dirname(e),`.${le.basename(e)}.${t}.rollback-removing`)}function DR(e,t,i){return le.join(_u(e,t).directory,`root-move-cleanup-${i}.json`)}function bq(e){return JSON.stringify(e,null,2)+`
|
|
289
|
+
`}function kq(e){return dq("sha256").update(e).digest("hex")}function Sq(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||le.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function Eq(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(Sq);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=le.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function Pq(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=bq(t);if(Buffer.byteLength(i,"utf8")>OR)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await Ne(DR(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),kq(i)}async function Rq(e){let t=await ge({root:e.paths.runtimeDir,file:DR(e.paths,e.id,e.cleanup.kind),maxBytes:OR,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return Eq(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Qv(e){let t=await Mc(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function jR(e){return e.ref.split("/").length}async function Cq(e){let i=[...await Qv({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>jR(a)-jR(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=le.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Pu({root:e.projectRoot,file:a,maxBytes:Zv,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Sp({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Qv({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Sp({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function rf(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function FR(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function xq(e,t,i,r){for(let a of[e,t])try{let o=await Ot(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=le.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ge({root:i,file:n,maxBytes:hq,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function $R(e){let t=rf(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Vt(e.projectRoot,t),t}async function Fc(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=rf(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Vt(e.projectRoot,i),i}async function nf(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await Ue(e.target),a=await Ue(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await Pq({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Mc(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await Rq({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await Ue(e.target),a=await Ue(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await eb({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Fc({projectRoot:e.projectRoot,config:t,id:e.id})}return await Qv({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Fc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await Cq({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Fc({projectRoot:e.projectRoot,config:t,id:e.id})}async function MR(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Ue(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=Nq(e.staging);t=await nf({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Mc(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([le.resolve(e.lockFile)])}),await wq(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await xo(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await $R({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Ue(e.destinationPaths.nativeRoot)){if(await Ue(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await xo(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Ue(e.staging))throw new Error("Native move staging tree is missing");await xo(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await bn.rename(e.staging,e.destinationPaths.nativeRoot)}t=await $R({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Ue(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=yq(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Ue(e.sourcePaths.nativeRoot)&&await xo(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await nf({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await vq(e.destinationPaths);let n=await Ot(e.destinationPaths,e.pending.id);await La(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Vt(e.projectRoot,o),o}async function BR(e){let t=await Y(e.projectRoot)??Hn("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=Br(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let r=await re(e.projectRoot,t.native.artifact_root),n=await re(e.projectRoot,i);if($(r.nativeRoot,n.nativeRoot)||$(n.nativeRoot,r.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Ue(r.nativeRoot))throw new Error(`Native source root does not exist: ${r.nativeRoot}`);if(await pq(r),await Ue(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await cr(r,"root-move",`move root to ${i}`),o=fq(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=FR({id:o,paths:r,now:e.now??new Date}),l=HR(n,o);try{if(await mq(r,a.file),await gq(r),await Ue(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Vt(e.projectRoot,rf(t,s)),await _p(r,c),await e.hooks?.afterRootMoveStage?.("copying",c),await MR({projectRoot:e.projectRoot,config:rf(t,s),pending:s,sourcePaths:r,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:r.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await lr(a)}}async function LR(e){let t=await Y(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await re(e.projectRoot,i.fromArtifactRoot),n=await re(e.projectRoot,i.toArtifactRoot),a=HR(n,i.id),o=await Ue(r.nativeRoot)?r:n,s=await cr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await xq(r,n,a,i.id)}catch(m){if(i.stage!=="copying"||!await Ue(r.nativeRoot))throw m;let p=FR({id:i.id,paths:r,now:new Date});await _p(r,p),c={journal:p,paths:r}}if(e.strategy==="continue"){let m=await MR({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:m}}if(!await Ue(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=IR(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Ue(n.nativeRoot)&&await xo(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await nf({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=IR(a,i.id);!t.native.pending_root_move?.cleanup&&await Ue(a)&&await xo(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await nf({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await Ot(r,i.id);await Tu(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await Vt(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await lr(s)}}var Ao=4096,Aq=4096,_q=1024;async function kn(e,t,i){try{let r=await $t({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function of(e,t){let i=new Map(e.map(r=>[Ke.resolve(r.file),{...r,file:Ke.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await bs(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await fp(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function Tq(e,t){let i=cc(e),r;try{await T(e.projectRoot,i);let n=await sc(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await ke(e,r.change)?[]:(await je(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await af.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function Iq(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function jq(e,t){let i=[],r=[];for(let n of await kn(e,e.transactionsDir,Aq)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await Ot(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ke.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Dn([e],`doctor archive recovery ${a.id}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,"archive.lock")}],i)?(await XP({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function $q(e,t,i){let r=[];for(let n of await kn(e,e.locksDir,_q)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ke.join(e.locksDir,n.name);try{let o=await bs(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await fp(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function Oq(e,t,i=5){let r=[],n=t?await Wv(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Wv(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Ke.join(e.changesDir,a.name,Ve)});continue}let o=await yn(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Ke.join(e.projectRoot,s.path)}:{}})}return r}async function Hq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await Ka(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Zb(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Ke.join(M(e,n),"trajectory.jsonl")})}return i}async function Dq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await Ns(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=On(e,n),s=ze(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await Dn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Wt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await af.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Wt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await af.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await af.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function Fq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Yp(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:Xa(e,n),repair:"migrate"});continue}let a=await je(e,n);await lk({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:Xa(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Xa(e,n)})}return i}async function Mq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Hc(e,n);try{let o=await Dc(e,n),s=await li(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Ke.join(e.changesDir,n,Ve)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:Ke.join(e.changesDir,n,Ve),repair:"migrate"});continue}await SR({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Ke.join(e.changesDir,n,Ve)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function Bq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Sr(e,n)}catch(o){if(o instanceof Cc)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:ht(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Dn([e],`doctor transition recovery ${n}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,`transition-${n}.lock`)}],i)?(await fP(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:ht(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:ht(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:ht(e,n),repair:"continue"})}}return i}async function Lq(e,t){let i=[],r=t.name?[t.name]:(await kn(e,e.changesDir,Ao)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=hn(e,n),o;try{o=await pn(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await Dn([e],`doctor checkpoint recovery ${n}`,async()=>await of([{paths:e,file:Ke.join(e.locksDir,"root-move.lock")},{paths:e,file:Ke.join(e.locksDir,`transition-${n}.lock`)}],i)?(await EP(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Bc(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Y(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([re(r.projectRoot,c.fromArtifactRoot),re(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await of([{paths:l,file:Ke.join(l.locksDir,"root-move.lock")},{paths:u,file:Ke.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await LR({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await re(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await Iq(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await jq(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await Dq(r,{name:e.name,repair:t})),i.push(...await Mq(r,{name:e.name,repair:t})),i.push(...await Fq(r,{name:e.name,repair:t})),i.push(...await Hq(r,{name:e.name,repair:t})),i.push(...await Bq(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await Lq(r,{name:e.name,repair:t})),i.push(...await TR({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await $q(r,t,s.unfinished)),i.push(...await Tq(r,t)),e.projectOnly||i.push(...await Oq(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{promises as qR}from"node:fs";function qq(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function Vq(e,t){let i=me(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function ji(e){let t=await vS(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=Vq(e.paths,t.state),n=await Gt({paths:e.paths,state:t.state}),a=de(t.state,n),o=r.bindingState==="mismatch"?{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...a.runnerAction,kind:"none"}}:a;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:qq(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{children:n.children,readyChildren:n.readyChildren}:{},continuation:o,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function VR(e){let t;try{t=await qR.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await qR.readFile(`${we(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}async function Lc(e,t){let i=await Gt({paths:e,state:t});return de(t,i)}async function Wq(e){let t;try{t=await JR.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function zq(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function WR(e,t){let i;try{i=await JR.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${zq(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:cf.join(e.archiveDir,n.name)}:null}function Jq(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function sf(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function zR(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:cf.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function Gq(e,t){let i=[],r=[];for(let n of await YN(e)){let a=Vn(n);if(t&&a.change!==t)continue;let o=cf.join(e.transactionsDir,n);try{let s=await Cs(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function eg(e,t){let i=Bt(e,"--repair"),r=Ae(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new O("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();Se(e);let a=await oR(t),o=await Gq(a,n);if(n&&o.findings.length>0){if(r)throw new O("--strategy is only available to the legacy transaction doctor");let d=await ke(a,n)?await ji({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let m=await dc({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:m.transactionId},state:m.state,continuation:await Lc(a,m.state)})}let h=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Lc(a,h)})}return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await ke(a,n)){if(r)throw new O("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([WR(a,n),_m(a,n)]);if(u){let h=await ji({paths:a,name:n,details:!0});return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await ji({paths:a,name:n,details:!0});return sf({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[zR(a,n)],continuation:h.continuation})}if(i){if(d){let m=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:m.schema,stateVersion:m.state_version},state:m,continuation:await Lc(a,m)})}let h=await ta({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:await Lc(a,h.state)})}let f=await ji({paths:a,name:n,details:!0});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await xi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Lc(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await VR(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new O("--strategy is only available to the legacy transaction doctor");if(i){let k=await Bc({paths:a,repair:!0,projectOnly:!0}),b=[];for(let w of c.transactions)w.kind==="archive"?await dc({paths:a,name:w.change}):await xi({paths:a,name:w.change}),b.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await eg([],t),N=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...N,repaired:!0,repairedPortableTransactions:b,repairFindings:k.findings}}}let u=await Wq(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[m,p,v,g,y]=await Promise.all([Promise.all(s.map(k=>ji({paths:a,name:k}))),Promise.all(s.map(k=>WR(a,k))),Promise.all(s.map(k=>_m(a,k))),Promise.all(h.map(k=>Bc({paths:a,name:k}))),Bc({paths:a,projectOnly:!0})]),E=Jq([...p.filter(k=>k!==null),...s.flatMap((k,b)=>v[b]&&!f.has(k)?[zR(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:cf.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...g.flatMap(({findings:k})=>k),...y.findings]),S={healthy:E.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:m,legacyChanges:h,findings:E};return S.healthy?W("doctor",S):sf(S)}let l=await Bc({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?W("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}import{promises as r1}from"fs";import $i from"path";import{readFileSync as Uq}from"fs";import GR from"path";var Kq=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),Yq=new Set(["glob","grep","listfiles","read","readfile","search","view"]),KR=["file_path","filePath","path","target_file","targetFile"],YR=["file_paths","filePaths","paths","files","targets"],XR=["operations","edits"],Xq=["patch","diff","patchText","patch_text","changes"];function ig(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function UR(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Qq(e){for(let t of["tool_name","toolName","tool","name"]){let i=e[t];if(typeof i=="string"&&i.trim())return i.trim()}return null}function Zq(e){for(let t of["cwd","working_directory","workspaceRoot"]){let i=e[t];if(!(typeof i!="string"||!i.trim()||!GR.isAbsolute(i.trim())))return GR.resolve(i.trim())}}function e1(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function t1(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return e1(e[t]);return e}function tg(e){let t=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let r of i)for(let n of e.matchAll(r)){let a=n[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function da(e,t){if(typeof t=="string"){let i=t.trim();i&&e.push(i);return}if(Array.isArray(t)){for(let i of t)da(e,i);return}if(ig(t)){for(let i of KR)da(e,t[i]);for(let i of YR)da(e,t[i]);for(let i of XR)da(e,t[i])}}function i1(e,t){let i=[],r=[t,e].filter(ig);for(let n of r){for(let a of KR)da(i,n[a]);for(let a of YR)da(i,n[a]);for(let a of XR)da(i,n[a]);for(let a of Xq){let o=n[a];typeof o=="string"&&i.push(...tg(o))}}return typeof t=="string"&&i.push(...tg(t)),[...new Set(i)]}function qc(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(e)}catch{let o=tg(e);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!ig(i))return{intent:"unknown",targets:[],toolName:null};let r=Qq(i),n=i1(i,t1(i)),a=Zq(i);return r&&Kq.has(UR(r))?{intent:n.length>0?"write":"unknown",targets:n,toolName:r,...a?{cwd:a}:{}}:r&&Yq.has(UR(r))?{intent:"non-write",targets:[],toolName:r,...a?{cwd:a}:{}}:r?{intent:"unknown",targets:n,toolName:r,...a?{cwd:a}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{}}}function QR(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return qc("",e);try{return qc(Uq(0,"utf8"),e)}catch{return qc("",e)}}async function n1(e){let{projectRoot:t,paths:i,state:r,request:n}=e,a=we(i,r.name),o=[],s=[],c=!1,l=!1,u=!1;for(let d of n.targets){let f=$i.resolve(t,d);if(!fa(t,f)){u=!0;continue}let h=$i.relative(t,f).replaceAll("\\","/");if(h===".comet/config.yaml"){l=!0;continue}if(!fa(i.nativeRoot,f)){if(await Lu(t,f,[$i.join(t,".comet"),i.nativeRoot])){c=!0;continue}s.push(h);continue}if(!fa(a,f))return{allowed:!1,reason:"Portable Native control state is Runtime-owned",workflow:"native",phase:r.phase,change:r.name};let m=$i.relative(a,f).replaceAll("\\","/");if(m==="brief.md"||m==="children.yaml"||m.startsWith("specs/")){o.push(m);continue}return{allowed:!1,reason:`${m||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:r.phase,change:r.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:r.phase,change:r.name}:o.length>0?r.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await nc({paths:i,name:r.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:r.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:r.phase,change:r.name}:s.length>0?r.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:r.phase,change:r.name}:r.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name}:r.phase==="verify"||r.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await no({paths:i,name:r.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:r.name}:{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in Build`,workflow:"native",phase:r.phase,change:r.name}:c?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:r.phase,change:r.name}:{allowed:!0,reason:l?"Native control artifact write":u?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}function fa(e,t){let i=$i.relative(e,t);return i===""||!i.startsWith("..")&&!$i.isAbsolute(i)}function a1(e,t,i){return i.targets.length>0&&i.targets.every(r=>{let n=$i.resolve(e,r);return fa(e,n)?$i.relative(e,n).replaceAll("\\","/")===".comet/config.yaml"||fa(t,n):!0})}async function o1(e){let t=await Y(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let i=await re(e,t.native.artifact_root),r;try{r=await r1.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let n=[];for(let a of r.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await ke(i,a.name)){let o=await K(i,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await je(i,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:i,changes:n}}var s1=Bu("nativeActiveContext",e=>o1(e));async function ZR(){let{intent:e,targets:t}=await QR();return{intent:e,targets:t}}async function eC(e,t,i){let r=await s1(e);if(!r)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.changes.length===0)return{allowed:!0,reason:a1(e,r.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"};let n;if(i){if(n=r.changes.find(l=>l.state.name===i),!n)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(r.changes.length===1)n=r.changes[0];else{let l=await SS(r.paths);if(n=r.changes.find(u=>u.state.name===l),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return n1({projectRoot:e,paths:r.paths,state:n.state,request:t});let o=!1,s=!1,c=!1;for(let l of t.targets){let u=$i.resolve(e,l);if(!fa(e,u)){s=!0;continue}if($i.relative(e,u).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(fa(r.paths.nativeRoot,u)){o=!0;continue}if(await Lu(e,u,[$i.join(e,".comet"),r.paths.nativeRoot])){c=!0;continue}return{allowed:!1,reason:`Native change ${a.name} is in ${a.phase}; implementation writes are only allowed in build. If this belongs to the current change, confirm the scope and run comet native next ${a.name} --summary "<reason>" --return-to-build; otherwise create or select a separate Native change`,workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":c?"Native configured Hook allow path":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}async function tC(e,t){let i=Ae(e,"--hook-output");if(i!==void 0&&i!=="copilot")throw new O("--hook-output must be copilot");Se(e);let r=await eC(t,await ZR());return i==="copilot"?{command:"hook-guard",exitCode:0,data:r,text:r.allowed?`{}
|
|
290
290
|
`:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:r.reason})}
|
|
291
|
-
`}:r.allowed?{command:"hook-guard",exitCode:0,data:r}:{command:"hook-guard",exitCode:2,data:r,error:{code:"blocked",message:r.reason}}}async function
|
|
292
|
-
`)}async function
|
|
293
|
-
`)}import{randomUUID as S1}from"node:crypto";import{promises as OR}from"node:fs";import E1 from"node:path";function Lv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function sa(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function er(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 HR(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,r)=>er(i,`${t}[${r}]`))}function P1(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,i)=>{let r=Lv(t,`Native Builder check ${i}`);if(sa(r,["name","result","note"],`Native Builder check ${i}`),!["passed","failed","not-run"].includes(String(r.result)))throw new Error(`Native Builder check ${i} result is invalid`);if(r.note!==null&&typeof r.note!="string")throw new Error(`Native Builder check ${i} note is invalid`);return{name:er(r.name,`Native Builder check ${i} name`),result:r.result,note:r.note}})}function R1(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,i)=>{let r=Lv(t,`Native Runtime check ${i}`);if(sa(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${i}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${i} argv is invalid`);if(!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1)throw new Error(`Native Runtime check ${i} timeoutMs is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Runtime check ${i} repeatable is invalid`);return{id:er(r.id,`Native Runtime check ${i} id`),name:er(r.name,`Native Runtime check ${i} name`),executable:er(r.executable,`Native Runtime check ${i} executable`),argv:[...r.argv],cwdRef:er(r.cwdRef,`Native Runtime check ${i} cwdRef`),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function DR(e,t){let i=e.stateVersion,r=e.iteration,n=e.attempt;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:i,iteration:r,attempt:n,verifierExecutionRef:er(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function x1(e){let t=Lv(e,"Native Runner input");if(t.kind==="builder-handoff")return sa(t,["kind","summary","addressed_acceptance_ids","checks","known_limits"],"Native Runner Builder input"),{kind:"builder-handoff",summary:er(t.summary,"Native Builder summary"),addressed_acceptance_ids:HR(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:P1(t.checks),known_limits:HR(t.known_limits,"Native Builder known limits")};if(t.kind==="dispatch-verifier")return sa(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:R1(t.checks)};if(t.kind==="verifier-response")return sa(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return sa(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:er(t.summary,"Native Verifier execution error summary"),...DR(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return sa(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:er(t.summary,"Native unavailable Verifier summary"),...DR(t,"Native Runner unavailable Verifier input")};throw new Error("Native Runner input kind is invalid")}async function BR(e,t){let i=E1.resolve(t,e),r=await OR.lstat(i);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await OR.readFile(i,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return x1(n)}function FR(e){return`${Je}:${e}:${S1()}`}function jc(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Je)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 C1(e){return{iteration:e.iteration,summary:e.summary,addressedAcceptanceIds:[...e.addressed_acceptance_ids],checks:e.checks.map(t=>({name:t.name,result:t.result,note:t.note})),checksTruncated:e.checks_truncated,knownLimits:e.known_limits.map(t=>({...t})),knownLimitsTruncated:e.known_limits_truncated,submittedAt:e.submitted_at}}function MR(e,t,i){let r=jc(e);return{coordination:Je,change:e.name,candidateId:r.candidate_id,stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:i,briefRef:e.brief,specRefs:e.spec_changes.map(({capability:n,operation:a,source:o})=>({capability:n,operation:a,ref:o})),acceptance:e.acceptance.map(({id:n,source:a,text:o})=>({id:n,source:a,text:o})),builderHandoff:C1(r),runtimeChecks:t.map(n=>({...n}))}}async function Bv(e){jc(e.state);let t=await Si(oe(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 LR(e){if(e.input.kind==="builder-handoff"){let c=Jp().captureExecutionIdentity({identityProvider:Je,executionRef:FR("builder")}),l=await Ck({paths:e.paths,name:e.name,input:{identity:c,summary:e.input.summary,addressedAcceptanceIds:e.input.addressed_acceptance_ids,checks:e.input.checks,knownLimits:e.input.known_limits}});return{state:l,checks:[],requestChecks:null,verifierDispatch:null,continuation:re(l)}}if(e.input.kind==="dispatch-verifier"){let s=await K(e.paths,e.name);if(s.builder_handoff!==null&&s.builder_handoff.identity_provider!==Je){let d=await Ya({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:d,checks:[],requestChecks:null,verifierDispatch:null,continuation:re(d)}}jc(s);let c=await Ik({paths:e.paths,name:e.name,plans:e.input.checks}),l=FR("verifier"),u=await jk({paths:e.paths,name:e.name,checks:c.checks,verifierExecutionId:l});return{state:u,checks:c.checks,requestChecks:null,verifierDispatch:MR(u,c.checks,l),continuation:re(u)}}if(e.input.kind==="verifier-execution-error"){let s=await K(e.paths,e.name);jc(s),await Bv({paths:e.paths,state:s});let c=await Ok({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:c,checks:[],requestChecks:null,verifierDispatch:null,continuation:re(c)}}if(e.input.kind==="verifier-unavailable"){let s=await Hk({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:s,checks:s.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:re(s)}}let t=await K(e.paths,e.name),i=jc(t),r=await Bv({paths:e.paths,state:t}),n=Jp(),a=n.captureExecutionIdentity({identityProvider:Je,executionRef:r}),o=await $k({paths:e.paths,name:e.name,envelope:n.envelopeVerifierResponse({candidateId:i.candidate_id,identity:a,payload:e.input.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures});return{...o,verifierDispatch:o.requestChecks===null?null:MR(o.state,o.checks,await Bv({paths:e.paths,state:o.state})),continuation:re(o.state)}}async function qR(e,t){let i=it(e,"change name"),r=Ce(e,"--summary"),n=Ce(e,"--runner-input"),a=Dt(e,"--confirmed"),o=Dt(e,"--return-to-build"),s=Dt(e,"--retry-verifier"),c=Dt(e,"--resolve-verifier-blocker");if([a,o,s,c].filter(Boolean).length>1)throw new O("--confirmed, --return-to-build, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");be(e);let l=await Qi(t);if(!await Ne(l.paths,i)){if(n)throw new O("--runner-input is only valid for portable Native changes");if(!r)throw new O("--summary is required");let h=await Ei({paths:l.paths,name:i});return U("next",{state:h,migration:{completed:!0,summary:r},continuation:re(h)})}if(n){if(r||a||o||s||c)throw new O("--runner-input cannot be combined with --summary or Agent transition flags");let h=await Un({paths:l.paths,name:i,preserveRunningExecution:!0}),m=h.state;if(h.action==="await-user"||h.action==="done"||h.reason!=="available")return U("next",{state:m,recovery:h,continuation:re(m)});let p=await BR(n,t),v=await LR({paths:l.paths,name:i,input:p,maxVerifyFailures:l.config.native.max_verify_failures});return U("next",{...v,coordination:Je})}let u=await Un({paths:l.paths,name:i}),d=u.state;if(!r)throw new O("--summary is required");let f;if(a)if(d.phase==="shape")f=await xk({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-skill-coordinated-pass")f=await Dk({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-verifier-unavailable")f=await Fk({paths:l.paths,name:i,summary:r});else throw new O("--confirmed is only valid in Shape, for an accepted Skill-coordinated pass, or for a user-accepted degraded verification fallback");else if(o)f=await Ya({paths:l.paths,name:i,reason:r});else if(s)f=await Bk({paths:l.paths,name:i});else if(c)f=await Mk({paths:l.paths,name:i});else return u.reason!=="available"?U("next",{state:d,recovery:u,continuation:re(d)}):{command:"next",exitCode:65,data:{state:d,continuation:re(d)},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 U("next",{state:f,continuation:re(f)})}async function VR(e,t){let i=it(e,"root subcommand");if(i==="show"){be(e);let r=await Y(t);if(!r)throw new Error(".comet/config.yaml was not found");let n=await ce(t,r.native.artifact_root);return U("root show",{projectRoot:t,artifactRoot:r.native.artifact_root,language:r.native.language,nativeRoot:n.nativeRoot,pendingRootMove:r.native.pending_root_move??null})}if(i==="move"){let r=it(e,"artifact root");be(e);let n=await vR({projectRoot:t,toArtifactRoot:r});return U("root move",n,`Moved Comet Native to ${n.toNativeRoot}
|
|
294
|
-
`)}throw new O(`Unknown root command: ${i}`)}async function
|
|
295
|
-
`)}import{promises as
|
|
296
|
-
`)}import
|
|
291
|
+
`}:r.allowed?{command:"hook-guard",exitCode:0,data:r}:{command:"hook-guard",exitCode:2,data:r,error:{code:"blocked",message:r.reason}}}async function iC(e,t){let i=Ae(e,"--root"),r=await Y(t),n=zd(e,r?.native.language??"en");if(Se(e),r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let a=Br(i??r?.native.artifact_root??"docs");if(r&&i&&r.native.artifact_root!==a)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${a}`);let o=r?{...r,native:{...r.native,language:n,snapshot:{...r.native.snapshot,exclude:yN(r.native.snapshot.exclude)}}}:Hn(a,n),s=await re(t,o.native.artifact_root);return await ou(s),await Wp(t),await Vt(t,o),W("init",{projectRoot:t,artifactRoot:o.native.artifact_root,nativeRoot:s.nativeRoot,language:n},`Initialized Comet Native at ${s.nativeRoot}
|
|
292
|
+
`)}async function rC(e,t){let i=rt(e,"change name"),r=await Y(t),n=zd(e,r?.native.language??"en"),a=Ae(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new O("--isolation must be current, branch, or worktree");let o=Ae(e,"--change-branch"),s=Ae(e,"--target-branch"),c=Ae(e,"--worktree-path");Se(e);let l=r;if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let u=await tR({projectRoot:t,name:i,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:l});t=u.projectRoot,r=await Y(t);let d=r===null?Hn("docs",n):void 0;if(r||(r=d),r.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete`);let f=await re(t,r.native.artifact_root);await ou(f);let h=await Yk({paths:f,name:i,language:n,workspaceBinding:u.binding,...d?{initialProjectConfig:d}:{}});return await gd(f,h.name),W("new",{...h,preparation:u.preparation,continuation:de(h)},`Created Native change ${h.name}
|
|
293
|
+
`)}import{randomUUID as c1}from"node:crypto";import{promises as nC}from"node:fs";import l1 from"node:path";function ng(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ha(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function nr(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 aC(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,r)=>nr(i,`${t}[${r}]`))}function u1(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,i)=>{let r=ng(t,`Native Builder check ${i}`);if(ha(r,["name","result","note"],`Native Builder check ${i}`),!["passed","failed","not-run"].includes(String(r.result)))throw new Error(`Native Builder check ${i} result is invalid`);if(r.note!==null&&typeof r.note!="string")throw new Error(`Native Builder check ${i} note is invalid`);return{name:nr(r.name,`Native Builder check ${i} name`),result:r.result,note:r.note}})}function d1(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,i)=>{let r=ng(t,`Native Runtime check ${i}`);if(ha(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${i}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${i} argv is invalid`);if(!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1)throw new Error(`Native Runtime check ${i} timeoutMs is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Runtime check ${i} repeatable is invalid`);return{id:nr(r.id,`Native Runtime check ${i} id`),name:nr(r.name,`Native Runtime check ${i} name`),executable:nr(r.executable,`Native Runtime check ${i} executable`),argv:[...r.argv],cwdRef:nr(r.cwdRef,`Native Runtime check ${i} cwdRef`),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function oC(e,t){let i=e.stateVersion,r=e.iteration,n=e.attempt;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:i,iteration:r,attempt:n,verifierExecutionRef:nr(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function f1(e){let t=ng(e,"Native Runner input");if(t.kind==="builder-handoff")return ha(t,["kind","summary","addressed_acceptance_ids","checks","known_limits"],"Native Runner Builder input"),{kind:"builder-handoff",summary:nr(t.summary,"Native Builder summary"),addressed_acceptance_ids:aC(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:u1(t.checks),known_limits:aC(t.known_limits,"Native Builder known limits")};if(t.kind==="dispatch-verifier")return ha(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:d1(t.checks)};if(t.kind==="verifier-response")return ha(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return ha(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:nr(t.summary,"Native Verifier execution error summary"),...oC(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ha(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:nr(t.summary,"Native unavailable Verifier summary"),...oC(t,"Native Runner unavailable Verifier input")};throw new Error("Native Runner input kind is invalid")}async function lC(e,t){let i=l1.resolve(t,e),r=await nC.lstat(i);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await nC.readFile(i,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return f1(n)}function sC(e){return`${Ge}:${e}:${c1()}`}function Vc(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Ge)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 h1(e){return{iteration:e.iteration,summary:e.summary,addressedAcceptanceIds:[...e.addressed_acceptance_ids],checks:e.checks.map(t=>({name:t.name,result:t.result,note:t.note})),checksTruncated:e.checks_truncated,knownLimits:e.known_limits.map(t=>({...t})),knownLimitsTruncated:e.known_limits_truncated,submittedAt:e.submitted_at}}function cC(e,t,i){let r=Vc(e);return{coordination:Ge,change:e.name,candidateId:r.candidate_id,stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:i,briefRef:e.brief,specRefs:e.spec_changes.map(({capability:n,operation:a,source:o})=>({capability:n,operation:a,ref:o})),acceptance:e.acceptance.map(({id:n,source:a,text:o})=>({id:n,source:a,text:o})),builderHandoff:h1(r),runtimeChecks:t.map(n=>({...n}))}}async function rg(e){Vc(e.state);let t=await Ci(ae(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 uC(e){if(e.input.kind==="builder-handoff"){let c=Ys().captureExecutionIdentity({identityProvider:Ge,executionRef:sC("builder")}),l=await eS({paths:e.paths,name:e.name,input:{identity:c,summary:e.input.summary,addressedAcceptanceIds:e.input.addressed_acceptance_ids,checks:e.input.checks,knownLimits:e.input.known_limits}});return{state:l,checks:[],requestChecks:null,verifierDispatch:null,continuation:de(l)}}if(e.input.kind==="dispatch-verifier"){let s=await K(e.paths,e.name);if(s.builder_handoff!==null&&s.builder_handoff.identity_provider!==Ge){let d=await no({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:d,checks:[],requestChecks:null,verifierDispatch:null,continuation:de(d)}}Vc(s);let c=await aS({paths:e.paths,name:e.name,plans:e.input.checks}),l=sC("verifier"),u=await oS({paths:e.paths,name:e.name,checks:c.checks,verifierExecutionId:l});return{state:u,checks:c.checks,requestChecks:null,verifierDispatch:cC(u,c.checks,l),continuation:de(u)}}if(e.input.kind==="verifier-execution-error"){let s=await K(e.paths,e.name);Vc(s),await rg({paths:e.paths,state:s});let c=await cS({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:c,checks:[],requestChecks:null,verifierDispatch:null,continuation:de(c)}}if(e.input.kind==="verifier-unavailable"){let s=await lS({paths:e.paths,name:e.name,summary:e.input.summary,expected:e.input,requireSkillCoordination:!0});return{state:s,checks:s.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:de(s)}}let t=await K(e.paths,e.name),i=Vc(t),r=await rg({paths:e.paths,state:t}),n=Ys(),a=n.captureExecutionIdentity({identityProvider:Ge,executionRef:r}),o=await sS({paths:e.paths,name:e.name,envelope:n.envelopeVerifierResponse({candidateId:i.candidate_id,identity:a,payload:e.input.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures});return{...o,verifierDispatch:o.requestChecks===null?null:cC(o.state,o.checks,await rg({paths:e.paths,state:o.state})),continuation:de(o.state)}}async function _o(e,t){let i=await Gt({paths:e,state:t});return{...i?{children:i.children,readyChildren:i.readyChildren}:{},continuation:de(t,i)}}async function dC(e,t){let i=rt(e,"change name"),r=Ae(e,"--summary"),n=Ae(e,"--runner-input"),a=Bt(e,"--confirmed"),o=Bt(e,"--return-to-build"),s=Bt(e,"--retry-verifier"),c=Bt(e,"--resolve-verifier-blocker");if([a,o,s,c].filter(Boolean).length>1)throw new O("--confirmed, --return-to-build, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");Se(e);let l=await ir(t);if(!await ke(l.paths,i)){if(n)throw new O("--runner-input is only valid for portable Native changes");if(!r)throw new O("--summary is required");let h=await xi({paths:l.paths,name:i});return W("next",{state:h,migration:{completed:!0,summary:r},continuation:de(h)})}if(n){if(r||a||o||s||c)throw new O("--runner-input cannot be combined with --summary or Agent transition flags");let h=await ta({paths:l.paths,name:i,preserveRunningExecution:!0}),m=h.state;if(h.action==="await-user"||h.action==="done"||h.reason!=="available")return W("next",{state:m,recovery:h,...await _o(l.paths,m)});if(m.phase==="build"){let g=await Zn({paths:l.paths,state:m});if(g.drifted){let y=await nc({paths:l.paths,name:i,reason:g.reason??"Native confirmed requirements changed"});return W("next",{state:y,...await _o(l.paths,y)})}if(await Gt({paths:l.paths,state:m}))throw new O("Native parent Build advances child changes and does not accept a Builder handoff")}let p=await lC(n,t),v=await uC({paths:l.paths,name:i,input:p,maxVerifyFailures:l.config.native.max_verify_failures});return W("next",{...v,...await _o(l.paths,v.state),coordination:Ge})}let u=await ta({paths:l.paths,name:i}),d=u.state;if(!r)throw new O("--summary is required");let f;if(a)if(d.phase==="shape")f=await Zk({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-skill-coordinated-pass")f=await uS({paths:l.paths,name:i});else if(d.phase==="verify"&&d.status==="await-user"&&d.loop.next_action==="confirm-verifier-unavailable")f=await dS({paths:l.paths,name:i,summary:r});else throw new O("--confirmed is only valid in Shape, for an accepted Skill-coordinated pass, or for a user-accepted degraded verification fallback");else if(o)f=await no({paths:l.paths,name:i,reason:r});else if(s)f=await hS({paths:l.paths,name:i});else if(c)f=await fS({paths:l.paths,name:i});else{if(u.reason!=="available")return W("next",{state:d,recovery:u,...await _o(l.paths,d)});if(d.phase==="build"){let h=await Zn({paths:l.paths,state:d});if(h.drifted)f=await nc({paths:l.paths,name:i,reason:h.reason??"Native confirmed requirements changed"});else{let m=await Gt({paths:l.paths,state:d});if(m)if(m.allDone&&!(d.loop.stage==="repairing"&&d.verification_result==="fail"))f=await tS({paths:l.paths,name:i,summary:r});else return W("next",{state:d,children:m.children,readyChildren:m.readyChildren,continuation:de(d,m)})}}return f?W("next",{state:f,...await _o(l.paths,f)}):{command:"next",exitCode:65,data:{state:d,continuation:de(d)},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 W("next",{state:f,...await _o(l.paths,f)})}async function fC(e,t){let i=rt(e,"root subcommand");if(i==="show"){Se(e);let r=await Y(t);if(!r)throw new Error(".comet/config.yaml was not found");let n=await re(t,r.native.artifact_root);return W("root show",{projectRoot:t,artifactRoot:r.native.artifact_root,language:r.native.language,nativeRoot:n.nativeRoot,pendingRootMove:r.native.pending_root_move??null})}if(i==="move"){let r=rt(e,"artifact root");Se(e);let n=await BR({projectRoot:t,toArtifactRoot:r});return W("root move",n,`Moved Comet Native to ${n.toNativeRoot}
|
|
294
|
+
`)}throw new O(`Unknown root command: ${i}`)}async function hC(e,t){let i=rt(e,"change name");Se(e);let{config:r,paths:n}=await ir(t);await gd(n,i);let a=await ke(n,i)?await ji({paths:n,name:i}):await yn(n,i,{clarificationMode:r.native.clarification_mode,maxVerifyFailures:r.native.max_verify_failures});return W("select",{selected:i,continuation:a.continuation},`Selected Native change ${i}
|
|
295
|
+
`)}import{promises as pC}from"fs";import mC from"path";var vC=Ti.maxSpecs*4;async function p1(e,t){let i=mC.join(te(e,t),"specs"),r;try{r=await Wt({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let n=[],a=0,o=await pC.opendir(i);try{for await(let s of o){if(a+=1,a>vC)throw new Error(`Native proposed specs directory exceeds ${vC} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Un(s.name);let c=mC.join(i,s.name,"spec.md");await T(e.nativeRoot,c);let l;try{l=await pC.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(n.push(s.name),n.length>Ti.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await r.verify(),n.sort()}async function gC(e,t){let i=te(e,t),r={},n=0;for(let a of await p1(e,t)){let o=await ee({root:i,ref:`specs/${a}/spec.md`,maxBytes:Ti.maxFileBytes});if(n+=o.size,n>Ti.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");r[a]=o.text}return r}async function wC(e,t){let i=rt(e,"change name");Se(e);let{paths:r}=await ir(t);if(await ke(r,i)){let u=await K(r,i),d=we(r,i),f=await ee({root:d,ref:u.brief,maxBytes:null,includeHash:!1}),h=[];for(let p of u.spec_changes){if(p.source===null)continue;let v=await ee({root:d,ref:p.source,maxBytes:null,includeHash:!1});h.push({capability:p.capability,operation:p.operation,source:p.source,content:v.text})}let m={state:u,brief:f.text,proposedSpecs:h,continuation:de(u,await Gt({paths:r,state:u}))};return W("show",m)}let n=await li(r,i);if(n.status==="migration-required")return W("show",{name:i,schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,migrationRequired:!0,message:n.message});if(n.status!=="current"||!n.state)throw new pr(n.schema,n.minimumRuntimeVersion);let a=n.state,o=te(r,i),s=await gC(r,i),c=await ee({root:o,ref:a.brief,maxBytes:Ti.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>nR)throw new Error("Native show output exceeds its serialized byte budget");return W("show",l)}async function yC(e,t){let i=rt(e,"spec subcommand");if(i!=="remove")throw new O(`Unknown spec command: ${i}`);let r=rt(e,"change name"),n=rt(e,"capability");Se(e);let{paths:a}=await ir(t);await ke(a,r)||await xi({paths:a,name:r});let o=await pS({paths:a,name:r,capability:n});return W("spec remove",{...o,continuation:de(o)},`Marked Native capability ${n} for removal in ${r}
|
|
296
|
+
`)}import Sn from"node:path";var m1=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function ag(e,t){let i=Sn.normalize(e),r=Sn.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function v1(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function NC(e){let t=[];for(let i of await Vv(e))t.push({name:i,kind:await ke(e,i)?"portable":"legacy"});return t}async function EC(e){let t=Zt(e),i=t.length>0?t:[Sn.resolve(e)];i.some(n=>ag(n,e))||i.push(Sn.resolve(e));let r=[];for(let n of[...new Set(i.map(a=>Sn.resolve(a)))].sort()){let a=await Y(n);if(!a)continue;let o=await re(n,a.native.artifact_root);r.push({projectRoot:n,config:a,paths:o,changes:await NC(o)})}if(r.length===0){let n=await Y(e);if(!n)throw new Error(".comet/config.yaml was not found in any registered worktree");let a=await re(e,n.native.artifact_root);r.push({projectRoot:Sn.resolve(e),config:n,paths:a,changes:await NC(a)})}return r}function bC(e,t){return e.workspace.bindingState==="aligned"?0:ag(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function PC(e,t){let i=new Map;for(let n of t)for(let a of n.changes)i.set(a.name,[...i.get(a.name)??[],{source:n,kind:a.kind}]);let r=[];for(let[n,a]of[...i.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:c,kind:l})=>{if(l==="portable"){let u=await ji({paths:c.paths,name:n});return{source:c,name:n,kind:l,workspace:u.workspace,portableStatus:u}}return{source:c,name:n,kind:l,workspace:await Ku(c.paths,n),portableStatus:null}}));o.sort((c,l)=>bC(c,e)-bC(l,e)||c.source.projectRoot.localeCompare(l.source.projectRoot));let s=o.filter(c=>c.workspace.bindingState==="aligned");s.length>1?r.push(...s):r.push(s[0]??o[0])}if(r.length>Qt.maxChanges)throw new Error(`Native status discovery exceeds ${Qt.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function kC(e,t){let i=t.toString(36),r=D("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function g1(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=m1.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let r=D("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:i});if(t[3]!==r)throw new Error("Native workspace status cursor integrity failed");return i}function SC(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?v1(i):null,nextPageArgs:i}}async function w1(e,t,i){let r=null;try{r=await Kn(e.source.paths,e.name)}catch{}return r?.state?{schema:"comet.native.status.v2",name:e.name,phase:r.state.phase,status:"blocked",migrationRequired:!0,legacySchema:r.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:r.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:yn(e.source.paths,e.name,{details:t,...i?{acceptanceCursor:i}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function RC(e,t,i){if(e.kind==="portable"){if(i)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:ji({paths:e.source.paths,name:e.name,details:t})}return w1(e,t,i)}async function CC(e){let t=await EC(e.projectRoot),i=(await PC(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>ag(n.projectRoot,e.projectRoot))??t[0];return yn(r.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:r.config.native.clarification_mode,maxVerifyFailures:r.config.native.max_verify_failures})}if(i.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${i.map(r=>r.source.projectRoot).join(", ")}`);return RC(i[0],e.details??!1,e.acceptanceCursor)}async function xC(e){let t=await EC(e.projectRoot),i=await PC(e.projectRoot,t),r=D("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=g1({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+Qt.maxItems).map(u=>RC(u,!1))),o=[],s=i.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,h=f<i.length?kC(r,f):null,m={schema:s,total:i.length,offset:n,items:d,nextCursor:h,...SC(Sn.resolve(e.projectRoot),h),limits:{...Qt}};if(Buffer.byteLength(JSON.stringify(m),"utf8")>Qt.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<i.length?kC(r,c):null;return{schema:s,total:i.length,offset:n,items:o,nextCursor:l,...SC(Sn.resolve(e.projectRoot),l),limits:{...Qt}}}async function AC(e,t){let i=Bt(e,"--details"),r=Ae(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!n)throw new O("status --details requires a change name");if(r&&n)throw new O("--cursor is only valid for status lists");if(r&&i)throw new O("--cursor cannot be combined with --details");Se(e);let a=n?await CC({projectRoot:t,name:n,details:i}):await xC({projectRoot:t,...r?{cursor:r}:{}});return W("status",a)}var y1={"hook-guard":tC,init:iC,root:fC,new:rC,spec:yC,show:wC,status:AC,select:hC,next:dC,archive:cR,doctor:eg};async function N1(e,t){let i=e.indexOf("--help");if(e.length===0||i>=0||e[0]==="help"){let o=e[0]==="help"?e.slice(1):i>=0?e.slice(0,i):[],s;try{s=Dv(o)}catch(c){throw new O(c.message)}return{command:s.topic?`${s.topic} --help`:"help",exitCode:0,data:s,text:s.usage}}let r=e.shift(),n=await aR(t),a=y1[r];if(!a)throw new O(`Unknown Native command: ${r}`);return a(e,n)}async function _C(e){let t=[...e],i=t.indexOf("--"),r=i<0?t:t.slice(0,i),n=i<0?[]:t.slice(i),a=r.includes("--json"),o,s=r[0]??null;try{Bt(r,"--json"),o=Ae(r,"--project-root");let c=[...r,...n];return s=c[0]??null,Mv(await N1(c,o),a)}catch(c){return Mv(sR(s,c),a)}}async function k1(e=process.argv.slice(2)){let t=await _C(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(`
|
|
297
297
|
`)?"":`
|
|
298
|
-
`)),t.exitCode}var
|
|
298
|
+
`)),t.exitCode}var TC=process.argv[1];TC&&import.meta.url===b1(TC).href&&k1().then(e=>{process.exitCode=e});export{k1 as main};
|