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