eutaxy 0.17.1 → 0.18.0

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.
Files changed (35) hide show
  1. package/README.md +6 -6
  2. package/dist/aws.d.mts +2 -2
  3. package/dist/aws.mjs +2 -2
  4. package/dist/bin.mjs +1 -1
  5. package/dist/{cli-CxbXc1j2.mjs → cli-DyA7uTBg.mjs} +801 -449
  6. package/dist/cli-DyA7uTBg.mjs.map +1 -0
  7. package/dist/cli.d.mts.map +1 -1
  8. package/dist/cli.mjs +1 -1
  9. package/dist/cloudflare.d.mts +22 -3
  10. package/dist/cloudflare.d.mts.map +1 -1
  11. package/dist/cloudflare.mjs +3 -3
  12. package/dist/{delivery-invariants-DO3j1mmD.mjs → delivery-invariants-BRwfZJrs.mjs} +2 -2
  13. package/dist/{delivery-invariants-DO3j1mmD.mjs.map → delivery-invariants-BRwfZJrs.mjs.map} +1 -1
  14. package/dist/{delivery-invariants-D7DI7i8x.d.mts → delivery-invariants-D-_GPOqE.d.mts} +2 -2
  15. package/dist/{delivery-invariants-D7DI7i8x.d.mts.map → delivery-invariants-D-_GPOqE.d.mts.map} +1 -1
  16. package/dist/{explore-CkKiOuz6.d.mts → explore-D33RP9hF.d.mts} +43 -8
  17. package/dist/explore-D33RP9hF.d.mts.map +1 -0
  18. package/dist/index.d.mts +11 -3
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +3 -3
  21. package/dist/{platform-D4hlJjm3.d.mts → platform-CawKCUru.d.mts} +69 -2
  22. package/dist/platform-CawKCUru.d.mts.map +1 -0
  23. package/dist/{src-fxWc6oGc.mjs → src-H1Q8ytEx.mjs} +50 -6
  24. package/dist/src-H1Q8ytEx.mjs.map +1 -0
  25. package/dist/{src-D_hHC_-3.mjs → src-Whn0RMSh.mjs} +406 -51
  26. package/dist/src-Whn0RMSh.mjs.map +1 -0
  27. package/dist/{workerd-DhrzU6AZ.mjs → workerd-tI8INa6v.mjs} +43 -9
  28. package/dist/workerd-tI8INa6v.mjs.map +1 -0
  29. package/package.json +1 -1
  30. package/dist/cli-CxbXc1j2.mjs.map +0 -1
  31. package/dist/explore-CkKiOuz6.d.mts.map +0 -1
  32. package/dist/platform-D4hlJjm3.d.mts.map +0 -1
  33. package/dist/src-D_hHC_-3.mjs.map +0 -1
  34. package/dist/src-fxWc6oGc.mjs.map +0 -1
  35. package/dist/workerd-DhrzU6AZ.mjs.map +0 -1
@@ -1,15 +1,15 @@
1
- import { R as canonicalJson } from "./src-D_hHC_-3.mjs";
2
- import { _ as render, a as renderText, c as checkSpecModule, d as shrinkRefutation, g as endpointNumber, h as endpointBigInt, i as renderSpecs, m as conforms, n as renderSpecReport, p as evaluate, r as renderSpecReportJson, v as describeType } from "./src-fxWc6oGc.mjs";
1
+ import { z as canonicalJson } from "./src-Whn0RMSh.mjs";
2
+ import { _ as endpointNumber, a as renderText, f as shrinkRefutation, g as endpointBigInt, h as conforms, i as renderSpecs, l as checkSpecModule, m as evaluate, n as renderSpecReport, r as renderSpecReportJson, v as render, y as describeType } from "./src-H1Q8ytEx.mjs";
3
3
  import { n as isSpec } from "./combinators-CLfsPfhT.mjs";
4
4
  import { t as aggregate } from "./provers-DS44OeEm.mjs";
5
- import { n as globKey, q as cloudflareRegressionTest, r as specKey } from "./workerd-DhrzU6AZ.mjs";
5
+ import { J as cloudflareRegressionTest, Y as cloudflareUnsupportedTest, n as globKey, r as specKey } from "./workerd-tI8INa6v.mjs";
6
6
  import { createRequire, registerHooks } from "node:module";
7
7
  import { Readable } from "node:stream";
8
8
  import { createHash, randomBytes } from "node:crypto";
9
- import { chmodSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync, writeSync } from "node:fs";
9
+ import { chmodSync, closeSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs";
10
10
  import { availableParallelism, homedir, tmpdir } from "node:os";
11
11
  import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
12
- import { createZstdDecompress, inflateRawSync } from "node:zlib";
12
+ import { crc32, gunzipSync, inflateRawSync } from "node:zlib";
13
13
  import { fork, spawn } from "node:child_process";
14
14
  import { InternalSymbolName, ModifierFlags, NodeFlags, SyntaxKind, forEachLeadingCommentRange, forEachTrailingCommentRange } from "typescript/ast";
15
15
  import { createFileSystemLayer } from "typescript/fs";
@@ -3633,6 +3633,189 @@ function readSpecs(input) {
3633
3633
  };
3634
3634
  });
3635
3635
  }
3636
+ // packages/prover/src/toolchain.ts
3637
+ /**
3638
+ * Where a pinned prover toolchain lives on this machine once `eutaxy prover
3639
+ * install` has put it there, and what that command downloads: one upstream
3640
+ * release file per platform, with the checksum the download must match.
3641
+ * Node-side only (`@eutaxy/prover/toolchain`, a subpath so workerd never
3642
+ * loads it): it reads the file system, so this file alone references Node's
3643
+ * types, as the reader alone uses the compiler's. Nothing here downloads or
3644
+ * runs anything; the engines ask `installed` and the command does the rest.
3645
+ */
3646
+ const platforms = [
3647
+ "linux-x64",
3648
+ "linux-arm64",
3649
+ "darwin-x64",
3650
+ "darwin-arm64",
3651
+ "win32-x64"
3652
+ ];
3653
+ function host() {
3654
+ return {
3655
+ platform: process.platform,
3656
+ arch: process.arch,
3657
+ env: process.env,
3658
+ home: homedir()
3659
+ };
3660
+ }
3661
+ function platformOf(h) {
3662
+ const key = `${h.platform}-${h.arch}`;
3663
+ return platforms.includes(key) ? key : void 0;
3664
+ }
3665
+ /**
3666
+ * Eutaxy's cache directory: `EUTAXY_CACHE_DIR`, else the platform's user
3667
+ * cache (`$XDG_CACHE_HOME/eutaxy` or `~/.cache/eutaxy` on Linux,
3668
+ * `~/Library/Caches/eutaxy` on macOS, `%LOCALAPPDATA%\eutaxy\Cache` on
3669
+ * Windows). Always absolute: the engines spawn the executable from a
3670
+ * scratch directory, where a relative path would not resolve.
3671
+ */
3672
+ function cacheDir(h = host()) {
3673
+ const set = h.env["EUTAXY_CACHE_DIR"];
3674
+ if (set) return resolve(set);
3675
+ if (h.platform === "darwin") return join(h.home, "Library", "Caches", "eutaxy");
3676
+ if (h.platform === "win32") return join(h.env["LOCALAPPDATA"] || join(h.home, "AppData", "Local"), "eutaxy", "Cache");
3677
+ return resolve(h.env["XDG_CACHE_HOME"] || join(h.home, ".cache"), "eutaxy");
3678
+ }
3679
+ /** Where one toolchain's unpacked release lives: `<cache>/toolchains/<name>/<version>`. */
3680
+ function toolchainDir(cache, toolchain) {
3681
+ return join(cache, "toolchains", toolchain.name, toolchain.version);
3682
+ }
3683
+ /** The file the command writes last, so its presence means the install completed. */
3684
+ const markerFile = "eutaxy-toolchain.json";
3685
+ function executableName(toolchain, h) {
3686
+ return h.platform === "win32" ? `${toolchain.executable}.exe` : toolchain.executable;
3687
+ }
3688
+ /**
3689
+ * The toolchain the command put in the cache, if its marker and its
3690
+ * executable are both there and the marker names this toolchain for this
3691
+ * platform (a cache carried to another machine holds the wrong binary).
3692
+ */
3693
+ function installed(toolchain, h = host()) {
3694
+ const dir = toolchainDir(cacheDir(h), toolchain);
3695
+ const executable = join(dir, executableName(toolchain, h));
3696
+ const markerPath = join(dir, markerFile);
3697
+ if (!existsSync(markerPath) || !existsSync(executable)) return void 0;
3698
+ try {
3699
+ const marker = JSON.parse(readFileSync(markerPath, "utf8"));
3700
+ if (marker.name !== toolchain.name || marker.version !== toolchain.version || marker.platform !== platformOf(h) || typeof marker.file !== "string" || typeof marker.sha256 !== "string" || typeof marker.source !== "string") return void 0;
3701
+ return {
3702
+ dir,
3703
+ executable,
3704
+ marker
3705
+ };
3706
+ } catch {
3707
+ return;
3708
+ }
3709
+ }
3710
+ // packages/prover-lean/src/elan.ts
3711
+ /**
3712
+ * Lean's toolchain comes through elan, Lean's own toolchain manager. This
3713
+ * file holds what `eutaxy prover install lean` and the engine share about
3714
+ * it: the pinned elan installer (`elanDownloads`, fetched only when no elan
3715
+ * is on the machine), where Eutaxy keeps an elan of its own (`elanHome`,
3716
+ * inside Eutaxy's cache), the elans the engine and the command look for
3717
+ * (`elanCandidates`), and the digest of the pinned toolchain's files
3718
+ * (`leanDigests`, `toolchainDigest`), which the command checks after elan
3719
+ * has installed it, since elan does not check the toolchain it downloads
3720
+ * against a pinned checksum.
3721
+ */
3722
+ /** The elan release whose installer the command fetches when the machine has no elan. */
3723
+ const elanVersion = "4.2.4";
3724
+ const elanRelease = `https://github.com/leanprover/elan/releases/download/v${elanVersion}`;
3725
+ const elanFile = (name, sha256, bytes) => {
3726
+ const installer = name.endsWith(".zip") ? "elan-init.exe" : "elan-init";
3727
+ return {
3728
+ file: name,
3729
+ url: `${elanRelease}/${name}`,
3730
+ sha256,
3731
+ bytes,
3732
+ entries: { [installer]: installer }
3733
+ };
3734
+ };
3735
+ /**
3736
+ * The upstream elan installer for each platform, as published on elan's
3737
+ * GitHub release with the checksums it reports; a test holds the file
3738
+ * names to `elanVersion`. The installer links only system libraries.
3739
+ */
3740
+ const elanDownloads = {
3741
+ name: "elan",
3742
+ version: elanVersion,
3743
+ executable: "elan-init",
3744
+ files: {
3745
+ "linux-x64": elanFile("elan-x86_64-unknown-linux-gnu.tar.gz", "42b94d4244e8353142c456ec0e4ca6528fd898a6c604d4059f494e706e431f63", 4996571),
3746
+ "linux-arm64": elanFile("elan-aarch64-unknown-linux-gnu.tar.gz", "05febd124d84ebf994b2e7479922a5650b1e950c17ae3bd1ddd776b65bb72bf9", 5131114),
3747
+ "darwin-x64": elanFile("elan-x86_64-apple-darwin.tar.gz", "8a340b309d8ed2e96f930761fa223b3af57a38f5d253b53ac90293c9516f8cd4", 2330818),
3748
+ "darwin-arm64": elanFile("elan-aarch64-apple-darwin.tar.gz", "7ad829861392c718dfebde3a83b5c8508df47be02af68894b094b0b3952616e5", 2190845),
3749
+ "win32-x64": elanFile("elan-x86_64-pc-windows-msvc.zip", "fad2e980a191c15884cc1d80d170ffc5fa84f3774541020145b66d1a644c6111", 2508099)
3750
+ }
3751
+ };
3752
+ /** Where Eutaxy's own elan keeps itself and its toolchains: `<cache>/elan`. */
3753
+ function elanHome(h) {
3754
+ return join(cacheDir(h), "elan");
3755
+ }
3756
+ /**
3757
+ * The elans to try, in order: Eutaxy's own in the cache, then the one on
3758
+ * the PATH, then the one in elan's home (`ELAN_HOME`, else `~/.elan`).
3759
+ */
3760
+ function elanCandidates(h) {
3761
+ const exe = h.platform === "win32" ? "elan.exe" : "elan";
3762
+ const own = elanHome(h);
3763
+ const home = h.env["ELAN_HOME"] || join(h.home || homedir(), ".elan");
3764
+ return [
3765
+ {
3766
+ command: join(own, "bin", exe),
3767
+ env: { ELAN_HOME: own }
3768
+ },
3769
+ { command: "elan" },
3770
+ { command: join(home, "bin", exe) }
3771
+ ];
3772
+ }
3773
+ /**
3774
+ * The pinned toolchain's `toolchainDigest`, per platform: computed over
3775
+ * Lean's GitHub release file for that platform, checked against the
3776
+ * checksum the release reports, and unpacked. elan installs exactly that
3777
+ * release (on macOS arm64 the digest of an elan-installed toolchain was
3778
+ * checked to equal it), so a toolchain elan installed whose digest differs
3779
+ * is not the pinned one.
3780
+ */
3781
+ const leanDigests = {
3782
+ "linux-x64": "d6bb6c4de1fce52bc5d88ff52f7fcf7d347ee5b3ba7d187de775ccf915714c35",
3783
+ "linux-arm64": "1bcaf2cf93006e3017a07234e3a33ba8bd1dec404e7dc0e4c202111b0bf2be41",
3784
+ "darwin-x64": "b817cf3c90432b774405bad998bad5985f0ef9594d1c31aeddb3df6479c1bd0c",
3785
+ "darwin-arm64": "2a31778d0185a17655be5f97e6e930dd0ece0d1db9f41a2825f500b3ca8c5c0a",
3786
+ "win32-x64": "441877e59afc80b7af1f1b6fc3db64b2c947d581de26a040486387aa4ec7a3cb"
3787
+ };
3788
+ /**
3789
+ * A digest of everything under a toolchain's directory: one line per file
3790
+ * (`<sha256> <path>`) and per link (`-> <target> <path>`), paths relative
3791
+ * and with `/`, sorted, the whole hashed. Directories count only through
3792
+ * what they hold.
3793
+ */
3794
+ function toolchainDigest(prefix) {
3795
+ const lines = [];
3796
+ let files = 0;
3797
+ let bytes = 0;
3798
+ for (const entry of readdirSync(prefix, {
3799
+ recursive: true,
3800
+ withFileTypes: true
3801
+ })) {
3802
+ const at = join(entry.parentPath, entry.name);
3803
+ const path = relative(prefix, at).split(sep).join("/");
3804
+ if (entry.isSymbolicLink()) lines.push([path, `-> ${readlinkSync(at)} ${path}`]);
3805
+ else if (entry.isFile()) {
3806
+ const data = readFileSync(at);
3807
+ files++;
3808
+ bytes += data.length;
3809
+ lines.push([path, `${createHash("sha256").update(data).digest("hex")} ${path}`]);
3810
+ }
3811
+ }
3812
+ lines.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
3813
+ return {
3814
+ digest: createHash("sha256").update(`${lines.map(([, line]) => line).join("\n")}\n`).digest("hex"),
3815
+ files,
3816
+ bytes
3817
+ };
3818
+ }
3636
3819
  // packages/prover-lean/src/emit.ts
3637
3820
  /**
3638
3821
  * Lean 4 for a module in the subset and the properties on it. The
@@ -4085,87 +4268,13 @@ function leanString(value) {
4085
4268
  }
4086
4269
  return `${out}"`;
4087
4270
  }
4088
- // packages/prover/src/toolchain.ts
4089
- /**
4090
- * Where a pinned prover toolchain lives on this machine once `eutaxy prover
4091
- * install` has put it there, and what that command downloads: one upstream
4092
- * release file per platform, with the checksum the download must match.
4093
- * Node-side only (`@eutaxy/prover/toolchain`, a subpath so workerd never
4094
- * loads it): it reads the file system, so this file alone references Node's
4095
- * types, as the reader alone uses the compiler's. Nothing here downloads or
4096
- * runs anything; the engines ask `installed` and the command does the rest.
4097
- */
4098
- const platforms = [
4099
- "linux-x64",
4100
- "linux-arm64",
4101
- "darwin-x64",
4102
- "darwin-arm64",
4103
- "win32-x64"
4104
- ];
4105
- function host() {
4106
- return {
4107
- platform: process.platform,
4108
- arch: process.arch,
4109
- env: process.env,
4110
- home: homedir()
4111
- };
4112
- }
4113
- function platformOf(h) {
4114
- const key = `${h.platform}-${h.arch}`;
4115
- return platforms.includes(key) ? key : void 0;
4116
- }
4117
- /**
4118
- * Eutaxy's cache directory: `EUTAXY_CACHE_DIR`, else the platform's user
4119
- * cache (`$XDG_CACHE_HOME/eutaxy` or `~/.cache/eutaxy` on Linux,
4120
- * `~/Library/Caches/eutaxy` on macOS, `%LOCALAPPDATA%\eutaxy\Cache` on
4121
- * Windows). Always absolute: the engines spawn the executable from a
4122
- * scratch directory, where a relative path would not resolve.
4123
- */
4124
- function cacheDir(h = host()) {
4125
- const set = h.env["EUTAXY_CACHE_DIR"];
4126
- if (set) return resolve(set);
4127
- if (h.platform === "darwin") return join(h.home, "Library", "Caches", "eutaxy");
4128
- if (h.platform === "win32") return join(h.env["LOCALAPPDATA"] || join(h.home, "AppData", "Local"), "eutaxy", "Cache");
4129
- return resolve(h.env["XDG_CACHE_HOME"] || join(h.home, ".cache"), "eutaxy");
4130
- }
4131
- /** Where one toolchain's unpacked release lives: `<cache>/toolchains/<name>/<version>`. */
4132
- function toolchainDir(cache, toolchain) {
4133
- return join(cache, "toolchains", toolchain.name, toolchain.version);
4134
- }
4135
- /** The file the command writes last, so its presence means the install completed. */
4136
- const markerFile = "eutaxy-toolchain.json";
4137
- function executableName(toolchain, h) {
4138
- return h.platform === "win32" ? `${toolchain.executable}.exe` : toolchain.executable;
4139
- }
4140
- /**
4141
- * The toolchain the command put in the cache, if its marker and its
4142
- * executable are both there and the marker names this toolchain for this
4143
- * platform (a cache carried to another machine holds the wrong binary).
4144
- */
4145
- function installed(toolchain, h = host()) {
4146
- const dir = toolchainDir(cacheDir(h), toolchain);
4147
- const executable = join(dir, executableName(toolchain, h));
4148
- const markerPath = join(dir, markerFile);
4149
- if (!existsSync(markerPath) || !existsSync(executable)) return void 0;
4150
- try {
4151
- const marker = JSON.parse(readFileSync(markerPath, "utf8"));
4152
- if (marker.name !== toolchain.name || marker.version !== toolchain.version || marker.platform !== platformOf(h) || typeof marker.file !== "string" || typeof marker.sha256 !== "string" || typeof marker.source !== "string") return void 0;
4153
- return {
4154
- dir,
4155
- executable,
4156
- marker
4157
- };
4158
- } catch {
4159
- return;
4160
- }
4161
- }
4162
4271
  // packages/prover-lean/src/lean.ts
4163
4272
  /**
4164
4273
  * Running Lean over a process boundary. The engine is pinned to one Lean
4165
- * release, looked for in Eutaxy's cache first (where `eutaxy prover install
4166
- * lean` puts the upstream release named in `leanDownloads`), then through
4167
- * `elan` (Lean's toolchain manager), asked for it by name, then as a bare
4168
- * `lean` that must report that version. Nothing is ever downloaded during
4274
+ * release, looked for through elan (Lean's toolchain manager), asked for it
4275
+ * by name: Eutaxy's own elan in its cache first (where `eutaxy prover
4276
+ * install lean` puts one when the machine has none), then the user's; then
4277
+ * as a bare `lean` that must report that version. Nothing is ever downloaded during
4169
4278
  * a check; a missing toolchain is `unavailable`, with the command that
4170
4279
  * installs it. Diagnostics come back as `file:line:col: severity: message`
4171
4280
  * lines, which the engine maps to theorems.
@@ -4182,38 +4291,16 @@ const leanToolchain = "leanprover/lean4:v4.35.0";
4182
4291
  const leanVersion = "4.35.0";
4183
4292
  /** How to put the pinned toolchain on this machine. */
4184
4293
  const installHint$1 = `run: eutaxy prover install lean (or install elan, https://elan.lean-lang.org, and run: elan toolchain install ${leanToolchain})`;
4185
- const leanRelease = `https://github.com/leanprover/lean4/releases/download/v${leanVersion}`;
4186
- const leanFile = (name, sha256, bytes) => ({
4187
- file: name,
4188
- url: `${leanRelease}/${name}`,
4189
- sha256,
4190
- bytes
4191
- });
4192
- /**
4193
- * The upstream release files `eutaxy prover install lean` downloads, one per
4194
- * platform, as published on Lean's GitHub release with the checksums it
4195
- * reports; the file names carry the version, and a test holds them to
4196
- * `leanVersion`. The compiler ships its C toolchain, so each is 570 to
4197
- * 620 MB, the same download elan makes.
4198
- */
4199
- const leanDownloads = {
4200
- name: "lean",
4201
- version: leanVersion,
4202
- executable: "bin/lean",
4203
- files: {
4204
- "linux-x64": leanFile("lean-4.35.0-linux.tar.zst", "7289597a44543246c9227b8cae501767e095ce17f6d448b95fc4a8dc97268f6d", 594481375),
4205
- "linux-arm64": leanFile("lean-4.35.0-linux_aarch64.tar.zst", "c8f0f8a3920e839718b1343e6781fd80a3e9b1024fbcd7078eb30f54e806b028", 594868592),
4206
- "darwin-x64": leanFile("lean-4.35.0-darwin.tar.zst", "0b43be5c7ecfb36016566a41005ab62bdb04743e6bfd5837e45f796ef4750b4e", 576516478),
4207
- "darwin-arm64": leanFile("lean-4.35.0-darwin_aarch64.tar.zst", "c0c6f34f35ba1dcc5c4a5fd106fefab9eb5e8469712624dd2c868d51b63177c2", 570422530),
4208
- "win32-x64": leanFile("lean-4.35.0-windows.tar.zst", "893fde3f52b48c647e3edcf33844cbb61f8ef70fcd88e0536bfc83f29844081e", 622724192)
4209
- }
4210
- };
4211
4294
  function run$1(command, args, options) {
4212
4295
  return new Promise((resolve) => {
4213
4296
  let child;
4214
4297
  try {
4215
4298
  child = spawn(command, args, {
4216
4299
  cwd: options.cwd,
4300
+ ...options.env === void 0 ? {} : { env: {
4301
+ ...process.env,
4302
+ ...options.env
4303
+ } },
4217
4304
  stdio: [
4218
4305
  "ignore",
4219
4306
  "pipe",
@@ -4268,46 +4355,40 @@ function run$1(command, args, options) {
4268
4355
  });
4269
4356
  });
4270
4357
  }
4271
- /** Candidates for the `elan` and `lean` executables: the PATH, then elan's default home. */
4272
- function candidates$1(name) {
4273
- const home = process.env["ELAN_HOME"] ?? join(homedir(), ".elan");
4274
- return [name, join(home, "bin", name)];
4358
+ /** Candidates for a bare `lean`: the PATH, then elan's default home. */
4359
+ function leanCandidates(h) {
4360
+ const home = h.env["ELAN_HOME"] || join(h.home || homedir(), ".elan");
4361
+ return ["lean", join(home, "bin", "lean")];
4275
4362
  }
4276
4363
  /**
4277
- * The pinned toolchain if it is installed: the one `eutaxy prover install
4278
- * lean` put in the cache, when it answers with the pinned version; else
4279
- * through `elan run <toolchain>` when elan is present (and only when it
4280
- * already has the toolchain, so nothing is downloaded); else a bare `lean`
4281
- * of exactly that version.
4364
+ * The pinned toolchain if it is installed: through `elan run <toolchain>`
4365
+ * with the first elan that has it (Eutaxy's own, then the user's), else,
4366
+ * only when no elan answered at all, a bare `lean` of exactly that version.
4367
+ * Nothing is downloaded: an elan is run only for its toolchain list, and
4368
+ * with an elan present a bare `lean` would be its proxy.
4282
4369
  */
4283
- async function findLean(h = host()) {
4284
- let cached;
4285
- const fromCache = installed(leanDownloads, h);
4286
- if (fromCache) {
4287
- const v = await run$1(fromCache.executable, ["--version"], { timeoutMs: 2e4 });
4288
- const m = /Lean \(version ([^,]+),/.exec(v.stdout);
4289
- if (v.code === 0 && m?.[1] === "4.35.0") return {
4290
- command: fromCache.executable,
4291
- args: [],
4292
- version: leanVersion
4293
- };
4294
- cached = `the toolchain in ${fromCache.dir} did not answer as Lean ${leanVersion} (delete it and run: eutaxy prover install lean)`;
4295
- }
4296
- for (const elan of candidates$1("elan")) {
4297
- const list = await run$1(elan, ["toolchain", "list"], { timeoutMs: 2e4 });
4370
+ async function findLean(h = host(), elans = elanCandidates(h), leans = leanCandidates(h)) {
4371
+ let lacking;
4372
+ for (const elan of elans) {
4373
+ const list = await run$1(elan.command, ["toolchain", "list"], {
4374
+ timeoutMs: 2e4,
4375
+ env: elan.env
4376
+ });
4298
4377
  if (list.code !== 0) continue;
4299
- if (!list.stdout.split("\n").some((l) => l.trim().split(" ")[0] === "leanprover/lean4:v4.35.0")) return { unavailable: `elan has no ${leanToolchain}; ${installHint$1}${cached ? `; ${cached}` : ""}` };
4300
- return {
4301
- command: elan,
4378
+ if (list.stdout.split("\n").some((l) => l.trim().split(" ")[0] === "leanprover/lean4:v4.35.0")) return {
4379
+ command: elan.command,
4302
4380
  args: [
4303
4381
  "run",
4304
4382
  leanToolchain,
4305
4383
  "lean"
4306
4384
  ],
4307
- version: leanVersion
4385
+ version: leanVersion,
4386
+ ...elan.env === void 0 ? {} : { env: elan.env }
4308
4387
  };
4388
+ lacking ??= `elan (${elan.command}) has no ${leanToolchain}`;
4309
4389
  }
4310
- for (const lean of candidates$1("lean")) {
4390
+ if (lacking !== void 0) return { unavailable: `${lacking}; ${installHint$1}` };
4391
+ for (const lean of leans) {
4311
4392
  const v = await run$1(lean, ["--version"], { timeoutMs: 2e4 });
4312
4393
  if (v.code !== 0) continue;
4313
4394
  const m = /Lean \(version ([^,]+),/.exec(v.stdout);
@@ -4316,9 +4397,9 @@ async function findLean(h = host()) {
4316
4397
  args: [],
4317
4398
  version: leanVersion
4318
4399
  };
4319
- return { unavailable: `lean ${m?.[1] ?? "of unknown version"} found, but the engine is pinned to ${leanVersion}; ${installHint$1}${cached ? `; ${cached}` : ""}` };
4400
+ return { unavailable: `lean ${m?.[1] ?? "of unknown version"} found, but the engine is pinned to ${leanVersion}; ${installHint$1}` };
4320
4401
  }
4321
- return { unavailable: `no Lean toolchain found; ${installHint$1}${cached ? `; ${cached}` : ""}` };
4402
+ return { unavailable: `no Lean toolchain found; ${installHint$1}` };
4322
4403
  }
4323
4404
  /** Parse Lean's diagnostics for the one file it was given. */
4324
4405
  /**
@@ -4360,7 +4441,8 @@ async function checkLean(toolchain, source, options = {}) {
4360
4441
  "Eutaxy.lean"
4361
4442
  ], {
4362
4443
  cwd: dir,
4363
- timeoutMs: options.timeoutMs ?? 12e4
4444
+ timeoutMs: options.timeoutMs ?? 12e4,
4445
+ env: toolchain.env
4364
4446
  });
4365
4447
  return {
4366
4448
  run: result,
@@ -5665,28 +5747,44 @@ const z3Version = "5.3.2";
5665
5747
  /** How to put the pinned solver on this machine. */
5666
5748
  const installHint = `run: eutaxy prover install smt (or put Z3 ${z3Version} on the PATH, from https://github.com/Z3Prover/z3/releases/tag/z3-${z3Version} or Homebrew: brew install z3)`;
5667
5749
  const z3Release = `https://github.com/Z3Prover/z3/releases/download/z3-${z3Version}`;
5668
- const z3File = (name, sha256, bytes) => ({
5750
+ /** The files the solver needs on Linux and macOS: the executable, which links only system libraries. */
5751
+ const unixFiles = ["bin/z3"];
5752
+ /**
5753
+ * On Windows the executable also needs the Visual C++ runtime, which a fresh
5754
+ * Windows may lack; the release ships it beside `z3.exe`, and Windows loads
5755
+ * a DLL from the executable's own directory first.
5756
+ */
5757
+ const windowsFiles = [
5758
+ "bin/z3.exe",
5759
+ "bin/msvcp140.dll",
5760
+ "bin/vcruntime140.dll",
5761
+ "bin/vcruntime140_1.dll"
5762
+ ];
5763
+ const z3File = (name, sha256, bytes, files) => ({
5669
5764
  file: name,
5670
5765
  url: `${z3Release}/${name}`,
5671
5766
  sha256,
5672
- bytes
5767
+ bytes,
5768
+ entries: Object.fromEntries(files.map((f) => [`${name.replace(/\.zip$/, "")}/${f}`, f]))
5673
5769
  });
5674
5770
  /**
5675
5771
  * The upstream release files `eutaxy prover install smt` downloads, one per
5676
5772
  * platform, as published on Z3's GitHub release with the checksums it
5677
- * reports; the file names carry the version, and a test holds them to
5678
- * `z3Version`. The Linux builds need glibc 2.39 (x64) or 2.38 (arm64).
5773
+ * reports, and the files taken from each (the rest of the zip, bindings for
5774
+ * other languages, headers and the shared library, is not unpacked); the
5775
+ * file names carry the version, and a test holds them to `z3Version`. The
5776
+ * Linux builds need glibc 2.39 (x64) or 2.38 (arm64).
5679
5777
  */
5680
5778
  const z3Downloads = {
5681
5779
  name: "smt",
5682
5780
  version: z3Version,
5683
5781
  executable: "bin/z3",
5684
5782
  files: {
5685
- "linux-x64": z3File("z3-5.3.2-x64-glibc-2.39.zip", "26d463cddad3901cbf86e3868c784914539f4e3f9b4de1a0b8dc2969806d60e2", 69479256),
5686
- "linux-arm64": z3File("z3-5.3.2-arm64-glibc-2.38.zip", "30b6a718a6cfe1b2db056038cc32eda5410f6d02e5937622b5238645347f59d5", 64803341),
5687
- "darwin-x64": z3File("z3-5.3.2-x64-osx-13.3.zip", "b911dc193f7447a14fba001e8e8a0c2866a544274bb003e76a9e864f03b4d557", 54270076),
5688
- "darwin-arm64": z3File("z3-5.3.2-arm64-osx-13.3.zip", "524290057c943a044ec3d1372db65a9c93f333d9817d58191154c4719ff7f8ad", 53576249),
5689
- "win32-x64": z3File("z3-5.3.2-x64-win.zip", "a75aa2b0383a8ee355387a54daad796911d6a965076751eea18d21a27f38e983", 70867398)
5783
+ "linux-x64": z3File("z3-5.3.2-x64-glibc-2.39.zip", "26d463cddad3901cbf86e3868c784914539f4e3f9b4de1a0b8dc2969806d60e2", 69479256, unixFiles),
5784
+ "linux-arm64": z3File("z3-5.3.2-arm64-glibc-2.38.zip", "30b6a718a6cfe1b2db056038cc32eda5410f6d02e5937622b5238645347f59d5", 64803341, unixFiles),
5785
+ "darwin-x64": z3File("z3-5.3.2-x64-osx-13.3.zip", "b911dc193f7447a14fba001e8e8a0c2866a544274bb003e76a9e864f03b4d557", 54270076, unixFiles),
5786
+ "darwin-arm64": z3File("z3-5.3.2-arm64-osx-13.3.zip", "524290057c943a044ec3d1372db65a9c93f333d9817d58191154c4719ff7f8ad", 53576249, unixFiles),
5787
+ "win32-x64": z3File("z3-5.3.2-x64-win.zip", "a75aa2b0383a8ee355387a54daad796911d6a965076751eea18d21a27f38e983", 70867398, windowsFiles)
5690
5788
  }
5691
5789
  };
5692
5790
  function run(command, args, options) {
@@ -6616,6 +6714,153 @@ const noIsolate = {
6616
6714
  function describeCallee(c, scenarioDir) {
6617
6715
  return `${c.binding} (${c.name}, ${toPosix$1(relative(scenarioDir, c.entry))})`;
6618
6716
  }
6717
+ // packages/cli/src/vitest-failure.ts
6718
+ /**
6719
+ * Why Vitest failed the run a check started, from what that run left: its
6720
+ * JSON report (a test file that could not run, a failed test) and the
6721
+ * errors nothing handled, which fail a run without being in that report,
6722
+ * so the generated config's own reporter writes them beside it
6723
+ * (`unhandledErrorsFile`). Without this the command could only say that
6724
+ * Vitest exited non-zero: the run's only reporter is the JSON one, and its
6725
+ * files are deleted after the run.
6726
+ */
6727
+ /** Where the run's errors nothing handled are written: beside its report, under its stamp. */
6728
+ function unhandledErrorsFile(reportFile) {
6729
+ return reportFile.replace(/\.json$/, ".unhandled.json");
6730
+ }
6731
+ /** Lines of an error kept in the explanation; a stack's first frames say where. */
6732
+ const keptLines = 8;
6733
+ function parsed(text) {
6734
+ if (text === void 0) return void 0;
6735
+ try {
6736
+ return JSON.parse(text);
6737
+ } catch {
6738
+ return;
6739
+ }
6740
+ }
6741
+ /** A field as text: a string as it is, anything else as JSON (a thrown value need not be an error). */
6742
+ function asText(value) {
6743
+ if (typeof value === "string") return value;
6744
+ try {
6745
+ return JSON.stringify(value) ?? String(value);
6746
+ } catch {
6747
+ return String(value);
6748
+ }
6749
+ }
6750
+ /** What an error says: its stack or message when either is text, else whatever was thrown, as data. */
6751
+ function said(e) {
6752
+ for (const v of [e.stack, e.message]) if (typeof v === "string" && v !== "") return v;
6753
+ const thrown = e.message ?? e.stack;
6754
+ return thrown === void 0 || thrown === null ? "(no message)" : asText(thrown);
6755
+ }
6756
+ /** An error's first lines, each without its indent; a line at the end says how many were cut. */
6757
+ function firstLines(text) {
6758
+ const lines = text.trimEnd().split("\n").map((l) => l.trimStart());
6759
+ const kept = lines.slice(0, keptLines);
6760
+ if (lines.length > keptLines) kept.push(`… ${lines.length - keptLines} more lines`);
6761
+ return kept;
6762
+ }
6763
+ /** An error's text, cut to its first lines and indented under its heading. */
6764
+ function cut(text) {
6765
+ return firstLines(text).join("\n ");
6766
+ }
6767
+ /** The errors nothing handled, the same type and text told once with how often it came, in first-seen order. */
6768
+ function distinct(unhandled) {
6769
+ const seen = /* @__PURE__ */ new Map();
6770
+ for (const e of unhandled) {
6771
+ const type = typeof e.type === "string" && e.type !== "" ? e.type : "Error";
6772
+ const whole = said(e);
6773
+ const key = `${type}\n${whole}`;
6774
+ const found = seen.get(key);
6775
+ if (found) found.times++;
6776
+ else seen.set(key, {
6777
+ type,
6778
+ message: firstLines(whole).join("\n"),
6779
+ times: 1
6780
+ });
6781
+ }
6782
+ return [...seen.values()];
6783
+ }
6784
+ /** The distinct errors, one a line under the count, each error's own lines indented under it. */
6785
+ function told(errors) {
6786
+ return errors.map(({ type, message, times }) => `\n ${type}${times > 1 ? ` (${times} times)` : ""}: ${message.split("\n").join("\n ")}`).join("");
6787
+ }
6788
+ /** How many errors came, and how many distinct when more than one. */
6789
+ function counted(errors) {
6790
+ const all = errors.reduce((n, e) => n + e.times, 0);
6791
+ return all === 1 ? "1 error nothing handled" : `${all} errors nothing handled, ${errors.length} distinct`;
6792
+ }
6793
+ /** Why each test file failed and each failed test's first error, and how many tests passed. */
6794
+ function reportCauses(report) {
6795
+ const causes = [];
6796
+ let passed = 0;
6797
+ for (const file of report?.testResults ?? []) {
6798
+ const tests = file.assertionResults ?? [];
6799
+ if (file.status === "failed" && file.message !== void 0 && file.message !== "") causes.push(`the check's test file ${tests.length === 0 ? "could not run" : "failed outside its test"}: ${cut(asText(file.message))}`);
6800
+ for (const t of tests) if (t.status === "passed") passed++;
6801
+ else if (t.status === "failed") {
6802
+ const [first] = t.failureMessages ?? [];
6803
+ causes.push(`the check's test failed${first === void 0 ? "" : `: ${cut(asText(first))}`}`);
6804
+ }
6805
+ }
6806
+ return {
6807
+ causes,
6808
+ passed
6809
+ };
6810
+ }
6811
+ /**
6812
+ * The kinds of error nothing handled that Vitest's error catcher in the
6813
+ * test's own runtime records (`listenForErrors`): what code that ran
6814
+ * inside the test left behind, the Worker's or the simulation's. The
6815
+ * runner, its pool and the reporters record their own failures through the
6816
+ * same channel (`Teardown Error`, `Unhandled Error`, `Unhandled Reporter
6817
+ * Error`, `Restart Error`, …); those mean the run broke.
6818
+ */
6819
+ const fromTheTest = /* @__PURE__ */ new Set(["Unhandled Rejection", "Uncaught Exception"]);
6820
+ /**
6821
+ * The errors nothing handled, when they are the run's only fault: every
6822
+ * test in the report passed, at least one did, no file failed outside its
6823
+ * tests, and there was at least one such error, every one recorded by the
6824
+ * test's own runtime (`fromTheTest`). Cloudflare's runtime only
6825
+ * logs an error nothing handled (a promise a Worker leaves rejected, say),
6826
+ * while Vitest fails the whole run on one, so then the verdict the test
6827
+ * left stands and these are told beside it. Otherwise undefined: the run
6828
+ * failed, and `vitestFailure` says why.
6829
+ */
6830
+ function strayErrors(left) {
6831
+ const report = parsed(left.report);
6832
+ const unhandled = parsed(left.unhandled);
6833
+ if (report === void 0 || !Array.isArray(unhandled) || unhandled.length === 0) return void 0;
6834
+ if (!unhandled.every((e) => typeof e?.type === "string" && fromTheTest.has(e.type))) return void 0;
6835
+ const { causes, passed } = reportCauses(report);
6836
+ const allPassed = (report.testResults ?? []).every((f) => f.status === "passed" && (f.assertionResults ?? []).every((t) => t.status === "passed"));
6837
+ return passed > 0 && causes.length === 0 && allPassed ? distinct(unhandled) : void 0;
6838
+ }
6839
+ /** The note printed beside a verdict that stands despite errors nothing handled. */
6840
+ function strayNote(errors) {
6841
+ return `note: the check's test passed, and its verdict stands, but there ${errors.reduce((n, e) => n + e.times, 0) === 1 ? "was" : "were"} ${counted(errors)} (Cloudflare's runtime only logs them; Vitest fails the run on them):${told(errors)}\n`;
6842
+ }
6843
+ /**
6844
+ * The explanation, one cause a line (each error's own lines indented under
6845
+ * it), from the report's text and the unhandled errors' text, either of
6846
+ * which may be missing.
6847
+ */
6848
+ function vitestFailure(left) {
6849
+ const report = parsed(left.report);
6850
+ const unhandled = parsed(left.unhandled) ?? [];
6851
+ const { causes, passed } = reportCauses(report);
6852
+ if (unhandled.length > 0) {
6853
+ const errors = distinct(unhandled);
6854
+ const passedAlone = passed > 0 && causes.length === 0;
6855
+ const onlyFromTheTest = unhandled.every((e) => typeof e?.type === "string" && fromTheTest.has(e.type));
6856
+ const intro = !passedAlone ? "" : onlyFromTheTest ? "its test passed but left no verdict in Vitest's report; there " : "its test passed, but Vitest fails a run on any error nothing handled, and there ";
6857
+ const also = passedAlone && onlyFromTheTest ? "also " : "";
6858
+ const verb = intro === "" ? "" : `${unhandled.length === 1 ? "was" : "were"} ${also}`;
6859
+ causes.push(`${intro}${verb}${counted(errors)}:${told(errors)}`);
6860
+ }
6861
+ if (causes.length === 0) causes.push(report === void 0 ? "Vitest left no report it could be told from" : passed > 0 ? "its test passed but left no verdict in Vitest's report" : "Vitest reported no failed test and no error nothing handled");
6862
+ return causes.map((c) => ` ${c}\n`).join("");
6863
+ }
6619
6864
  // packages/cli/src/generate.ts
6620
6865
  /**
6621
6866
  * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before
@@ -6662,6 +6907,7 @@ test("eutaxy check", async ({ task }) => {
6662
6907
  function vitestConfigSource(wranglerConfigPath, testPath, outputFile, isolate) {
6663
6908
  const plugin = isolate === void 0 ? `cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })` : `cloudflareTest({ main: ${JSON.stringify(isolate.main)}, wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} }${isolate.miniflare === void 0 ? "" : `, miniflare: ${isolate.miniflare}`} })`;
6664
6909
  return `// Generated by eutaxy check; deleted after the run.
6910
+ import { writeFileSync } from "node:fs";
6665
6911
  import { cloudflareTest } from "@cloudflare/vitest-plugin";
6666
6912
  import { defineConfig } from "vitest/config";
6667
6913
 
@@ -6673,7 +6919,11 @@ ${isolate?.miniflare === void 0 ? "" : `const ${neverCalled} = () => new Respons
6673
6919
  test: {
6674
6920
  include: [${JSON.stringify(testPath)}],
6675
6921
  testTimeout: 600_000,
6676
- reporters: ["json"],
6922
+ // An error nothing handled fails the run but is not in the JSON report; kept for the command to tell.
6923
+ reporters: ["json", { onTestRunEnd(_modules, errors) {
6924
+ if (errors.length > 0)
6925
+ writeFileSync(${JSON.stringify(unhandledErrorsFile(outputFile))}, JSON.stringify(errors.map((e) => ({ type: e.type, message: e.message, stack: e.stack }))));
6926
+ } }],
6677
6927
  outputFile: ${JSON.stringify(outputFile)},
6678
6928
  },
6679
6929
  });
@@ -6980,11 +7230,19 @@ async function runCheck(o) {
6980
7230
  ...callerServices.length > 0 ? { miniflare: miniflareOptionsSource([], void 0, callerServices) } : {}
6981
7231
  } : void 0));
6982
7232
  const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
6983
- const transport = code === 0 ? readTransport(reportPath) : null;
7233
+ const left = (path) => existsSync(path) ? readFileSync(path, "utf8") : void 0;
7234
+ const ran = {
7235
+ report: left(reportPath),
7236
+ unhandled: left(unhandledErrorsFile(reportPath))
7237
+ };
7238
+ const stray = code === 0 ? void 0 : strayErrors(ran);
7239
+ const transport = code === 0 || stray !== void 0 ? readTransport(reportPath) : null;
6984
7240
  if (!transport) {
6985
- o.stderr(`eutaxy check could not read a verdict from Vitest (exit ${code}):\n${output}\n`);
7241
+ const why = vitestFailure(ran);
7242
+ o.stderr(`eutaxy check could not read a verdict from Vitest (exit ${code}):\n${why}Vitest's output:\n${output}\n`);
6986
7243
  return exitCodes.error;
6987
7244
  }
7245
+ if (stray !== void 0) o.stderr(strayNote(stray));
6988
7246
  if (transport.specErrors && transport.specErrors.length > 0) {
6989
7247
  for (const e of transport.specErrors) o.stderr(`${e.module}${e.line > 0 ? `:${e.line}` : ""}: ${e.message}\n`);
6990
7248
  return exitCodes.error;
@@ -7000,11 +7258,12 @@ async function runCheck(o) {
7000
7258
  }
7001
7259
  specs = await proveSpecs(dir, transport.observed ?? [], specs, named.engines, specModules);
7002
7260
  }
7003
- const regressionPath = verdict.kind === "VIOLATED" && !o.noRegression ? o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`) : void 0;
7261
+ const regressionPath = (verdict.kind === "VIOLATED" || verdict.kind === "UNSUPPORTED" && verdict.cause === "unsupported_api" && verdict.replay !== void 0) && !o.noRegression ? o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`) : void 0;
7004
7262
  const printed = {
7005
7263
  ...transport.report,
7006
7264
  ...o.provers && o.provers.length > 0 ? { specs } : {},
7007
- ...regressionPath === void 0 ? {} : { regressionTest: toPosix(relative(o.cwd, regressionPath) || regressionPath) }
7265
+ ...regressionPath === void 0 ? {} : { regressionTest: toPosix(relative(o.cwd, regressionPath) || regressionPath) },
7266
+ ...stray === void 0 ? {} : { unhandledErrors: stray }
7008
7267
  };
7009
7268
  if (o.json) o.stdout(`${canonicalJson(printed)}\n`);
7010
7269
  else o.stdout(`${renderText(verdict)}\n${specs.length > 0 ? `\n${renderSpecs(specs)}\n` : ""}`);
@@ -7028,7 +7287,7 @@ async function runCheck(o) {
7028
7287
  path: toPosix(relative(outDir, resolve(dir, String(step["entry"]))))
7029
7288
  };
7030
7289
  }
7031
- const source = cloudflareRegressionTest(verdict, {
7290
+ const testOptions = {
7032
7291
  scenarioPath: toPosix(relative(outDir, scenarioPath)),
7033
7292
  workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),
7034
7293
  schemaPaths,
@@ -7045,10 +7304,11 @@ async function runCheck(o) {
7045
7304
  path: toPosix(relative(outDir, resolve(dir, m.module))),
7046
7305
  functions: m.functions
7047
7306
  })) } : {}
7048
- });
7307
+ };
7308
+ const source = verdict.kind === "UNSUPPORTED" ? cloudflareUnsupportedTest(verdict, testOptions) : cloudflareRegressionTest(verdict, testOptions);
7049
7309
  mkdirSync(outDir, { recursive: true });
7050
7310
  writeFileSync(outPath, source);
7051
- if (!o.json) o.stdout(`\nRegression test written to ${relative(o.cwd, outPath) || outPath}\n`);
7311
+ if (!o.json) o.stdout(`\n${verdict.kind === "UNSUPPORTED" ? "Test replaying the run" : "Regression test"} written to ${relative(o.cwd, outPath) || outPath}\n`);
7052
7312
  }
7053
7313
  if (verdict.kind !== "VIOLATED" && specs.some((v) => v.kind === "REFUTED" || v.kind === "CONFLICT")) return exitCodes.VIOLATED;
7054
7314
  return exitCodes[verdict.kind];
@@ -7532,222 +7792,41 @@ function runDraft(o) {
7532
7792
  }
7533
7793
  // packages/cli/src/archive.ts
7534
7794
  /**
7535
- * Reading the two archive formats the prover releases come in, with Node's
7536
- * standard library alone: a tar stream compressed with zstd (Lean) and a zip
7537
- * (Z3). Entries are written under one destination directory; an entry whose
7538
- * path would leave it, or a link pointing out of it, is refused, since the
7539
- * archive is downloaded. The tar is read as it decompresses, so a release
7540
- * of hundreds of megabytes never sits in memory; a zip is read from its
7541
- * central directory, entry by entry.
7795
+ * Reading the two archive formats the release files come in, with Node's
7796
+ * standard library alone: a zip (Z3; elan's installer on Windows) and a
7797
+ * gzip-compressed tar (elan's installer elsewhere). From either, only the
7798
+ * files the caller names are taken, each to the path the caller gives: the
7799
+ * archive chooses no path and makes no link, so nothing in it can write
7800
+ * anywhere else. A named entry that is missing, there twice, a link or a
7801
+ * directory, or whose data does not match what its headers say, is refused,
7802
+ * and nothing is written until every named entry has been read.
7542
7803
  */
7543
7804
  var ArchiveError = class extends Error {};
7544
- /** The entry's place under `dest`, refused when it would be outside. */
7545
- function placeOf(dest, name) {
7546
- if (name.includes("\0")) throw new ArchiveError("an entry name holds a NUL byte");
7547
- const target = resolve(dest, name);
7548
- if (target !== dest && !target.startsWith(dest + sep)) throw new ArchiveError(`entry ${JSON.stringify(name)} would be written outside the toolchain directory`);
7549
- return target;
7550
- }
7551
- /** A symlink's target must stay under `dest` too. */
7552
- function checkLink(dest, at, linkTo) {
7553
- const target = resolve(dirname(at), linkTo);
7554
- if (target !== dest && !target.startsWith(dest + sep)) throw new ArchiveError(`link ${JSON.stringify(linkTo)} would point outside the toolchain directory`);
7555
- }
7556
- function ensureDir(dir) {
7557
- mkdirSync(dir, { recursive: true });
7558
- }
7559
- function setMode(path, mode) {
7560
- if (process.platform === "win32") return;
7561
- const bits = mode & 511;
7562
- if (bits !== 0) chmodSync(path, bits | 384);
7563
- }
7564
- const text = (block, start, length) => {
7565
- const slice = block.subarray(start, start + length);
7566
- const end = slice.indexOf(0);
7567
- return slice.subarray(0, end < 0 ? slice.length : end).toString("utf8");
7568
- };
7569
- /** An octal field, or GNU base-256 when the high bit of the first byte is set. */
7570
- const numeric = (block, start, length) => {
7571
- if (block[start] & 128) {
7572
- let n = 0;
7573
- for (let i = start + 1; i < start + length; i++) n = n * 256 + block[i];
7574
- return n;
7575
- }
7576
- const t = text(block, start, length).trim();
7577
- return t.length === 0 ? 0 : Number.parseInt(t, 8);
7578
- };
7579
- function parseHeader(block) {
7580
- const magic = text(block, 257, 6);
7581
- const name = text(block, 0, 100);
7582
- const prefix = magic.startsWith("ustar") ? text(block, 345, 155) : "";
7583
- return {
7584
- name: prefix.length > 0 ? `${prefix}/${name}` : name,
7585
- mode: numeric(block, 100, 8),
7586
- size: numeric(block, 124, 12),
7587
- type: block[156] === 0 ? "0" : String.fromCharCode(block[156]),
7588
- linkName: text(block, 157, 100)
7589
- };
7590
- }
7591
- /** `length key=value\n` records of a pax extended header. */
7592
- function paxRecords(data) {
7593
- const out = /* @__PURE__ */ new Map();
7594
- let at = 0;
7595
- while (at < data.length) {
7596
- const space = data.indexOf(32, at);
7597
- if (space < 0) break;
7598
- const length = Number.parseInt(data.subarray(at, space).toString("latin1"), 10);
7599
- if (!Number.isInteger(length) || length <= 0) break;
7600
- const record = data.subarray(space + 1, at + length - 1).toString("utf8");
7601
- const eq = record.indexOf("=");
7602
- if (eq > 0) out.set(record.slice(0, eq), record.slice(eq + 1));
7603
- at += length;
7805
+ const inside = (dest, path) => path === dest || path.startsWith(dest + sep);
7806
+ /** Each named entry's place under `dest`, checked before the archive is read. */
7807
+ function placesOf(entries, dest) {
7808
+ const root = resolve(dest);
7809
+ const places = /* @__PURE__ */ new Map();
7810
+ for (const [name, to] of Object.entries(entries)) {
7811
+ const place = resolve(root, to);
7812
+ if (place === root || !inside(root, place)) throw new ArchiveError(`${JSON.stringify(to)} is not a path under the toolchain directory`);
7813
+ places.set(name, place);
7604
7814
  }
7605
- return out;
7815
+ return places;
7606
7816
  }
7607
7817
  /**
7608
- * Reads a tar stream block by block as its chunks arrive. A file entry's
7609
- * bytes are written to disk as they come; pax and GNU long-name entries are
7610
- * read into memory (they are small) and apply to the entry that follows.
7818
+ * Write what was read, once every named entry has been: files with mode
7819
+ * 0644 (the caller makes its executable runnable). Returns how many.
7611
7820
  */
7612
- var TarReader = class {
7613
- dest;
7614
- buffer = Buffer.alloc(0);
7615
- current;
7616
- /** Overrides for the next entry from a pax or long-name entry. */
7617
- next = {};
7618
- zeroBlocks = 0;
7619
- ended = false;
7620
- entries = 0;
7621
- constructor(dest) {
7622
- this.dest = dest;
7623
- }
7624
- push(chunk) {
7625
- this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk]);
7626
- for (;;) {
7627
- if (this.ended) return;
7628
- if (this.current) {
7629
- const take = Math.min(this.current.remaining, this.buffer.length);
7630
- if (take > 0) {
7631
- const part = this.buffer.subarray(0, take);
7632
- if ("fd" in this.current.sink) writeSync(this.current.sink.fd, part);
7633
- else if ("chunks" in this.current.sink) this.current.sink.chunks.push(Buffer.from(part));
7634
- this.buffer = this.buffer.subarray(take);
7635
- this.current.remaining -= take;
7636
- }
7637
- if (this.current.remaining > 0) return;
7638
- const skip = Math.min(this.current.padding, this.buffer.length);
7639
- this.buffer = this.buffer.subarray(skip);
7640
- this.current.padding -= skip;
7641
- if (this.current.padding > 0) return;
7642
- this.finish();
7643
- continue;
7644
- }
7645
- if (this.buffer.length < 512) return;
7646
- const block = this.buffer.subarray(0, 512);
7647
- this.buffer = this.buffer.subarray(512);
7648
- if (block.every((b) => b === 0)) {
7649
- if (++this.zeroBlocks >= 2) this.ended = true;
7650
- continue;
7651
- }
7652
- this.zeroBlocks = 0;
7653
- this.begin(parseHeader(block));
7654
- }
7655
- }
7656
- begin(header) {
7657
- const size = this.next.size ?? header.size;
7658
- const padding = (512 - size % 512) % 512;
7659
- if (header.type === "x" || header.type === "L") {
7660
- const kind = header.type === "x" ? "pax" : "longname";
7661
- this.current = {
7662
- remaining: size,
7663
- padding,
7664
- sink: {
7665
- chunks: [],
7666
- kind
7667
- }
7668
- };
7669
- return;
7670
- }
7671
- const name = this.next.path ?? header.name;
7672
- const linkName = this.next.linkpath ?? header.linkName;
7673
- this.next = {};
7674
- this.entries++;
7675
- const at = placeOf(this.dest, name);
7676
- if (header.type === "0" || header.type === "7") {
7677
- ensureDir(dirname(at));
7678
- const fd = openSync(at, "w");
7679
- this.current = {
7680
- remaining: size,
7681
- padding,
7682
- sink: {
7683
- fd,
7684
- at,
7685
- mode: header.mode
7686
- }
7687
- };
7688
- if (size === 0) this.finish();
7689
- return;
7690
- }
7691
- if (header.type === "5") ensureDir(at);
7692
- else if (header.type === "2") {
7693
- checkLink(this.dest, at, linkName);
7694
- ensureDir(dirname(at));
7695
- rmSync(at, { force: true });
7696
- symlinkSync(linkName, at);
7697
- } else if (header.type === "1") {
7698
- ensureDir(dirname(at));
7699
- copyFileSync(placeOf(this.dest, linkName), at);
7700
- }
7701
- if (size > 0) this.current = {
7702
- remaining: size,
7703
- padding,
7704
- sink: { skip: true }
7705
- };
7706
- }
7707
- finish() {
7708
- const current = this.current;
7709
- this.current = void 0;
7710
- if ("fd" in current.sink) {
7711
- closeSync(current.sink.fd);
7712
- setMode(current.sink.at, current.sink.mode);
7713
- return;
7714
- }
7715
- if (!("chunks" in current.sink)) return;
7716
- const data = Buffer.concat(current.sink.chunks);
7717
- if (current.sink.kind === "longname") {
7718
- this.next.path = text(data, 0, data.length);
7719
- return;
7720
- }
7721
- const records = paxRecords(data);
7722
- const path = records.get("path");
7723
- const linkpath = records.get("linkpath");
7724
- const size = records.get("size");
7725
- if (path !== void 0) this.next.path = path;
7726
- if (linkpath !== void 0) this.next.linkpath = linkpath;
7727
- if (size !== void 0) this.next.size = Number(size);
7728
- }
7729
- /** Close the file being written, if any. */
7730
- release() {
7731
- if (this.current && "fd" in this.current.sink) closeSync(this.current.sink.fd);
7732
- }
7733
- end() {
7734
- this.release();
7735
- if (this.current) throw new ArchiveError("the tar stream ended inside an entry; the file is truncated");
7736
- }
7737
- };
7738
- /** Unpack a zstd-compressed tar into `dest`, which must exist and be empty. */
7739
- async function extractTarZst(file, dest) {
7740
- const reader = new TarReader(resolve(dest));
7741
- const source = createReadStream(file).pipe(createZstdDecompress());
7742
- try {
7743
- for await (const chunk of source) reader.push(chunk);
7744
- } catch (err) {
7745
- reader.release();
7746
- source.destroy();
7747
- throw err;
7821
+ function writeFound(kind, places, found) {
7822
+ const missing = [...places.keys()].filter((name) => !found.has(name));
7823
+ if (missing.length > 0) throw new ArchiveError(`the ${kind} holds no ${missing.map((m) => JSON.stringify(m)).join(", ")}`);
7824
+ for (const [name, data] of found) {
7825
+ const place = places.get(name);
7826
+ mkdirSync(dirname(place), { recursive: true });
7827
+ writeFileSync(place, data, { mode: 420 });
7748
7828
  }
7749
- reader.end();
7750
- return reader.entries;
7829
+ return found.size;
7751
7830
  }
7752
7831
  const ZIP_EOCD = 101010256;
7753
7832
  const ZIP64_EOCD = 101075792;
@@ -7769,7 +7848,7 @@ function centralDirectory(zip) {
7769
7848
  const locator = eocd - 20;
7770
7849
  if (locator < 0 || zip.readUInt32LE(locator) !== ZIP64_LOCATOR) throw new ArchiveError("zip64 archive without its locator");
7771
7850
  const at = Number(zip.readBigUInt64LE(locator + 8));
7772
- if (zip.readUInt32LE(at) !== ZIP64_EOCD) throw new ArchiveError("zip64 archive without its end record");
7851
+ if (at + 56 > zip.length || zip.readUInt32LE(at) !== ZIP64_EOCD) throw new ArchiveError("zip64 archive without its end record");
7773
7852
  entries = Number(zip.readBigUInt64LE(at + 32));
7774
7853
  offset = Number(zip.readBigUInt64LE(at + 48));
7775
7854
  }
@@ -7784,34 +7863,46 @@ function zip64Fields(extra, plain) {
7784
7863
  while (at + 4 <= extra.length) {
7785
7864
  const id = extra.readUInt16LE(at);
7786
7865
  const size = extra.readUInt16LE(at + 2);
7866
+ const end = at + 4 + size;
7867
+ if (end > extra.length) throw new ArchiveError("an entry's extra field is cut short");
7787
7868
  if (id === 1) {
7788
7869
  let p = at + 4;
7789
- const out = { ...plain };
7790
- if (out.uncompressed === 4294967295) {
7791
- out.uncompressed = Number(extra.readBigUInt64LE(p));
7792
- p += 8;
7793
- }
7794
- if (out.compressed === 4294967295) {
7795
- out.compressed = Number(extra.readBigUInt64LE(p));
7870
+ const next = () => {
7871
+ if (p + 8 > end) throw new ArchiveError("an entry's zip64 field is cut short");
7872
+ const value = Number(extra.readBigUInt64LE(p));
7796
7873
  p += 8;
7797
- }
7798
- if (out.offset === 4294967295) out.offset = Number(extra.readBigUInt64LE(p));
7874
+ return value;
7875
+ };
7876
+ const out = { ...plain };
7877
+ if (out.uncompressed === 4294967295) out.uncompressed = next();
7878
+ if (out.compressed === 4294967295) out.compressed = next();
7879
+ if (out.offset === 4294967295) out.offset = next();
7799
7880
  return out;
7800
7881
  }
7801
7882
  at += 4 + size;
7802
7883
  }
7803
7884
  return plain;
7804
7885
  }
7805
- /** Unpack a zip into `dest`, which must exist and be empty. */
7806
- function extractZip(file, dest) {
7807
- const root = resolve(dest);
7886
+ /**
7887
+ * Take the named files of a zip, and nothing else: `entries` maps each
7888
+ * file's path in the archive to the path under `dest` it is written to.
7889
+ * Every named entry must be there exactly once, must be a plain file
7890
+ * (a directory or a link is refused), and must inflate to its declared
7891
+ * size and CRC-32; nothing is written until all of them have. Files are
7892
+ * written with mode 0644 (the caller makes its executable runnable).
7893
+ * Returns how many files were written.
7894
+ */
7895
+ function extractZipEntries(file, entries, dest) {
7896
+ const places = placesOf(entries, dest);
7808
7897
  const zip = readFileSync(file);
7809
- const { offset, entries } = centralDirectory(zip);
7898
+ const { offset, entries: count } = centralDirectory(zip);
7899
+ const found = /* @__PURE__ */ new Map();
7810
7900
  let at = offset;
7811
- for (let i = 0; i < entries; i++) {
7812
- if (zip.readUInt32LE(at) !== ZIP_CENTRAL) throw new ArchiveError("a central directory entry is not where the zip says it is");
7901
+ for (let i = 0; i < count; i++) {
7902
+ if (at + 46 > zip.length || zip.readUInt32LE(at) !== ZIP_CENTRAL) throw new ArchiveError("a central directory entry is not where the zip says it is");
7813
7903
  const madeBy = zip.readUInt16LE(at + 4) >> 8;
7814
7904
  const method = zip.readUInt16LE(at + 10);
7905
+ const crc = zip.readUInt32LE(at + 16);
7815
7906
  const nameLength = zip.readUInt16LE(at + 28);
7816
7907
  const extraLength = zip.readUInt16LE(at + 30);
7817
7908
  const commentLength = zip.readUInt16LE(at + 32);
@@ -7823,68 +7914,149 @@ function extractZip(file, dest) {
7823
7914
  offset: zip.readUInt32LE(at + 42)
7824
7915
  });
7825
7916
  at += 46 + nameLength + extraLength + commentLength;
7917
+ if (!places.has(name)) continue;
7918
+ const quoted = JSON.stringify(name);
7919
+ if (found.has(name)) throw new ArchiveError(`entry ${quoted} is in the zip twice`);
7920
+ const type = (madeBy === 3 ? externalAttributes >>> 16 : 0) & 61440;
7921
+ if (name.endsWith("/") || type === 16384) throw new ArchiveError(`entry ${quoted} is a directory, not a file`);
7922
+ if (type === 40960) throw new ArchiveError(`entry ${quoted} is a link, not a file`);
7826
7923
  const local = sizes.offset;
7827
- if (zip.readUInt32LE(local) !== ZIP_LOCAL) throw new ArchiveError(`entry ${JSON.stringify(name)} has no local header where the zip says`);
7924
+ if (local + 30 > zip.length || zip.readUInt32LE(local) !== ZIP_LOCAL) throw new ArchiveError(`entry ${quoted} has no local header where the zip says`);
7828
7925
  const dataStart = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);
7829
7926
  const raw = zip.subarray(dataStart, dataStart + sizes.compressed);
7830
- const mode = madeBy === 3 ? externalAttributes >>> 16 : 0;
7831
- const place = placeOf(root, name);
7832
- if (name.endsWith("/") || (mode & 61440) === 16384) {
7833
- ensureDir(place);
7834
- continue;
7835
- }
7836
7927
  let data;
7837
7928
  if (method === 0) data = raw;
7838
- else if (method === 8) data = inflateRawSync(raw);
7839
- else throw new ArchiveError(`entry ${JSON.stringify(name)} uses compression method ${method}; only stored and deflated entries are read`);
7840
- if (data.length !== sizes.uncompressed) throw new ArchiveError(`entry ${JSON.stringify(name)} did not inflate to its declared size`);
7841
- ensureDir(dirname(place));
7842
- if ((mode & 61440) === 40960) {
7843
- const linkTo = data.toString("utf8");
7844
- checkLink(root, place, linkTo);
7845
- rmSync(place, { force: true });
7846
- symlinkSync(linkTo, place);
7847
- continue;
7929
+ else if (method === 8) try {
7930
+ data = inflateRawSync(raw, { maxOutputLength: Math.max(1, sizes.uncompressed) });
7931
+ } catch (err) {
7932
+ throw new ArchiveError(`entry ${quoted} did not inflate within its declared size: ${err instanceof Error ? err.message : String(err)}`);
7848
7933
  }
7849
- writeFileSync(place, data);
7850
- setMode(place, mode);
7934
+ else throw new ArchiveError(`entry ${quoted} uses compression method ${method}; only stored and deflated entries are read`);
7935
+ if (data.length !== sizes.uncompressed) throw new ArchiveError(`entry ${quoted} did not inflate to its declared size`);
7936
+ if (crc32(data) !== crc) throw new ArchiveError(`entry ${quoted} fails its CRC-32 check`);
7937
+ found.set(name, data);
7851
7938
  }
7852
- return entries;
7939
+ return writeFound("zip", places, found);
7940
+ }
7941
+ /** The largest tar a release's installer comes in, uncompressed; elan's is 6 to 14 MB. */
7942
+ const maxTarBytes = 268435456;
7943
+ const text = (block, start, length) => {
7944
+ const slice = block.subarray(start, start + length);
7945
+ const end = slice.indexOf(0);
7946
+ return slice.subarray(0, end < 0 ? slice.length : end).toString("utf8");
7947
+ };
7948
+ /** An octal field, or GNU base-256 when the high bit of the first byte is set. */
7949
+ const numeric = (block, start, length) => {
7950
+ if (block[start] & 128) {
7951
+ let n = 0;
7952
+ for (let i = start + 1; i < start + length; i++) n = n * 256 + block[i];
7953
+ return n;
7954
+ }
7955
+ const t = text(block, start, length).trim();
7956
+ if (t.length === 0) return 0;
7957
+ if (!/^[0-7]+$/.test(t)) throw new ArchiveError(`a tar header holds ${JSON.stringify(t)} where a number goes`);
7958
+ return Number.parseInt(t, 8);
7959
+ };
7960
+ /** `length key=value\n` records of a pax extended header. */
7961
+ function paxRecords(data) {
7962
+ const out = /* @__PURE__ */ new Map();
7963
+ let at = 0;
7964
+ while (at < data.length) {
7965
+ const space = data.indexOf(32, at);
7966
+ if (space < 0) break;
7967
+ const length = Number.parseInt(data.subarray(at, space).toString("latin1"), 10);
7968
+ if (!Number.isInteger(length) || length <= 0) break;
7969
+ const record = data.subarray(space + 1, at + length - 1).toString("utf8");
7970
+ const eq = record.indexOf("=");
7971
+ if (eq > 0) out.set(record.slice(0, eq), record.slice(eq + 1));
7972
+ at += length;
7973
+ }
7974
+ return out;
7853
7975
  }
7854
7976
  /**
7855
- * When an archive puts everything under one top-level directory, as the
7856
- * releases do (`lean-4.35.0-linux/`, `z3-5.3.2-x64-glibc-2.39/`), move
7857
- * its contents up so the executable is at the path the table names.
7977
+ * Take the named files of a gzip-compressed tar, and nothing else, as
7978
+ * `extractZipEntries` does for a zip: `entries` maps each file's path in
7979
+ * the archive (after any pax or GNU long name) to its path under `dest`.
7980
+ * Every header's checksum is checked; a named entry must be a regular file.
7858
7981
  */
7859
- function flattenSingleDirectory(dest) {
7860
- const entries = readdirSync(dest, { withFileTypes: true });
7861
- if (entries.length !== 1 || !entries[0].isDirectory()) return;
7862
- const inner = join(dest, entries[0].name);
7863
- for (const name of readdirSync(inner)) {
7864
- const to = join(dest, name);
7865
- if (existsSync(to)) throw new ArchiveError(`cannot flatten the archive: ${name} exists twice`);
7866
- renameSync(join(inner, name), to);
7867
- }
7868
- rmSync(inner, {
7869
- recursive: true,
7870
- force: true
7871
- });
7982
+ function extractTarGzEntries(file, entries, dest) {
7983
+ const places = placesOf(entries, dest);
7984
+ let tar;
7985
+ try {
7986
+ tar = gunzipSync(readFileSync(file), { maxOutputLength: maxTarBytes });
7987
+ } catch (err) {
7988
+ throw new ArchiveError(`not a gzip-compressed tar within ${maxTarBytes} bytes: ${err instanceof Error ? err.message : String(err)}`);
7989
+ }
7990
+ const found = /* @__PURE__ */ new Map();
7991
+ let next = {};
7992
+ let at = 0;
7993
+ while (at + 512 <= tar.length) {
7994
+ const block = tar.subarray(at, at + 512);
7995
+ if (block.every((b) => b === 0)) break;
7996
+ let sum = 0;
7997
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : block[i];
7998
+ if (sum !== numeric(block, 148, 8)) throw new ArchiveError("a tar header fails its checksum");
7999
+ const type = block[156] === 0 ? "0" : String.fromCharCode(block[156]);
8000
+ const size = type === "x" || type === "L" ? numeric(block, 124, 12) : next.size ?? numeric(block, 124, 12);
8001
+ const start = at + 512;
8002
+ if (start + size > tar.length) throw new ArchiveError("the tar ends inside an entry; the file is truncated");
8003
+ const data = tar.subarray(start, start + size);
8004
+ at = start + Math.ceil(size / 512) * 512;
8005
+ if (type === "x") {
8006
+ const records = paxRecords(data);
8007
+ const path = records.get("path");
8008
+ const declared = records.get("size");
8009
+ if (declared !== void 0 && !/^\d+$/.test(declared)) throw new ArchiveError(`a pax header gives the size ${JSON.stringify(declared)}`);
8010
+ next = {
8011
+ ...path === void 0 ? {} : { path },
8012
+ ...declared === void 0 ? {} : { size: Number(declared) }
8013
+ };
8014
+ continue;
8015
+ }
8016
+ if (type === "L") {
8017
+ next = {
8018
+ ...next,
8019
+ path: text(data, 0, data.length)
8020
+ };
8021
+ continue;
8022
+ }
8023
+ if (type === "g") continue;
8024
+ const prefix = text(block, 257, 6) === "ustar" ? text(block, 345, 155) : "";
8025
+ const plain = text(block, 0, 100);
8026
+ const name = next.path ?? (prefix.length > 0 ? `${prefix}/${plain}` : plain);
8027
+ next = {};
8028
+ if (!places.has(name)) continue;
8029
+ const quoted = JSON.stringify(name);
8030
+ if (found.has(name)) throw new ArchiveError(`entry ${quoted} is in the tar twice`);
8031
+ if (type === "5") throw new ArchiveError(`entry ${quoted} is a directory, not a file`);
8032
+ if (type === "1" || type === "2") throw new ArchiveError(`entry ${quoted} is a link, not a file`);
8033
+ if (type !== "0" && type !== "7") throw new ArchiveError(`entry ${quoted} is of tar type ${JSON.stringify(type)}, not a file`);
8034
+ found.set(name, Buffer.from(data));
8035
+ }
8036
+ return writeFound("tar", places, found);
7872
8037
  }
7873
8038
  // packages/cli/src/install.ts
7874
8039
  /**
7875
- * `eutaxy prover install <name>`: the pinned release of a prover put in
7876
- * Eutaxy's cache, where the engines look first. The file for this platform
7877
- * is downloaded (or copied from a mirror or an offline directory given with
7878
- * `--from`), its SHA-256 checked against the engine's table before anything
7879
- * is unpacked, unpacked beside a marker written last, and deleted. A
7880
- * mismatch or a failed download installs nothing. Nothing is run: the
7881
- * engines check the version when they look the toolchain up.
8040
+ * `eutaxy prover install <lean|smt>`: the pinned toolchain of a prover put
8041
+ * on this machine, where the engines look first.
8042
+ *
8043
+ * `installToolchain` installs a pinned upstream release file into Eutaxy's
8044
+ * cache: the file for this platform is downloaded (or copied from a mirror
8045
+ * or an offline directory given with `--from`), its SHA-256 checked against
8046
+ * the table before anything is unpacked, the files the table names taken
8047
+ * from it (a zip or a `tar.gz`) beside a marker written last, and the
8048
+ * download deleted. A mismatch or a failed download installs nothing, and
8049
+ * nothing is run. Z3 comes this way, and so does elan's installer.
8050
+ *
8051
+ * `installLean` installs Lean through elan, Lean's toolchain manager: the
8052
+ * machine's elan if it has one, else elan installed into Eutaxy's cache
8053
+ * from its pinned installer (without touching the PATH or the shell's
8054
+ * profile); then `elan toolchain install` of the pinned toolchain, whose
8055
+ * files' digest is checked against the pinned one, since elan checks no
8056
+ * pinned checksum itself.
7882
8057
  */
7883
- /** The toolchains the command installs, by the engine name it takes. */
7884
- const toolchains = {
7885
- lean: leanDownloads,
7886
- smt: z3Downloads
7887
- };
8058
+ /** The engines the command installs, by the name it takes. */
8059
+ const engines = ["lean", "smt"];
7888
8060
  var InstallError = class extends Error {};
7889
8061
  const isUrl = (s) => /^https?:\/\//.test(s);
7890
8062
  /** Write a byte stream to `path`, hashing it as it goes; the hash and the byte count come back. */
@@ -7966,10 +8138,10 @@ async function installToolchain(options) {
7966
8138
  mkdirSync(partial, { recursive: true });
7967
8139
  try {
7968
8140
  options.progress?.(`unpacking ${release.file}`);
7969
- if (release.file.endsWith(".zip")) extractZip(archive, partial);
7970
- else if (release.file.endsWith(".tar.zst")) await extractTarZst(archive, partial);
7971
- else throw new InstallError(`${release.file} is neither a .zip nor a .tar.zst`);
7972
- flattenSingleDirectory(partial);
8141
+ const extract = release.file.endsWith(".zip") ? extractZipEntries : release.file.endsWith(".tar.gz") ? extractTarGzEntries : void 0;
8142
+ if (extract === void 0) throw new InstallError(`${release.file} is neither a .zip nor a .tar.gz`);
8143
+ if (release.entries === void 0) throw new InstallError(`the table names no files to take from ${release.file}; nothing was installed`);
8144
+ extract(archive, release.entries, partial);
7973
8145
  const executable = executableName(toolchain, h);
7974
8146
  if (!existsSync(join(partial, executable))) throw new InstallError(`${release.file} holds no ${executable}; nothing was installed`);
7975
8147
  if (h.platform !== "win32") chmodSync(join(partial, executable), 493);
@@ -8014,21 +8186,197 @@ async function installToolchain(options) {
8014
8186
  } catch {}
8015
8187
  }
8016
8188
  }
8189
+ /** How long a quick elan command (a version, a list, a path) may take. */
8190
+ const quickMs = 6e4;
8191
+ /** How long elan may take to install the toolchain: a 600 MB download and 2.8 GB unpacked. */
8192
+ const toolchainInstallMs = 36e5;
8193
+ const exec = (command, args, options = {}) => new Promise((resolve) => {
8194
+ let child;
8195
+ try {
8196
+ child = spawn(command, args, {
8197
+ stdio: [
8198
+ "ignore",
8199
+ "pipe",
8200
+ "pipe"
8201
+ ],
8202
+ ...options.cwd === void 0 ? {} : { cwd: options.cwd },
8203
+ ...options.env === void 0 ? {} : { env: {
8204
+ ...process.env,
8205
+ ...options.env
8206
+ } }
8207
+ });
8208
+ } catch (err) {
8209
+ resolve({
8210
+ code: null,
8211
+ stdout: "",
8212
+ stderr: String(err)
8213
+ });
8214
+ return;
8215
+ }
8216
+ let stdout = "";
8217
+ let stderr = "";
8218
+ let timedOut = false;
8219
+ const timer = setTimeout(() => {
8220
+ timedOut = true;
8221
+ child.kill("SIGKILL");
8222
+ }, options.timeoutMs ?? quickMs);
8223
+ child.stdout?.on("data", (d) => {
8224
+ stdout += d.toString();
8225
+ });
8226
+ child.stderr?.on("data", (d) => {
8227
+ stderr += d.toString();
8228
+ });
8229
+ child.on("error", (err) => {
8230
+ clearTimeout(timer);
8231
+ resolve({
8232
+ code: null,
8233
+ stdout,
8234
+ stderr: `${stderr}${String(err)}`
8235
+ });
8236
+ });
8237
+ child.on("close", (code) => {
8238
+ clearTimeout(timer);
8239
+ resolve(timedOut ? {
8240
+ code: null,
8241
+ stdout,
8242
+ stderr: `${stderr}timed out`,
8243
+ timedOut: true
8244
+ } : {
8245
+ code,
8246
+ stdout,
8247
+ stderr
8248
+ });
8249
+ });
8250
+ });
8251
+ /** The last lines of a command's error output, for a message. */
8252
+ const tail = (text) => text.trim().split("\n").slice(-5).join("\n");
8253
+ /**
8254
+ * Lean through elan. The result's `file` is the toolchain's name, `source`
8255
+ * the elan that installed it, `sha256` the digest of the toolchain's files,
8256
+ * `bytes` their size and `dir` the toolchain's directory.
8257
+ */
8258
+ async function installLean(options = {}) {
8259
+ const h = options.host ?? host();
8260
+ const platform = platformOf(h);
8261
+ const expected = platform === void 0 ? void 0 : (options.digests ?? leanDigests)[platform];
8262
+ if (platform === void 0 || expected === void 0) throw new InstallError(`no lean ${leanVersion} toolchain for ${h.platform}-${h.arch}; the platforms are ${platforms.join(", ")}`);
8263
+ if (options.from !== void 0) throw new InstallError(`--from applies to smt only: Lean is installed by elan, which downloads it from releases.lean-lang.org; offline, unpack Lean's release by hand and register it with elan toolchain link`);
8264
+ const run = options.exec ?? exec;
8265
+ const say = options.progress ?? (() => {});
8266
+ let elan;
8267
+ for (const candidate of elanCandidates(h)) if ((await run(candidate.command, ["--version"], { env: candidate.env })).code === 0) {
8268
+ elan = candidate;
8269
+ break;
8270
+ }
8271
+ if (elan === void 0) {
8272
+ const installer = await installToolchain({
8273
+ toolchain: options.elanInstaller ?? elanDownloads,
8274
+ host: h,
8275
+ ...options.fetch === void 0 ? {} : { fetch: options.fetch },
8276
+ ...options.progress === void 0 ? {} : { progress: options.progress }
8277
+ });
8278
+ const home = elanHome(h);
8279
+ say(`installing elan ${elanVersion} in ${home}`);
8280
+ const made = await run(installer.executable, [
8281
+ "-y",
8282
+ "--no-modify-path",
8283
+ "--default-toolchain",
8284
+ "none"
8285
+ ], {
8286
+ env: { ELAN_HOME: home },
8287
+ timeoutMs: 6e5
8288
+ });
8289
+ elan = elanCandidates(h)[0];
8290
+ if (made.code !== 0 || (await run(elan.command, ["--version"], { env: elan.env })).code !== 0) throw new InstallError(`elan's installer did not install elan in ${home} (exit ${made.code}): ${tail(made.stderr)}`);
8291
+ }
8292
+ const list = await run(elan.command, ["toolchain", "list"], { env: elan.env });
8293
+ if (list.code !== 0) throw new InstallError(`elan (${elan.command}) could not list its toolchains (exit ${list.code}): ${tail(list.stderr)}`);
8294
+ const had = list.stdout.split("\n").some((line) => line.trim().split(" ")[0] === leanToolchain);
8295
+ if (!had) {
8296
+ say(`installing ${leanToolchain} through ${elan.command} (about 600 MB to download, 2.8 GB unpacked)`);
8297
+ const installed = await run(elan.command, [
8298
+ "toolchain",
8299
+ "install",
8300
+ leanToolchain
8301
+ ], {
8302
+ env: elan.env,
8303
+ timeoutMs: toolchainInstallMs
8304
+ });
8305
+ if (installed.code !== 0) throw new InstallError(`elan could not install ${leanToolchain} (exit ${installed.code}): ${tail(installed.stderr)}`);
8306
+ }
8307
+ const pinned = mkdtempSync(join(tmpdir(), "eutaxy-lean-toolchain-"));
8308
+ let where;
8309
+ try {
8310
+ writeFileSync(join(pinned, "lean-toolchain"), `${leanToolchain}\n`);
8311
+ where = await run(elan.command, ["which", "lean"], {
8312
+ env: {
8313
+ ...elan.env,
8314
+ ELAN_TOOLCHAIN: leanToolchain
8315
+ },
8316
+ cwd: pinned
8317
+ });
8318
+ } finally {
8319
+ rmSync(pinned, {
8320
+ recursive: true,
8321
+ force: true
8322
+ });
8323
+ }
8324
+ const leanPath = where.stdout.trim();
8325
+ const prefix = dirname(dirname(leanPath));
8326
+ if (where.code !== 0 || !/[\\/]bin[\\/]lean(\.exe)?$/.test(leanPath) || !existsSync(prefix)) throw new InstallError(`elan has ${leanToolchain} but did not say where (exit ${where.code}): ${tail(where.stderr) || leanPath}`);
8327
+ say(`checking the files of ${leanToolchain} in ${prefix}`);
8328
+ const found = toolchainDigest(prefix);
8329
+ const digests = options.digests ?? leanDigests;
8330
+ const sameSystem = Object.entries(digests).find(([p, d]) => d === found.digest && p.startsWith(`${h.platform}-`))?.[0];
8331
+ if (sameSystem !== void 0 && sameSystem !== platform) say(`the toolchain is the pinned release for ${sameSystem}, the architecture ${elan.command} installs for, not ${platform}; it runs here too`);
8332
+ if (sameSystem === void 0) {
8333
+ let fate = "it was there before this command, so it was left as it is";
8334
+ if (!had) {
8335
+ const removed = await run(elan.command, [
8336
+ "toolchain",
8337
+ "uninstall",
8338
+ leanToolchain
8339
+ ], { env: elan.env });
8340
+ fate = removed.code === 0 ? "it was uninstalled" : `uninstalling it failed (exit ${removed.code}): remove it with elan toolchain uninstall ${leanToolchain}`;
8341
+ }
8342
+ throw new InstallError(`the toolchain in ${prefix} is not the pinned ${leanToolchain}: the digest of its files is ${found.digest}, expected ${expected}; ${fate}`);
8343
+ }
8344
+ return {
8345
+ name: "lean",
8346
+ version: leanVersion,
8347
+ platform,
8348
+ file: leanToolchain,
8349
+ source: elan.command,
8350
+ sha256: found.digest,
8351
+ bytes: found.bytes,
8352
+ dir: prefix,
8353
+ executable: join(prefix, "bin", h.platform === "win32" ? "lean.exe" : "lean"),
8354
+ downloaded: !had
8355
+ };
8356
+ }
8017
8357
  /** The command: the result as text or `--json` on stdout, progress and errors on stderr; exit 0, or 3 on an error. */
8018
8358
  async function runInstall(options) {
8019
8359
  try {
8020
- const result = await installToolchain({
8021
- toolchain: options.toolchain,
8360
+ const shared = {
8022
8361
  ...options.host === void 0 ? {} : { host: options.host },
8023
8362
  ...options.fetch === void 0 ? {} : { fetch: options.fetch },
8024
8363
  ...options.from === void 0 ? {} : { from: options.from },
8025
8364
  progress: (text) => options.stderr(`${text}\n`)
8365
+ };
8366
+ const result = options.engine === "lean" ? await installLean({
8367
+ ...shared,
8368
+ ...options.exec === void 0 ? {} : { exec: options.exec },
8369
+ ...options.digests === void 0 ? {} : { digests: options.digests }
8370
+ }) : await installToolchain({
8371
+ ...shared,
8372
+ toolchain: z3Downloads
8026
8373
  });
8027
8374
  if (options.json) options.stdout(`${JSON.stringify({
8028
8375
  schemaVersion: 1,
8029
8376
  command: "prover install",
8030
8377
  ...result
8031
8378
  }, null, 2)}\n`);
8379
+ else if (options.engine === "lean") options.stdout(`${result.name} ${result.version} ${result.downloaded ? "installed" : "already installed"} in ${result.dir}\n ${result.file} through ${result.source}\n files checked, digest ${result.sha256}\n`);
8032
8380
  else if (result.downloaded) options.stdout(`${result.name} ${result.version} installed in ${result.dir}\n ${result.file} from ${result.source}\n sha256 ${result.sha256}\n`);
8033
8381
  else options.stdout(`${result.name} ${result.version} already installed in ${result.dir} (${result.file}, sha256 ${result.sha256})\n`);
8034
8382
  return exitCodes.BOUNDED;
@@ -8334,7 +8682,7 @@ async function runReport(o) {
8334
8682
  }
8335
8683
  // packages/cli/src/version.ts
8336
8684
  /** The published package's version, as the MCP server reports it; the release tooling keeps it in step. */
8337
- const eutaxyVersion = "0.17.1";
8685
+ const eutaxyVersion = "0.18.0";
8338
8686
  // packages/cli/src/mcp.ts
8339
8687
  /**
8340
8688
  * `eutaxy mcp`: a Model Context Protocol server over stdio, so a coding
@@ -8468,7 +8816,7 @@ const tools = [
8468
8816
  {
8469
8817
  name: "check",
8470
8818
  title: "Check a scenario",
8471
- description: "Run a scenario file (*.sim.ts) in the simulator and return the JSON report: the verdict (BOUNDED, VIOLATED with the shrunk schedule, or UNSUPPORTED), the spec verdicts, and on a violation the path of the regression test written beside the scenario (regressionTest). Exit code 1 is a violation or a refuted spec, not an error.",
8819
+ description: "Run a scenario file (*.sim.ts) in the simulator and return the JSON report: the verdict (BOUNDED, VIOLATED with the shrunk schedule, or UNSUPPORTED), the spec verdicts, and on a violation the path of the regression test written beside the scenario (regressionTest), and the errors nothing handled during a run whose verdict still stands (unhandledErrors). Exit code 1 is a violation or a refuted spec, not an error.",
8472
8820
  inputSchema: {
8473
8821
  type: "object",
8474
8822
  properties: {
@@ -8876,8 +9224,9 @@ check options:
8876
9224
  --prover <names> also run the PROVEN rung with these engines on the scenario's specs
8877
9225
  (comma-separated; known: lean, smt)
8878
9226
  --json print the versioned JSON report instead of text
8879
- --out <path> where to write the regression test on a violation
8880
- --no-regression do not write a regression test
9227
+ --out <path> where to write the regression test on a violation, or the
9228
+ test replaying the run that met something outside the model
9229
+ --no-regression do not write either test
8881
9230
  --expect-violation write a regression test that asserts the violation (for corpora)
8882
9231
  --keep keep the generated .eutaxy/ files
8883
9232
 
@@ -8894,11 +9243,14 @@ through the TESTED rung, on inputs drawn from the parameter types with the seed
8894
9243
  (default: report), and the PROVEN rung with --prover. No scenario runs, so nothing
8895
9244
  is CHECKED.
8896
9245
 
8897
- prover install puts the pinned Lean or Z3 release for this platform in Eutaxy's cache
9246
+ prover install smt puts the pinned Z3 for this platform in Eutaxy's cache
8898
9247
  (EUTAXY_CACHE_DIR, else the platform's user cache), where --prover finds it first:
8899
9248
  downloaded from the upstream GitHub release, or from a mirror or offline directory
8900
- holding the same file (--from), and checked against the engine's SHA-256 before it is
8901
- unpacked. Nothing is downloaded at any other time.
9249
+ holding the same file (--from), and checked against its SHA-256 before the solver is
9250
+ taken from it. prover install lean installs the pinned Lean through elan: the machine's
9251
+ elan, else elan put in Eutaxy's cache from its pinned installer (the PATH and the
9252
+ shell's profile untouched); the toolchain's files are checked against the pinned
9253
+ digest. Nothing is downloaded at any other time.
8902
9254
 
8903
9255
  report options: --goals writes each module's open Lean goals beside its spec file as
8904
9256
  <spec>.goals.lean (a proof file with every proof open) and lists them; needs --prover lean.
@@ -8952,7 +9304,7 @@ async function main(argv, io) {
8952
9304
  });
8953
9305
  }
8954
9306
  if (command === "prover") {
8955
- const names = Object.keys(toolchains).join("|");
9307
+ const names = engines.join("|");
8956
9308
  if (positionals[1] !== "install" || positionals.length !== 3) {
8957
9309
  io.stderr(`prover takes: install <${names}>\n\n${usage}`);
8958
9310
  return exitCodes.error;
@@ -8962,13 +9314,13 @@ async function main(argv, io) {
8962
9314
  io.stderr(`prover install does not take --${other}\n`);
8963
9315
  return exitCodes.error;
8964
9316
  }
8965
- const toolchain = toolchains[positionals[2]];
8966
- if (toolchain === void 0) {
9317
+ const engine = positionals[2];
9318
+ if (!engines.includes(engine)) {
8967
9319
  io.stderr(`unknown engine ${positionals[2]}; the engines are ${names.replaceAll("|", ", ")}\n`);
8968
9320
  return exitCodes.error;
8969
9321
  }
8970
9322
  return runInstall({
8971
- toolchain,
9323
+ engine,
8972
9324
  from: str("from"),
8973
9325
  json: flags["json"] === true,
8974
9326
  stdout: io.stdout,
@@ -9092,4 +9444,4 @@ async function main(argv, io) {
9092
9444
  }
9093
9445
  export { main as t };
9094
9446
 
9095
- //# sourceMappingURL=cli-CxbXc1j2.mjs.map
9447
+ //# sourceMappingURL=cli-DyA7uTBg.mjs.map