Skip to main content

sail_cli/
lib.rs

1//! The `sail` command line, as a library so that a `sail` built outside this
2//! workspace can link optional extensions (ADR 0083).
3//!
4//! Verification, persistent jobs, workspace watch, MCP and cache management.
5//! Experimental commands (`help::EXPERIMENTAL`) and `sail bench` for
6//! contributors run but are not listed by `sail --help`.
7#![forbid(unsafe_code)]
8
9mod ci_report;
10mod engine_cli;
11mod engine_download;
12mod fragility;
13mod fragility_join;
14mod health;
15mod help;
16mod jobs;
17mod kani_cli;
18mod kani_setup;
19mod managed_cli;
20mod measurement;
21mod new;
22mod ops;
23mod portfolio;
24mod portfolio_scope;
25mod preparation;
26mod product_cli;
27mod projects_cli;
28mod remote_cache;
29mod report;
30mod runtime_cli;
31#[cfg(test)]
32mod scope;
33mod shared_ops;
34mod verify;
35mod watch;
36
37use std::fmt::Write as _;
38use std::process::ExitCode;
39
40/// The version `sail --version` reports, which every report also states.
41const VERSION: &str = sail_api::VERSION;
42
43/// The supported commands, in the order `--help` lists them.
44const COMMANDS: &[(&str, &str)] = &[
45    (
46        "new",
47        "create a Verus project that `sail verify` verifies as it stands",
48    ),
49    (
50        "verify",
51        "verify a Cargo project or a standalone Verus .rs file",
52    ),
53    (
54        "repair-check",
55        "focus a repair, then independently validate its full target",
56    ),
57    (
58        "explain",
59        "show the exact failure evidence for one function from a retained job",
60    ),
61    (
62        "baseline",
63        "save, list and read immutable verification baselines",
64    ),
65    (
66        "compare",
67        "compare two completed jobs, or a job against a saved baseline",
68    ),
69    (
70        "report",
71        "render a result document for CI: job summary, annotations or SARIF",
72    ),
73    (
74        "health",
75        "read recorded proof effort and compare earlier evidence",
76    ),
77    (
78        "engine",
79        "install or inspect Sail's Verus (fork runtime and repair engine)",
80    ),
81    (
82        "watch",
83        "re-verify a workspace or standalone file as it changes",
84    ),
85    ("jobs", "inspect, follow, or cancel local verification jobs"),
86    (
87        "mcp",
88        "serve verification to agents over MCP (stdio; see docs/mcp.md)",
89    ),
90    (
91        "runtime",
92        "run SMT-LIB transcripts through the pinned Z3 (see docs/runtime.md)",
93    ),
94    ("status", "show daemon and cache state"),
95    ("cache", "inspect and manage the result cache"),
96];
97
98/// Exit code for a malformed command line.
99const EXIT_USAGE: u8 = 2;
100
101fn usage() -> String {
102    let mut text = format!(
103        "sail {VERSION}\nSatisfiability Analysis & Inference Layer\n\nUSAGE:\n    sail <COMMAND> [ARGS]\n\nCOMMANDS:\n"
104    );
105    for (name, help) in COMMANDS {
106        let _ = writeln!(text, "    {name:<13} {help}");
107    }
108    text.push_str(
109        "\nRun `sail COMMAND --help` (or `sail help COMMAND`) for a command's options.\n",
110    );
111    text
112}
113
114/// Optional components linked into the command line.
115///
116/// The `sail` binary links the native temporal backend (ADR 0172); an
117/// embedder that passes [`Extensions::default`] gets a command line whose
118/// temporal jobs report unavailable.
119#[derive(Clone, Debug, Default)]
120pub struct Extensions {
121    /// Native temporal backend for the runtime endpoint and `sail runtime`;
122    /// `None` reports temporal jobs unavailable.
123    pub temporal: Option<std::sync::Arc<dyn sail_runtime::temporal::TemporalBackend>>,
124}
125
126/// Runs `sail` with the process's arguments and standard streams.
127#[must_use]
128pub fn run_with(extensions: &Extensions) -> ExitCode {
129    if let Some(exit) = sail_verus::adapter::dispatch() {
130        return exit;
131    }
132    let args: Vec<String> = std::env::args().skip(1).collect();
133    run(
134        &args,
135        &mut std::io::stdout(),
136        &mut std::io::stderr(),
137        extensions,
138    )
139}
140
141fn run(
142    args: &[String],
143    out: &mut dyn std::io::Write,
144    err: &mut dyn std::io::Write,
145    extensions: &Extensions,
146) -> ExitCode {
147    match args.first().map(String::as_str) {
148        None => {
149            let _ = write!(err, "{}", usage());
150            ExitCode::from(EXIT_USAGE)
151        }
152        Some("-h" | "--help" | "help") => match args.get(1) {
153            Some(command) if command != "bench" => help::print(&help::topic(&args[1..]), out)
154                .unwrap_or_else(|| {
155                    let _ = writeln!(err, "error[SAIL0002]: unknown command `{command}`\n");
156                    let _ = write!(err, "{}", usage());
157                    ExitCode::from(EXIT_USAGE)
158                }),
159            _ => {
160                let _ = write!(out, "{}", usage());
161                ExitCode::SUCCESS
162            }
163        },
164        Some(command) if command != "bench" && help::requested(&args[1..]) => {
165            help::print(&help::topic(args), out).unwrap_or_else(|| {
166                let _ = writeln!(err, "error[SAIL0002]: unknown command `{command}`\n");
167                let _ = write!(err, "{}", usage());
168                ExitCode::from(EXIT_USAGE)
169            })
170        }
171        Some("-V" | "--version") => {
172            let _ = writeln!(out, "sail {VERSION}");
173            ExitCode::SUCCESS
174        }
175        Some("serve") => serve(args.get(1..).unwrap_or_default(), err, extensions),
176        Some("_serve-jobs") => serve_jobs(args.get(1..).unwrap_or_default(), err),
177        Some("new") => new::run(&args[1..], out, err),
178        Some("verify") => verify::verify(args.get(1..).unwrap_or_default(), out, err),
179        Some("_portfolio-attempt") => {
180            verify::portfolio_attempt(args.get(1..).unwrap_or_default(), out, err)
181        }
182        Some("engine") => engine_cli::run(&args[1..], out, err),
183        Some("runtime") => runtime_cli::run(&args[1..], out, err, extensions),
184        Some("repair-check") => product_cli::repair(&args[1..], out, err),
185        Some("_prepare-worker") => preparation::worker(&args[1..], out, err),
186        Some("_serve-prepare-new") => preparation::serve_new(&args[1..], err, extensions),
187        Some("_repair-worker") => product_cli::worker(&args[1..], out, err),
188        Some("_repair-file-worker") => product_cli::standalone_worker(&args[1..], out, err),
189        Some("explain" | "baseline" | "compare" | "assurance") => {
190            product_cli::evidence(args, out, err)
191        }
192        Some("report") => ci_report::run(args.get(1..).unwrap_or_default(), out, err),
193        Some("health") => health::run(args.get(1..).unwrap_or_default(), out, err),
194        Some("watch") => watch::watch(args.get(1..).unwrap_or_default(), out, err),
195        Some("jobs") => jobs::run(args.get(1..).unwrap_or_default(), out, err),
196        Some("status") => ops::status(args.get(1..).unwrap_or_default(), out, err),
197        Some("cache") => ops::cache(args.get(1..).unwrap_or_default(), out, err),
198        Some("mcp") => mcp(args.get(1..).unwrap_or_default(), err),
199        Some("fragility") => fragility::fragility(args.get(1..).unwrap_or_default(), out, err),
200        Some("bench") => bench(args.get(1..).unwrap_or_default(), err),
201        Some(other) => {
202            let _ = writeln!(err, "error[SAIL0002]: unknown command `{other}`\n");
203            let _ = write!(err, "{}", usage());
204            ExitCode::from(EXIT_USAGE)
205        }
206    }
207}
208
209/// Runs `sail-bench`, the developer benchmark tool, with identical arguments
210/// and stdio. It is built from a Sail source checkout and is not in the
211/// release archives, so `sail --help` does not list it.
212fn bench(args: &[String], err: &mut dyn std::io::Write) -> ExitCode {
213    let result = std::env::current_exe().and_then(|exe| {
214        std::process::Command::new(exe.with_file_name("sail-bench"))
215            .args(args)
216            .status()
217    });
218    match result {
219        Ok(status) => ExitCode::from(
220            status
221                .code()
222                .and_then(|c| u8::try_from(c).ok())
223                .unwrap_or(1),
224        ),
225        Err(e) => {
226            let _ = writeln!(
227                err,
228                "error[SAIL0003]: cannot run sail-bench: {e}. `sail bench` is a developer tool that \
229                 is not in the release archives; build it from a Sail source checkout with \
230                 `cargo build --release -p sail-bench` and run it from there (or install it next to sail)"
231            );
232            ExitCode::from(2)
233        }
234    }
235}
236
237/// `sail mcp`: the MCP server on stdin and stdout (ADR 0016). Tool calls
238/// run this same `sail` binary. Results are recorded under
239/// `<cache>/mcp`, where `<cache>` is `$SAIL_CACHE_DIR` or `~/.cache/sail`.
240fn mcp(args: &[String], err: &mut dyn std::io::Write) -> ExitCode {
241    if let Some(arg) = args.first() {
242        let _ = writeln!(
243            err,
244            "error[SAIL0002]: `sail mcp` takes no arguments (got `{arg}`); it speaks MCP on stdin and stdout"
245        );
246        return ExitCode::from(EXIT_USAGE);
247    }
248    let (sail, cwd) = match (std::env::current_exe(), std::env::current_dir()) {
249        (Ok(s), Ok(c)) => (s, c),
250        (Err(e), _) | (_, Err(e)) => {
251            let _ = writeln!(err, "error[SAIL0301]: sail mcp cannot start: {e}");
252            return ExitCode::from(EXIT_USAGE);
253        }
254    };
255    let config = sail_mcp::Config {
256        sail,
257        store_dir: sail_verus::cache_dir().ok().map(|c| c.join("mcp")),
258        cwd,
259    };
260    let stdin = std::io::stdin();
261    match sail_mcp::serve_with_job_clients(config, stdin.lock(), std::io::stdout()) {
262        Ok(()) => ExitCode::SUCCESS,
263        Err(e) => {
264            let _ = writeln!(err, "error[SAIL0302]: sail mcp: cannot read stdin: {e}");
265            ExitCode::from(1)
266        }
267    }
268}
269
270/// The default daemon socket: `<cache>/daemon-v<protocol>-workspace-v2-proof-v1.sock`, so clients
271/// of one protocol version never reach a daemon of another.
272pub(crate) fn default_socket(cache: &std::path::Path) -> std::path::PathBuf {
273    sail_api::jobs::default_cache_socket(cache)
274}
275
276/// Reads a whole number from the environment variable `name`.
277fn env_number(name: &str) -> Result<Option<u64>, String> {
278    match std::env::var(name) {
279        Ok(v) if !v.is_empty() => v
280            .trim()
281            .parse()
282            .map(Some)
283            .map_err(|_| format!("{name} must be a whole number, not `{v}`")),
284        _ => Ok(None),
285    }
286}
287
288/// The socket, cache root and daemon settings for
289/// `sail serve [--socket PATH] [--cache DIR] [--memory-bytes N]
290/// [--idle-timeout SECS] [--shared DIR] [--shared-timeout-ms MS]`, which runs the
291/// daemon in the foreground (ADR 0011, ADR 0015). Defaults:
292/// `<cache>/daemon-v<N>-workspace-v2-proof-v1.sock` and `<cache>/results`, where `<cache>` is
293/// `$SAIL_CACHE_DIR` or `~/.cache/sail`; a 256 MiB memory tier
294/// (`$SAIL_DAEMON_MEMORY_BYTES`); a 30-minute idle timeout
295/// (`$SAIL_DAEMON_IDLE_TIMEOUT`, seconds, 0 for never); no shared tier
296/// (`$SAIL_SHARED_STORE`), looked up with a 250 ms timeout
297/// (`$SAIL_SHARED_TIMEOUT_MS`) and trusting the keys in
298/// `<cache root>/trust/*.pub` (ADR 0017). The log is
299/// `<cache root>/daemon.log`. SIGINT, SIGTERM and SIGHUP stop it cleanly.
300#[cfg(unix)]
301fn serve_config(
302    args: &[String],
303) -> Result<(std::path::PathBuf, std::path::PathBuf, sail_daemon::Config), String> {
304    let cache = sail_verus::cache_dir().map_err(|e| e.to_string())?;
305    let mut config = sail_daemon::Config {
306        idle_timeout: Some(sail_daemon::DEFAULT_IDLE_TIMEOUT),
307        ..sail_daemon::Config::default()
308    };
309    let mut shared_store = std::env::var_os("SAIL_SHARED_STORE")
310        .filter(|v| !v.is_empty())
311        .map(std::path::PathBuf::from);
312    let mut shared_timeout = sail_daemon::DEFAULT_SHARED_TIMEOUT;
313    if let Some(n) = env_number("SAIL_DAEMON_MEMORY_BYTES")? {
314        config.memory_bytes = n;
315    }
316    if let Some(n) = env_number("SAIL_DAEMON_IDLE_TIMEOUT")? {
317        config.idle_timeout = (n > 0).then(|| std::time::Duration::from_secs(n));
318    }
319    if let Some(n) = env_number("SAIL_SHARED_TIMEOUT_MS")? {
320        shared_timeout = std::time::Duration::from_millis(n);
321    }
322    // Fault injection only (ADR 0015): slow every disk write.
323    if let Some(n) = env_number("SAIL_DAEMON_WRITE_DELAY_MS")? {
324        config.write_delay = (n > 0).then(|| std::time::Duration::from_millis(n));
325    }
326    let (mut socket, mut root) = (default_socket(&cache), cache.join("results"));
327    let mut it = args.iter();
328    while let Some(arg) = it.next() {
329        let value = it.next().ok_or_else(|| format!("{arg} needs a value"))?;
330        match arg.as_str() {
331            "--socket" => socket = value.into(),
332            "--cache" => root = value.into(),
333            "--memory-bytes" => {
334                config.memory_bytes =
335                    ops::parse_bytes(value).ok_or_else(|| format!("bad byte count `{value}`"))?;
336            }
337            "--idle-timeout" => {
338                let n = value
339                    .parse::<u64>()
340                    .map_err(|_| format!("bad idle timeout `{value}` (seconds)"))?;
341                config.idle_timeout = (n > 0).then(|| std::time::Duration::from_secs(n));
342            }
343            "--shared" => shared_store = Some(value.into()),
344            "--shared-timeout-ms" => {
345                let n = value
346                    .parse::<u64>()
347                    .map_err(|_| format!("bad shared timeout `{value}` (ms)"))?;
348                shared_timeout = std::time::Duration::from_millis(n);
349            }
350            _ => return Err(format!("unknown argument `{arg}`")),
351        }
352    }
353    if runtime_cli::temporal_cache_override(&cache, &root.join("runtime")).is_some() {
354        // The default socket and solver store can both create their parent
355        // before a temporal job arrives. Create it privately from the outset.
356        // DirBuilder leaves an existing cache owner's permissions untouched.
357        use std::os::unix::fs::DirBuilderExt as _;
358        std::fs::DirBuilder::new()
359            .recursive(true)
360            .mode(0o700)
361            .create(&cache)
362            .map_err(|e| format!("cannot create cache directory {}: {e}", cache.display()))?;
363    }
364    config.log = Some(root.join("daemon.log"));
365    config.bundled = sail_daemon::BundledConfig::discover();
366    config.shared = shared_store.map(|store| sail_daemon::SharedConfig {
367        store,
368        trust_dir: sail_cache::shared::trust_dir(&root),
369        timeout: shared_timeout,
370        backoff: sail_daemon::DEFAULT_SHARED_BACKOFF,
371    });
372    Ok((socket, root, config))
373}
374
375#[cfg(unix)]
376fn serve(args: &[String], err: &mut dyn std::io::Write, extensions: &Extensions) -> ExitCode {
377    serve_prepared(args, err, extensions, None)
378}
379
380#[cfg(unix)]
381fn serve_prepared(
382    args: &[String],
383    err: &mut dyn std::io::Write,
384    extensions: &Extensions,
385    preparation: Option<sail_api::preparation::Submission>,
386) -> ExitCode {
387    let (socket, root, config) = match serve_config(args) {
388        Ok(c) => c,
389        Err(e) => {
390            // Errors that carry their own code (the cache directory) keep it.
391            let code = if e.starts_with("error[") {
392                ""
393            } else {
394                "error[SAIL0002]: "
395            };
396            let _ = writeln!(err, "{code}{e}");
397            return ExitCode::from(EXIT_USAGE);
398        }
399    };
400    let stats = std::sync::Arc::new(sail_daemon::Stats::default());
401    let server = match sail_daemon::bind(&socket, &root, stats, &config) {
402        Ok(s) => s,
403        Err(e) => {
404            let _ = writeln!(
405                err,
406                "error[SAIL0003]: cannot serve on {}: {e}",
407                socket.display()
408            );
409            return ExitCode::from(1);
410        }
411    };
412    // Only this foreground line goes to stderr; `sail verify` discards it.
413    let _ = writeln!(
414        err,
415        "sail daemon: socket {}, cache {}, log {}",
416        socket.display(),
417        root.display(),
418        root.join("daemon.log").display()
419    );
420    let executable = match std::env::current_exe() {
421        Ok(path) => path,
422        Err(e) => {
423            let _ = writeln!(err, "error[SAIL0800]: cannot locate job worker: {e}");
424            return ExitCode::from(2);
425        }
426    };
427    let job_server = match sail_daemon::jobs::bind(
428        &sail_api::jobs::socket_path(&socket),
429        &root.join("projects/jobs"),
430        &executable,
431    )
432    .and_then(configure_project_cache)
433    .and_then(|server| {
434        if let Some(preparation) = preparation {
435            server.enqueue_preparation(preparation)?;
436        }
437        server.spawn()
438    }) {
439        Ok(handle) => handle,
440        Err(e) => {
441            let _ = writeln!(err, "error[SAIL0800]: cannot start job service: {e}");
442            return ExitCode::from(2);
443        }
444    };
445    let mut job_server = job_server;
446    let mut runtime_service = match runtime_cli::start_service(
447        &socket,
448        root.join("runtime"),
449        job_server.activity(),
450        extensions,
451    ) {
452        Ok(handle) => handle,
453        Err(error) => {
454            job_server.shutdown();
455            let _ = writeln!(
456                err,
457                "error[SAIL6201]: cannot start runtime endpoint: {error}"
458            );
459            return ExitCode::from(2);
460        }
461    };
462    let activity = job_server.activity();
463    let handle = server.handle();
464    let signals = signal_hook::iterator::Signals::new([
465        signal_hook::consts::SIGINT,
466        signal_hook::consts::SIGTERM,
467        signal_hook::consts::SIGHUP,
468    ]);
469    if let Ok(mut signals) = signals {
470        let _ = std::thread::Builder::new()
471            .name("sail-signals".to_owned())
472            .spawn(move || {
473                if signals.forever().next().is_some() {
474                    handle.shutdown();
475                }
476            });
477    }
478    let result = server.run_with_activity(activity);
479    runtime_service.shutdown();
480    job_server.shutdown();
481    match result {
482        Ok(()) => ExitCode::SUCCESS,
483        Err(e) => {
484            let _ = writeln!(err, "error[SAIL0003]: daemon failed: {e}");
485            ExitCode::from(1)
486        }
487    }
488}
489
490#[cfg(unix)]
491fn configure_project_cache(
492    server: sail_daemon::jobs::JobServer,
493) -> std::io::Result<sail_daemon::jobs::JobServer> {
494    let cache =
495        sail_verus::cache_dir().map_err(|error| std::io::Error::other(error.to_string()))?;
496    server.with_project_cache(&cache)
497}
498
499/// A jobs-only sidecar for an explicitly selected, older cache daemon.
500#[cfg(unix)]
501fn serve_jobs(args: &[String], err: &mut dyn std::io::Write) -> ExitCode {
502    use std::sync::atomic::{AtomicBool, Ordering};
503    let setup = (|| {
504        let (socket, root, config) = serve_config(args)?;
505        let executable = std::env::current_exe().map_err(|error| error.to_string())?;
506        let jobs = sail_daemon::jobs::bind(
507            &sail_api::jobs::socket_path(&socket),
508            &root.join("projects/jobs"),
509            &executable,
510        )
511        .and_then(configure_project_cache)
512        .and_then(sail_daemon::jobs::JobServer::spawn)
513        .map_err(|error| error.to_string())?;
514        Ok::<_, String>((jobs, config.idle_timeout))
515    })();
516    let (mut jobs, timeout) = match setup {
517        Ok(setup) => setup,
518        Err(error) => {
519            let _ = writeln!(err, "error[SAIL0800]: cannot start job sidecar: {error}");
520            return ExitCode::from(2);
521        }
522    };
523    let stopped = std::sync::Arc::new(AtomicBool::new(false));
524    for signal in [
525        signal_hook::consts::SIGINT,
526        signal_hook::consts::SIGTERM,
527        signal_hook::consts::SIGHUP,
528    ] {
529        if let Err(error) = signal_hook::flag::register(signal, stopped.clone()) {
530            let _ = writeln!(
531                err,
532                "error[SAIL0800]: cannot register job shutdown: {error}"
533            );
534            jobs.shutdown();
535            return ExitCode::from(2);
536        }
537    }
538    let activity = jobs.activity();
539    let mut idle_since = std::time::Instant::now();
540    while !stopped.load(Ordering::Relaxed) {
541        if activity.load(Ordering::Relaxed) > 0 {
542            idle_since = std::time::Instant::now();
543        } else if timeout.is_some_and(|timeout| idle_since.elapsed() >= timeout) {
544            break;
545        }
546        std::thread::sleep(std::time::Duration::from_millis(100));
547    }
548    jobs.shutdown();
549    ExitCode::SUCCESS
550}
551
552#[cfg(not(unix))]
553fn serve_jobs(_args: &[String], err: &mut dyn std::io::Write) -> ExitCode {
554    let _ = writeln!(err, "error[SAIL0800]: local jobs need Unix sockets");
555    ExitCode::from(2)
556}
557
558#[cfg(not(unix))]
559fn serve(_args: &[String], err: &mut dyn std::io::Write, _: &Extensions) -> ExitCode {
560    let _ = writeln!(err, "error[SAIL0001]: `sail serve` needs Unix sockets");
561    ExitCode::from(EXIT_UNIMPLEMENTED)
562}