sail-solve 0.3.1

Fast, cached Verus verification for Rust: standalone files, projects, watch and agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Smoke tests for the `sail` binary's command surface.

use std::io::Write as _;
use std::process::{Command, Output, Stdio};

fn sail(args: &[&str]) -> Output {
    match Command::new(env!("CARGO_BIN_EXE_sail")).args(args).output() {
        Ok(output) => output,
        Err(e) => unreachable!("cannot run sail: {e}"),
    }
}

/// The user help lists the supported commands. `sail bench` needs
/// `sail-bench`, which only a source build has, and experimental commands
/// are not part of the supported set, so the help leaves them out.
#[test]
fn help_lists_every_user_command() {
    let output = sail(&["--help"]);
    assert_eq!(output.status.code(), Some(0));
    let text = String::from_utf8_lossy(&output.stdout);
    let listed: Vec<&str> = text
        .lines()
        .filter_map(|line| line.strip_prefix("    "))
        .filter_map(|line| line.split_whitespace().next())
        .collect();
    for cmd in [
        "new",
        "verify",
        "repair-check",
        "explain",
        "baseline",
        "compare",
        "report",
        "engine",
        "watch",
        "jobs",
        "mcp",
        "runtime",
        "status",
        "cache",
    ] {
        assert!(listed.contains(&cmd), "help is missing `{cmd}`:\n{text}");
    }
    for cmd in ["bench", "serve", "fragility", "assurance"] {
        assert!(!listed.contains(&cmd), "help lists `{cmd}`:\n{text}");
    }
    assert!(!text.contains("experimental"), "{text}");
}

/// `--version` reports the build's `SAIL_VERSION` when set (release builds),
/// else the crate version.
#[test]
fn version_reports_the_build_version() {
    let output = sail(&["--version"]);
    assert_eq!(output.status.code(), Some(0));
    let expected = match option_env!("SAIL_VERSION") {
        Some(version) if !version.is_empty() => version,
        _ => env!("CARGO_PKG_VERSION"),
    };
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        format!("sail {expected}\n")
    );
    assert_eq!(expected, sail_api::VERSION, "reports state this version");
}

/// The MCP server states the version `sail --version` prints (#180).
#[test]
fn mcp_server_states_the_cli_version() {
    let cache = std::env::temp_dir().join(format!("sail-cli-version-{}", std::process::id()));
    let child = Command::new(env!("CARGO_BIN_EXE_sail"))
        .arg("mcp")
        .env("SAIL_CACHE_DIR", &cache)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn();
    let Ok(mut child) = child else {
        unreachable!("cannot run sail mcp: {child:?}")
    };
    let init = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}"#;
    if let Some(mut stdin) = child.stdin.take() {
        assert!(writeln!(stdin, "{init}").is_ok());
    }
    let output = child.wait_with_output();
    let _ = std::fs::remove_dir_all(&cache);
    let Ok(output) = output else {
        unreachable!("sail mcp failed: {output:?}")
    };
    let text = String::from_utf8_lossy(&output.stdout);
    let reply: serde_json::Value = text
        .lines()
        .next()
        .and_then(|l| serde_json::from_str(l).ok())
        .unwrap_or_default();
    let version = String::from_utf8_lossy(&sail(&["--version"]).stdout).into_owned();
    let served = reply["result"]["serverInfo"]["version"]
        .as_str()
        .unwrap_or("(none)");
    assert_eq!(format!("sail {served}\n"), version, "{text}");
}

fn temporal_capability(dir: &std::path::Path) -> serde_json::Value {
    let output = Command::new(dir.join("sail"))
        .args(["runtime", "capabilities", "--cache"])
        .arg(dir)
        .env("SAIL_CACHE_DIR", dir)
        .output();
    let output = match output {
        Ok(output) => output,
        Err(e) => unreachable!("cannot run sail: {e}"),
    };
    assert!(output.status.success(), "{output:?}");
    let capabilities: serde_json::Value = match serde_json::from_slice(&output.stdout) {
        Ok(value) => value,
        Err(e) => unreachable!("capabilities are not JSON: {e}"),
    };
    capabilities["temporal"].clone()
}

/// The `sail` binary links the native temporal backend (ADR 0172), so its
/// capability reaches worker discovery: with no worker beside it, it reports
/// the missing installation, never that the backend is absent from the build;
/// a malformed manifest beside it is refused, never trusted.
#[test]
fn sail_links_the_temporal_backend_and_discovers_its_worker() {
    let dir = isolated_sail("temporal-linked");
    let missing = temporal_capability(&dir);
    assert!(std::fs::write(dir.join("sail-runtime-worker.json"), "{}").is_ok());
    let malformed = temporal_capability(&dir);
    let _ = std::fs::remove_dir_all(&dir);
    for temporal in [&missing, &malformed] {
        assert_eq!(temporal["implemented"], true, "{temporal}");
        assert_eq!(temporal["installed"], false, "{temporal}");
        assert_eq!(temporal["worker_sha256"], serde_json::Value::Null);
        assert_eq!(
            temporal["backend_revision"],
            sail_api::temporal::DIVE_VERSION
        );
        assert_ne!(
            temporal["error"]["message"],
            sail_runtime::temporal::NOT_INCLUDED,
            "{temporal}"
        );
    }
    assert_eq!(
        missing["error"]["message"],
        "native temporal worker is not installed"
    );
    assert!(
        malformed["error"]["message"]
            .as_str()
            .is_some_and(|m| m.contains("invalid worker installation manifest")),
        "{malformed}"
    );
}

/// A directory holding this build's `sail` under its own name, so `sail
/// bench` resolves `sail-bench` beside it there. Cargo builds `sail-bench` only
/// for a test run that selects that package, so the delegation tests supply
/// their own; `sail-bench`'s own tests check its help. The binary is hard
/// linked where possible: a fresh copy is a new executable, which macOS
/// assesses on first exec.
fn isolated_sail(name: &str) -> std::path::PathBuf {
    let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"))
        .join(format!("sail-cli-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    assert!(std::fs::create_dir_all(&dir).is_ok());
    let sail = dir.join("sail");
    let source = env!("CARGO_BIN_EXE_sail");
    assert!(
        std::fs::hard_link(source, &sail).is_ok() || std::fs::copy(source, &sail).is_ok(),
        "cannot place sail in {}",
        dir.display()
    );
    dir
}

/// `sail bench` runs the `sail-bench` beside it with the same arguments and
/// stdio, and exits with its status.
#[cfg(unix)]
#[test]
fn bench_delegates_to_the_benchmark_binary() {
    use std::os::unix::fs::PermissionsExt as _;
    let dir = isolated_sail("bench");
    let bench = dir.join("sail-bench");
    assert!(
        std::fs::write(
            &bench,
            "#!/bin/sh\nprintf 'stand-in sail-bench:'\nprintf ' [%s]' \"$@\"\necho\necho 'to stderr' >&2\nexit 7\n",
        )
        .is_ok()
    );
    assert!(std::fs::set_permissions(&bench, std::fs::Permissions::from_mode(0o755)).is_ok());
    let output = Command::new(dir.join("sail"))
        .args(["bench", "history-replay", "--project", "a b"])
        .output();
    let _ = std::fs::remove_dir_all(&dir);
    let Ok(output) = output else {
        unreachable!("cannot run sail: {output:?}")
    };
    assert_eq!(
        output.status.code(),
        Some(7),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        "stand-in sail-bench: [history-replay] [--project] [a b]\n"
    );
    assert_eq!(String::from_utf8_lossy(&output.stderr), "to stderr\n");
}

/// Without `sail-bench` beside it, `sail bench` explains how to build it.
#[test]
fn bench_without_the_benchmark_binary_says_how_to_build_it() {
    let dir = isolated_sail("nobench");
    let output = Command::new(dir.join("sail"))
        .args(["bench", "--help"])
        .output();
    let _ = std::fs::remove_dir_all(&dir);
    let Ok(output) = output else {
        unreachable!("cannot run sail: {output:?}")
    };
    assert_eq!(output.status.code(), Some(2));
    assert_eq!(output.stdout, b"");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.starts_with("error[SAIL0003]: cannot run sail-bench")
            && stderr.contains("cargo build --release -p sail-bench"),
        "{stderr}"
    );
}

/// Retired attribution refuses before any verifier mode touches a project.
#[test]
fn retired_attribution_refuses_before_mode_setup() {
    let root =
        std::env::temp_dir().join(format!("sail-retired-attribution-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    assert!(std::fs::create_dir_all(&root).is_ok());
    assert!(std::fs::write(
        root.join("Cargo.toml"),
        "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[package.metadata.verus]\nverify = true\n[workspace]\n",
    ).is_ok());
    assert!(std::fs::write(root.join("demo.rs"), "fn main() {}\n").is_ok());
    for mode in [
        vec![],
        vec!["--background"],
        vec!["--engine"],
        vec!["--measure-fragility", "--fragility-seeds", "1"],
        vec![
            "--portfolio",
            "accept-first-proof",
            "--portfolio-seeds",
            "1",
        ],
        vec!["demo.rs"],
    ] {
        for retired in [
            vec!["--requirement", "R=demo::f"],
            vec!["--requirement=R=demo::f"],
        ] {
            let output = Command::new(env!("CARGO_BIN_EXE_sail"))
                .arg("verify")
                .args(&mode)
                .args(&retired)
                .current_dir(&root)
                .env("CARGO", root.join("missing-cargo"))
                .env("SAIL_CARGO_VERUS", root.join("missing-cargo-verus"))
                .env("SAIL_CACHE_DIR", root.join("cache"))
                .output();
            let Ok(output) = output else {
                unreachable!("cannot run sail: {output:?}")
            };
            assert_eq!(output.status.code(), Some(2), "{mode:?} {retired:?}");
            assert!(output.stdout.is_empty(), "{mode:?} {retired:?}");
            assert!(
                String::from_utf8_lossy(&output.stderr).starts_with("error[SAIL3161]:"),
                "{mode:?} {retired:?}: {:?}",
                output.stderr
            );
            let entries = std::fs::read_dir(&root)
                .into_iter()
                .flatten()
                .flatten()
                .count();
            assert_eq!(
                entries, 2,
                "retired request created project/cache artifacts: {mode:?} {retired:?}"
            );
        }
    }
    let output = sail(&["assurance", "--help"]);
    assert_eq!(output.status.code(), Some(2));
    assert_eq!(output.stdout, b"");
    assert!(String::from_utf8_lossy(&output.stderr).contains("SAIL0002"));
    for args in [vec!["assurance"], vec!["assurance", "historical-job"]] {
        let output = sail(&args);
        assert_eq!(output.status.code(), Some(2));
        assert_eq!(output.stdout, b"");
        assert!(String::from_utf8_lossy(&output.stderr).contains("SAIL3161"));
    }
    assert!(std::fs::remove_dir_all(root).is_ok());
}

/// ADR 0043: Sail runs only its own Verus. Without it, `sail verify` fails
/// with SAIL0101 and never runs a `cargo-verus` found on `PATH`; the explicit
/// development override is used instead, announced by warning SAIL0108.
/// (Managed verification identifies the override's toolchain before it runs
/// it, through the `verus` launcher beside it, which this stand-in lacks.)
#[cfg(unix)]
#[test]
fn verify_never_runs_a_cargo_verus_from_path() {
    use std::os::unix::fs::PermissionsExt as _;
    let root = std::env::temp_dir().join(format!("sail-nostock-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    let bin = root.join("bin");
    assert!(std::fs::create_dir_all(&bin).is_ok());
    let marker = root.join("ran");
    // Keep this engine-selection fixture in the supported managed setup;
    // overlapping package/cache roots deliberately take the plain fallback.
    let cache = root.with_extension("cache");
    let _ = std::fs::remove_dir_all(&cache);
    let cargo_home = root.with_extension("cargo-home");
    let _ = std::fs::remove_dir_all(&cargo_home);
    assert!(std::fs::create_dir_all(&cargo_home).is_ok());
    // A Verus project, so verification gets as far as choosing a Verus.
    assert!(std::fs::create_dir_all(root.join("src")).is_ok());
    assert!(
        std::fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[package.metadata.verus]\nverify = true\n\n[workspace]\n",
        )
        .is_ok()
    );
    assert!(std::fs::write(root.join("src/lib.rs"), "").is_ok());
    // A copy of `sail` with a stand-in `sail-z3` beside it, so setup succeeds
    // whether or not the shim was built.
    let sail = root.join("sail-bin").join("sail");
    assert!(std::fs::create_dir_all(root.join("sail-bin")).is_ok());
    assert!(std::fs::copy(env!("CARGO_BIN_EXE_sail"), &sail).is_ok());
    assert!(std::fs::write(root.join("sail-bin").join("sail-z3"), "").is_ok());
    let fake = bin.join("cargo-verus");
    let script = format!("#!/bin/sh\ntouch '{}'\nexit 0\n", marker.display());
    assert!(std::fs::write(&fake, script).is_ok());
    assert!(std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).is_ok());
    let path = std::env::join_paths(std::iter::once(bin.clone()).chain(std::env::split_paths(
        &std::env::var_os("PATH").unwrap_or_default(),
    )))
    .unwrap_or_default();
    let run = |cargo_verus: Option<&std::path::Path>| {
        let mut command = Command::new(&sail);
        command
            .arg("verify")
            .current_dir(&root)
            .env("PATH", &path)
            // This fixture needs an unconfigured Cargo setup, independent of the caller.
            .env("CARGO_HOME", &cargo_home)
            .env("SAIL_CACHE_DIR", &cache)
            // Longer than any Unix socket path: no daemon is started.
            .env("SAIL_DAEMON_SOCKET", root.join("d".repeat(120)))
            .env_remove("SAIL_VERUS_BUILD")
            .env_remove("SAIL_CARGO_VERUS")
            .env("VERUS_Z3_PATH", &fake);
        // Loader overrides (the CI image sets one) are refused before a
        // Verus is chosen (SAIL3112); this test is about the choice.
        for loader in [
            "LD_PRELOAD",
            "LD_LIBRARY_PATH",
            "DYLD_INSERT_LIBRARIES",
            "DYLD_LIBRARY_PATH",
            "DYLD_FRAMEWORK_PATH",
        ] {
            command.env_remove(loader);
        }
        if let Some(cargo_verus) = cargo_verus {
            command.env("SAIL_CARGO_VERUS", cargo_verus);
        }
        command
            .output()
            .unwrap_or_else(|e| unreachable!("cannot run sail: {e}"))
    };
    let output = run(None);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(output.status.code(), Some(2), "{stderr}");
    assert!(
        stderr.starts_with("error[SAIL0101]: sail verify: Sail's Verus (the fork runtime and interactive engine) is not installed")
            && stderr.contains("never falls back"),
        "{stderr}"
    );
    assert!(!marker.exists(), "sail ran the cargo-verus on PATH");
    let output = run(Some(&fake));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.starts_with("warning[SAIL0108]: SAIL_CARGO_VERUS replaces Sail's Verus"),
        "{stderr}"
    );
    assert!(
        !stderr.contains("SAIL0101") && stderr.contains(&bin.join("verus").display().to_string()),
        "the explicit override was not used: {stderr}"
    );
    assert!(
        !marker.exists(),
        "sail ran a cargo-verus without identifying it"
    );
    let _ = std::fs::remove_dir_all(&root);
    let _ = std::fs::remove_dir_all(&cache);
    let _ = std::fs::remove_dir_all(&cargo_home);
}

#[test]
fn unknown_command_is_a_usage_error() {
    let output = sail(&["frobnicate"]);
    assert_eq!(output.status.code(), Some(2));
    assert!(String::from_utf8_lossy(&output.stderr).contains("SAIL0002"));
}

#[test]
fn no_arguments_is_a_usage_error() {
    assert_eq!(sail(&[]).status.code(), Some(2));
}

/// Without an installed engine, `engine status` and `repair-check` name the
/// missing file and how to obtain the engine, and `repair-check` fails before
/// it starts a daemon or submits a job (no infrastructure-error job is left).
#[test]
fn missing_engine_is_reported_up_front() {
    let root = std::env::temp_dir().join(format!("sail-noengine-{}", std::process::id()));
    let cache = root.join("cache");
    let _ = std::fs::remove_dir_all(&root);
    assert!(std::fs::create_dir_all(&root).is_ok());
    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_sail"))
            .args(args)
            .current_dir(&root)
            .env("SAIL_CACHE_DIR", &cache)
            .env_remove("SAIL_DAEMON_SOCKET")
            .env_remove("SAIL_VERUS_BUILD")
            .output()
            .unwrap_or_else(|e| unreachable!("cannot run sail: {e}"))
    };
    for args in [
        &["engine", "status"][..],
        &[
            "repair-check",
            "--engine",
            "interactive",
            "-p",
            "demo",
            "--lib",
            "--function",
            "demo::max",
        ][..],
    ] {
        let output = run(args);
        assert_eq!(output.status.code(), Some(2), "{args:?}");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.starts_with(
                "error[SAIL3120]: Sail's Verus (the fork runtime and interactive engine) is not installed"
            )
                && stderr.contains("sail-build.json")
                && stderr.contains("cargo xtask build-verus-engine")
                && stderr.contains("sail engine install --from PATH")
                && !stderr.contains("private"),
            "{args:?}: {stderr}"
        );
    }
    // No daemon was started and no job was recorded.
    assert!(!cache.join("results/projects/jobs").exists());
    let _ = std::fs::remove_dir_all(&root);
}

/// `--help` prints help and exits 0 for every command, without running it
/// (`sail watch --help` used to start a watcher; `sail cache gc --help` was
/// rejected).
#[test]
fn every_command_has_help() {
    for command in [
        "verify",
        "repair-check",
        "engine",
        "explain",
        "baseline",
        "compare",
        "report",
        "watch",
        "jobs",
        "mcp",
        "serve",
        "status",
        "cache",
        "fragility",
        "runtime",
    ] {
        for args in [
            vec![command, "--help"],
            vec![command, "-h"],
            vec!["help", command],
        ] {
            let output = Command::new(env!("CARGO_BIN_EXE_sail"))
                .args(&args)
                .env("SAIL_CARGO_VERUS", "/nonexistent/cargo-verus")
                .output()
                .unwrap_or_else(|e| unreachable!("cannot run sail: {e}"));
            assert_eq!(output.status.code(), Some(0), "{args:?}");
            assert!(!output.stdout.is_empty(), "{args:?}");
        }
    }
    // Supported commands' help carries no experimental note.
    for args in [
        &["repair-check", "--help"][..],
        &["explain", "--help"],
        &["baseline", "--help"],
        &["compare", "--help"],
        &["report", "--help"],
        &["runtime", "--help"],
    ] {
        let output = sail(args);
        assert_eq!(output.status.code(), Some(0), "{args:?}");
        assert!(
            !String::from_utf8_lossy(&output.stdout).contains("EXPERIMENTAL"),
            "{args:?}"
        );
    }
    // Experimental commands keep their help, which says they are experimental.
    for args in [
        &["serve", "--help"][..],
        &["fragility", "--help"],
        &["cache", "keygen", "--help"],
        &["cache", "trust", "list", "--help"],
        &["cache", "publish", "--help"],
        &["cache", "serve", "--help"],
        &["cache", "connect", "--help"],
    ] {
        let output = sail(args);
        assert_eq!(output.status.code(), Some(0), "{args:?}");
        assert!(
            String::from_utf8_lossy(&output.stdout).starts_with("EXPERIMENTAL: "),
            "{args:?}"
        );
    }
    let cache = sail(&["cache", "--help"]);
    let cache = String::from_utf8_lossy(&cache.stdout);
    assert!(
        !cache.contains("EXPERIMENTAL") && !cache.contains("keygen"),
        "{cache}"
    );
    let gc = sail(&["cache", "gc", "--help"]);
    assert_eq!(gc.status.code(), Some(0));
    assert!(String::from_utf8_lossy(&gc.stdout).contains("gc --max-bytes N"));
    let verify = sail(&["verify", "--help"]);
    let verify = String::from_utf8_lossy(&verify.stdout);
    // Managed verification is the default; `--incremental` stays accepted
    // and is documented as a deprecated no-op.
    assert!(
        verify.contains("--incremental                 deprecated, does nothing"),
        "{verify}"
    );
    // The verdict-changing portfolio and experimental fragility options
    // still run but are not listed.
    assert!(
        !verify.contains("--portfolio") && !verify.contains("--measure-fragility"),
        "{verify}"
    );
    assert_eq!(sail(&["help", "frobnicate"]).status.code(), Some(2));
}