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