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