Skip to main content

dive_cli/
lib.rs

1//! Shared command dispatch for the `dive` and `tlc` binaries.
2//!
3//! Native commands retain their own defaults. The checking-only TLC adapter
4//! selects TLC evaluation and accepts common checking spellings through
5//! `dive tlc` or an executable named `tlc`. Unimplemented commands and features
6//! return named refusals.
7#![forbid(unsafe_code)]
8
9mod debug;
10mod explain;
11mod help;
12mod tlc;
13mod translate;
14
15use std::io::Write as _;
16use std::process::ExitCode;
17
18/// Implemented commands advertised in help, each with a one-line description.
19const COMMANDS: &[(&str, &str)] = &[
20    ("check", "Check a model exhaustively"),
21    ("worker", "Serve safety work for a distributed `dive check`"),
22    ("tlc", "Check a model with TLC's command-line arguments"),
23    ("dfid", "Check a model by bounded iterative deepening"),
24    ("simulate", "Explore random bounded behaviors"),
25    ("parse", "Parse a specification or configuration"),
26    ("analyze", "Resolve modules and analyze a specification"),
27    ("translate", "Translate PlusCal into TLA+"),
28    ("validate-trace", "Validate a counterexample independently"),
29    ("explain", "Explain an error code"),
30    (
31        "debug",
32        "Debug a safety check over the Debug Adapter Protocol (experimental)",
33    ),
34];
35
36/// What `--lncheck final --lasso short` adds to Core's refusal of a model's
37/// temporal properties. A model without temporal properties is checked as
38/// usual.
39pub(crate) const FINAL_SHORT_REFUSAL: &str =
40    "bounded final checking (--lncheck final --lasso short) is not implemented on Core";
41
42/// The command list of `dive --help`: names in a column, then descriptions.
43fn command_list() -> String {
44    let width = COMMANDS
45        .iter()
46        .map(|(name, _)| name.len())
47        .max()
48        .unwrap_or(0);
49    COMMANDS
50        .iter()
51        .map(|(name, description)| format!("{name:width$}  {description}"))
52        .collect::<Vec<_>>()
53        .join("\n    ")
54}
55
56/// Exit code when the input is rejected (`parse`: syntax or cfg errors;
57/// `analyze`: any error SANY would report).
58const EXIT_REJECTED: u8 = 1;
59/// Exit code for a malformed command line or unreadable input.
60const EXIT_USAGE: u8 = 2;
61/// Exit code for a request that `dive` recognises but does not implement.
62const EXIT_UNSUPPORTED: u8 = 3;
63
64/// Validates an `--engine` value. Core is the only engine: the earlier
65/// `auto` and `reference` values name engines that no longer exist and are
66/// rejected with an explanation. `--engine core` is still accepted, and no
67/// longer advertised.
68fn engine_option(name: Option<&str>) -> Result<(), String> {
69    match name {
70        Some("core") => Ok(()),
71        Some("auto") => Err(
72            "--engine auto was removed: Core is the only engine and refuses by \
73             name what it does not implement"
74                .to_owned(),
75        ),
76        Some("reference") => Err(
77            "--engine reference was removed: the reference engine is no longer part of \
78             dive check, simulate, dfid or tlc; Core refuses by name what it does not implement"
79                .to_owned(),
80        ),
81        _ => Err("--engine expects `core`, the only engine".to_owned()),
82    }
83}
84
85/// Validates `DIVE_ENGINE`, which may be unset, empty or `core`.
86fn engine_from_env() -> Result<(), String> {
87    match std::env::var("DIVE_ENGINE").ok().as_deref() {
88        None | Some("") => Ok(()),
89        Some(name) => engine_option(Some(name))
90            .map_err(|message| message.replacen("--engine", "DIVE_ENGINE", 1)),
91    }
92}
93
94fn usage() -> String {
95    format!(
96        "dive {}\nDeterministic Invariant Verification Engine\n\nUSAGE:\n    dive <COMMAND> [ARGS]\n\nCOMMANDS:\n    {}\n\n    dive parse [FILE.tla] [--config FILE.cfg] [--output human|json] [--cst]\n    dive translate <FILE.tla> [--compat=tlc] [--rewrite|--write] [--checksums tla|full] [--replace-modified] [--ast|-writeAST] [--output human|json] [--library-path DIR]... [--module-path DIR]...\n    dive analyze <FILE.tla> [--output human|json] [--library-path DIR]... [--module-path DIR]...\n    dive debug <FILE.tla> [--stdio|--listen 127.0.0.1:PORT] [--compat=tlc]\n    dive explain <CODE> [--output human|json]\n    dive tlc [OPTIONS] SPEC[.tla] (TLC checking arguments; see dive tlc -help)\n    dive check <FILE.tla> [--config FILE.cfg] [--compat=tlc] [--exit-codes native|tlc] [--store fp|exact] [--seed N] [--fp N]\n               [--workers N|auto] [--sequential] [-deadlock] [--action-composition off|tla]\n               [--symmetry-liveness unreduced|refuse|tlc]\n               [--frontier-memory-bytes N] [--frontier-directory DIR] [--candidate-memory-bytes N] [--candidate-directory DIR] [--store-compact-bytes N] [--output human|json]\n               [--time-limit DURATION|none] [--max-memory BYTES|auto|none]
97               [--max-states N|none] [--max-depth N|none]
98               [--predecessor-memory-bytes N] [--predecessor-directory DIR]\n               [--seen-disk-entries N] [--seen-directory DIR] [--seen-key-bytes N]\n               [--seen-probe-steps N] [--seen-summary-pairs N]
99               [--checkpoint FILE --checkpoint-after-levels N | --recover FILE]
100               [--checkpoint-counters tlc|retain]
101               [--distributed-worker IP:port]... [--worker-key FILE] [--worker-timeout-ms N] [--distributed-retries N]
102               [--core-sample N] [--library-path DIR]... [--module-path DIR]...\n    dive worker <FILE.tla> --seed N --fp N --worker-key FILE [--listen IP:port] [--worker-timeout-ms N] [--worker-max-units N]\n                [--config FILE.cfg] [--compat=tlc] [--store fp|exact] [--output human|json]\n    dive simulate <FILE.tla> --traces N [--generate] [--exit-codes native|tlc] [--depth N] [--seed N] [--aril N] [--stats none|basic] [--time-limit DURATION|none] [--max-memory BYTES|auto|none] [--compat=tlc] [--output human|json]\n    dive dfid <FILE.tla> --max-level N [--compat=tlc] [--seed N] [--worker-seeds S,...] [--time-limit DURATION|none] [--max-memory BYTES|auto|none] [--output human|json]\n    dive validate-trace <FILE.tla> [--trace TRACE.json] [--inputs RUN.json] [--config FILE.cfg] [--claim ENDING] [--sample]\n               [--compat=tlc] [--symmetry-liveness unreduced|refuse|tlc] [--seed N] [--fp N] [-deadlock] [--output human|json] [--library-path DIR]... [--module-path DIR]...\n\n    Eligible ordinary temporal checks use deterministic completed-level checks in the dive
103    profile and final checking in the TLC profile.
104    dive check uses TLC process statuses by default, independently of semantic profile.\n    --exit-codes native retains: 0 no error, 1 rejected input, 10 property violated, 11 deadlock,\n    12 assumption, 13 evaluation error. Both conventions keep 2 usage, 3 unsupported/resource\n    limit, 4 internal error and 5 stopped by a run budget (no verdict).\n    --time-limit defaults to none in both profiles, as in TLC; --max-memory defaults to\n    half of physical memory (auto) in both. --compat=tlc (or DIVE_COMPAT=tlc) selects existing TLC-compatible behavior; known gaps are documented.\n    The compiled Core is the engine of check, simulate, dfid and tlc; what it does not\n    implement is a named refusal, never a fallback. --core-sample N\n    also compares the successors of N sampled states with an independent evaluator's, in the JSON\n    report (core.sample); it is diagnostic and changes no result.
105    Options Core does not implement are not listed; they still parse and refuse by name\n    (exit 3).\n",
106        env!("CARGO_PKG_VERSION"),
107        command_list()
108    )
109}
110
111/// Parsed `dive parse` arguments.
112#[derive(Default)]
113struct ParseArgs<'a> {
114    file: Option<&'a str>,
115    config: Option<&'a str>,
116    json: bool,
117    cst: bool,
118}
119
120fn parse_args<'a>(args: &'a [String], err: &mut impl std::io::Write) -> Option<ParseArgs<'a>> {
121    let mut p = ParseArgs::default();
122    let mut it = args.iter();
123    while let Some(a) = it.next() {
124        match a.as_str() {
125            "--output" => match it.next().map(String::as_str) {
126                Some("json") => p.json = true,
127                Some("human") => p.json = false,
128                other => {
129                    let _ = writeln!(
130                        err,
131                        "error: --output expects `human` or `json`, got {}",
132                        other.unwrap_or("nothing")
133                    );
134                    return None;
135                }
136            },
137            "--config" => {
138                let Some(c) = it.next() else {
139                    let _ = writeln!(err, "error: --config expects a .cfg file");
140                    return None;
141                };
142                if p.config.replace(c).is_some() {
143                    let _ = writeln!(err, "error: --config given twice");
144                    return None;
145                }
146            }
147            "--cst" => p.cst = true,
148            s if s.starts_with('-') => {
149                let _ = writeln!(err, "error: unknown option `{s}` for `dive parse`");
150                return None;
151            }
152            s => {
153                if p.file.replace(s).is_some() {
154                    let _ = writeln!(err, "error: `dive parse` takes one file");
155                    return None;
156                }
157            }
158        }
159    }
160    if p.file.is_none() && p.config.is_none() {
161        let _ = writeln!(
162            err,
163            "error: `dive parse` needs a file or --config\n\n{}",
164            usage()
165        );
166        return None;
167    }
168    Some(p)
169}
170
171/// `dive parse [file] [--config cfg] [--output human|json] [--cst]`.
172fn parse_command(
173    args: &[String],
174    out: &mut impl std::io::Write,
175    err: &mut impl std::io::Write,
176) -> ExitCode {
177    let Some(p) = parse_args(args, err) else {
178        return ExitCode::from(EXIT_USAGE);
179    };
180    let report = match p
181        .file
182        .map(|f| dive_api::parse_file(std::path::Path::new(f)))
183    {
184        None => None,
185        Some(Ok(r)) => Some(r),
186        Some(Err(e)) => {
187            let _ = writeln!(err, "error: {e}");
188            return ExitCode::from(EXIT_USAGE);
189        }
190    };
191    let config = match p
192        .config
193        .map(|c| dive_api::parse_config_file(std::path::Path::new(c)))
194    {
195        None => None,
196        Some(Ok(r)) => Some(r),
197        Some(Err(e @ dive_api::ApiError::Unsupported { .. })) => {
198            let _ = writeln!(err, "{e}; no result produced");
199            return ExitCode::from(EXIT_UNSUPPORTED);
200        }
201        Some(Err(e)) => {
202            let _ = writeln!(err, "error: {e}");
203            return ExitCode::from(EXIT_USAGE);
204        }
205    };
206    let accepted = report.as_ref().is_none_or(dive_api::ParseReport::accepted)
207        && config.as_ref().is_none_or(dive_api::ConfigReport::accepted);
208    if p.json {
209        let mut v = match &report {
210            Some(r) => r.to_json(p.cst),
211            None => serde_json::json!({
212                "schema_version": dive_api::PARSE_SCHEMA_VERSION,
213                "command": "parse",
214                "file": null,
215                "module": null,
216                "modules": [],
217                "diagnostics": [],
218            }),
219        };
220        if let Some(obj) = v.as_object_mut() {
221            obj.insert("accepted".to_owned(), serde_json::Value::Bool(accepted));
222            if let Some(c) = &config {
223                obj.insert("config".to_owned(), c.to_json());
224            }
225        }
226        let _ = writeln!(out, "{v}");
227    } else {
228        if let Some(r) = &report {
229            let _ = write!(err, "{}", r.render_human());
230            if p.cst {
231                let _ = write!(out, "{:#?}", r.parse().syntax());
232            }
233            if r.accepted() {
234                let _ = writeln!(
235                    out,
236                    "ok: {} parsed ({})",
237                    p.file.unwrap_or_default(),
238                    r.modules().join(", ")
239                );
240            }
241        }
242        if let Some(c) = &config {
243            let _ = write!(err, "{}", c.render_human());
244            if let Some(m) = c.config() {
245                let _ = writeln!(
246                    out,
247                    "ok: {} read ({} constants, {} invariants, {} properties)",
248                    p.config.unwrap_or_default(),
249                    m.constants.len(),
250                    m.invariants.len(),
251                    m.properties.len()
252                );
253            }
254        }
255    }
256    if accepted {
257        ExitCode::SUCCESS
258    } else {
259        ExitCode::from(EXIT_REJECTED)
260    }
261}
262
263/// `dive analyze <file> [--output human|json] [--library-path DIR]... [--module-path DIR]...`.
264///
265/// SANY-equivalent semantic analysis of the specification rooted at the file.
266/// Modules are found in the file's directory, the library paths, the standard
267/// modules, then the module paths.
268fn analyze_command(
269    args: &[String],
270    out: &mut impl std::io::Write,
271    err: &mut impl std::io::Write,
272) -> ExitCode {
273    let mut file: Option<&str> = None;
274    let mut json = false;
275    let mut opts = dive_api::AnalyzeOptions::default();
276    let mut it = args.iter();
277    while let Some(a) = it.next() {
278        match a.as_str() {
279            "--output" => match it.next().map(String::as_str) {
280                Some("json") => json = true,
281                Some("human") => json = false,
282                other => {
283                    let _ = writeln!(
284                        err,
285                        "error: --output expects `human` or `json`, got {}",
286                        other.unwrap_or("nothing")
287                    );
288                    return ExitCode::from(EXIT_USAGE);
289                }
290            },
291            "--library-path" | "--module-path" => {
292                let Some(dir) = it.next() else {
293                    let _ = writeln!(err, "error: {a} expects a directory");
294                    return ExitCode::from(EXIT_USAGE);
295                };
296                if a == "--library-path" {
297                    opts.library_paths.push(dir.into());
298                } else {
299                    opts.after_standard.push(dir.into());
300                }
301            }
302            s if s.starts_with('-') => {
303                let _ = writeln!(err, "error: unknown option `{s}` for `dive analyze`");
304                return ExitCode::from(EXIT_USAGE);
305            }
306            s => {
307                if file.replace(s).is_some() {
308                    let _ = writeln!(err, "error: `dive analyze` takes one file");
309                    return ExitCode::from(EXIT_USAGE);
310                }
311            }
312        }
313    }
314    let Some(file) = file else {
315        let _ = writeln!(err, "error: `dive analyze` needs a file\n\n{}", usage());
316        return ExitCode::from(EXIT_USAGE);
317    };
318    let report = match dive_api::analyze_file(std::path::Path::new(file), &opts) {
319        Ok(r) => r,
320        Err(e) => {
321            let _ = writeln!(err, "error: {e}");
322            return ExitCode::from(EXIT_USAGE);
323        }
324    };
325    if json {
326        let _ = writeln!(out, "{}", report.to_json());
327    } else {
328        let _ = write!(err, "{}", report.render_human());
329        if report.accepted() {
330            let _ = writeln!(
331                out,
332                "ok: {} analysed ({})",
333                file,
334                report.modules().join(", ")
335            );
336        }
337    }
338    if report.accepted() {
339        ExitCode::SUCCESS
340    } else {
341        ExitCode::from(EXIT_REJECTED)
342    }
343}
344
345/// Parses a numeric option value.
346fn number<T: std::str::FromStr>(
347    flag: &str,
348    v: Option<&String>,
349    err: &mut impl std::io::Write,
350) -> Option<T> {
351    let parsed = v.and_then(|v| v.parse().ok());
352    if parsed.is_none() {
353        let _ = writeln!(err, "error: {flag} expects a number");
354    }
355    parsed
356}
357
358/// `--time-limit`: `none`, or a positive duration in seconds by default, or
359/// with a unit (`ms`, `s`, `m`, `h`).
360fn time_limit(text: &str) -> Option<dive_api::BudgetSetting<std::time::Duration>> {
361    if text == "none" {
362        return Some(dive_api::BudgetSetting::Unlimited);
363    }
364    let split = text
365        .find(|c: char| !c.is_ascii_digit())
366        .unwrap_or(text.len());
367    let (digits, unit) = text.split_at(split);
368    let n: u64 = digits.parse().ok().filter(|n| *n > 0)?;
369    let duration = match unit {
370        "ms" => std::time::Duration::from_millis(n),
371        "" | "s" => std::time::Duration::from_secs(n),
372        "m" => std::time::Duration::from_secs(n.checked_mul(60)?),
373        "h" => std::time::Duration::from_secs(n.checked_mul(3600)?),
374        _ => return None,
375    };
376    Some(dive_api::BudgetSetting::Explicit(duration))
377}
378
379/// `--max-memory`: `auto`, `none`, or a positive byte count, optionally with a
380/// binary unit as for the JVM's `-Xmx` (`k`, `m`, `g`, `t`, either case).
381fn max_memory(text: &str) -> Option<dive_api::BudgetSetting<u64>> {
382    match text {
383        "auto" => return Some(dive_api::BudgetSetting::Default),
384        "none" => return Some(dive_api::BudgetSetting::Unlimited),
385        _ => {}
386    }
387    let split = text
388        .find(|c: char| !c.is_ascii_digit())
389        .unwrap_or(text.len());
390    let (digits, unit) = text.split_at(split);
391    let n: u64 = digits.parse().ok().filter(|n| *n > 0)?;
392    let shift = match unit.to_ascii_lowercase().as_str() {
393        "" => 0,
394        "k" => 10,
395        "m" => 20,
396        "g" => 30,
397        "t" => 40,
398        _ => return None,
399    };
400    n.checked_mul(1 << shift)
401        .map(dive_api::BudgetSetting::Explicit)
402}
403
404/// Search limits admit zero and use `none` for TLC-equivalent unlimited search.
405fn search_limit(text: &str) -> Result<Option<u64>, std::num::ParseIntError> {
406    if text == "none" {
407        Ok(None)
408    } else {
409        text.parse().map(Some)
410    }
411}
412
413/// `dive check <file> [options]`: safety model checking (see `usage`).
414#[allow(clippy::too_many_lines, reason = "one flag per arm")]
415fn check_command(
416    args: &[String],
417    out: &mut impl std::io::Write,
418    err: &mut impl std::io::Write,
419) -> ExitCode {
420    check_command_mode(args, out, err, false)
421}
422
423#[allow(
424    clippy::too_many_lines,
425    reason = "one shared checker/worker option parser preserves source and policy flags"
426)]
427fn check_command_mode(
428    args: &[String],
429    out: &mut impl std::io::Write,
430    err: &mut impl std::io::Write,
431    worker_mode: bool,
432) -> ExitCode {
433    let mut req = dive_api::CheckRequest {
434        compat_tlc: std::env::var("DIVE_COMPAT").is_ok_and(|v| v == "tlc"),
435        // Test-only (hidden): chaos scheduling for determinism testing.
436        chaos: std::env::var("DIVE_CHAOS")
437            .ok()
438            .and_then(|v| v.parse().ok()),
439        ..dive_api::CheckRequest::default()
440    };
441    let mut seen_policy = dive_api::SeenOptions::default();
442    let mut host_access_given = false;
443    let mut seen_entries = false;
444    let mut seen_extra = false;
445    let mut checkpoint_path: Option<std::path::PathBuf> = None;
446    let mut recover_path: Option<std::path::PathBuf> = None;
447    let mut checkpoint_after: Option<u64> = None;
448    let mut checkpoint_counters = dive_api::checkpoint::Counters::Tlc;
449    let mut counters_given = false;
450    let mut final_check = false;
451    let mut short_lasso = false;
452    let mut file: Option<&str> = None;
453    let mut json = false;
454    let mut remote_workers = Vec::new();
455    let mut worker_key: Option<std::path::PathBuf> = None;
456    let mut worker_listen = "127.0.0.1:0".parse::<std::net::SocketAddr>().ok();
457    let mut worker_timeout = std::time::Duration::from_secs(5);
458    let mut worker_timeout_given = false;
459    let mut worker_retries = 2;
460    let mut worker_retries_given = false;
461    let mut worker_max_units = None;
462    let mut exit_convention = dive_api::ExitConvention::Tlc;
463    if !worker_mode && let Err(message) = engine_from_env() {
464        let _ = writeln!(err, "error: {message}");
465        return ExitCode::from(EXIT_USAGE);
466    }
467    let usage_error = |err: &mut dyn std::io::Write, m: &str| {
468        let _ = writeln!(err, "error: {m}");
469        ExitCode::from(EXIT_USAGE)
470    };
471    let mut it = args.iter();
472    while let Some(a) = it.next() {
473        let (flag, inline) = match a.split_once('=') {
474            Some((f, v)) if f.starts_with('-') => (f, Some(v.to_owned())),
475            _ => (a.as_str(), None),
476        };
477        let mut value = || inline.clone().or_else(|| it.next().cloned());
478        match flag {
479            "--distributed-worker" if !worker_mode => match value()
480                .as_deref()
481                .and_then(|s| s.parse::<std::net::SocketAddr>().ok())
482            {
483                Some(address) => remote_workers.push(address),
484                None => {
485                    return usage_error(err, "--distributed-worker expects an IP:port endpoint");
486                }
487            },
488            "--worker-key" => match value() {
489                Some(path) => worker_key = Some(path.into()),
490                None => return usage_error(err, "--worker-key expects a local key-file path"),
491            },
492            "--listen" if worker_mode => match value()
493                .as_deref()
494                .and_then(|s| s.parse::<std::net::SocketAddr>().ok())
495            {
496                Some(address) => worker_listen = Some(address),
497                None => return usage_error(err, "--listen expects an IP:port endpoint"),
498            },
499            "--worker-timeout-ms" => match value()
500                .as_deref()
501                .and_then(|s| s.parse::<u64>().ok())
502                .filter(|ms| (1..=60_000).contains(ms))
503            {
504                Some(ms) => {
505                    worker_timeout_given = true;
506                    worker_timeout = std::time::Duration::from_millis(ms);
507                }
508                None => {
509                    return usage_error(
510                        err,
511                        "--worker-timeout-ms expects milliseconds in 1..60000",
512                    );
513                }
514            },
515            "--distributed-retries" if !worker_mode => {
516                match value()
517                    .as_deref()
518                    .and_then(|s| s.parse::<u8>().ok())
519                    .filter(|n| *n <= 8)
520                {
521                    Some(n) => {
522                        worker_retries_given = true;
523                        worker_retries = n;
524                    }
525                    None => return usage_error(err, "--distributed-retries expects 0..8"),
526                }
527            }
528            "--worker-max-units" if worker_mode => {
529                match value().as_deref().and_then(|s| s.parse::<u64>().ok()) {
530                    Some(n) => worker_max_units = Some(n),
531                    None => return usage_error(err, "--worker-max-units expects a work count"),
532                }
533            }
534            "--output" => match value().as_deref() {
535                Some("json") => json = true,
536                Some("human") => json = false,
537                _ => return usage_error(err, "--output expects `human` or `json`"),
538            },
539            "--exit-codes" => match value().as_deref() {
540                Some("native") => exit_convention = dive_api::ExitConvention::Native,
541                Some("tlc") => exit_convention = dive_api::ExitConvention::Tlc,
542                _ => return usage_error(err, "--exit-codes expects `native` or `tlc`"),
543            },
544            "--compat" => match value().as_deref() {
545                Some("tlc") => req.compat_tlc = true,
546                Some("dive" | "none") => req.compat_tlc = false,
547                _ => return usage_error(err, "--compat expects `tlc`"),
548            },
549            "--config" | "-config" => match value() {
550                Some(c) => req.config = Some(c.into()),
551                None => return usage_error(err, "--config expects a .cfg file"),
552            },
553            "--lncheck" => match value().as_deref() {
554                Some("final") => final_check = true,
555                _ => {
556                    return usage_error(
557                        err,
558                        "--lncheck currently supports explicit `final` with --lasso short",
559                    );
560                }
561            },
562            "--lasso" => match value().as_deref() {
563                Some("short") => short_lasso = true,
564                Some("tlc") => {
565                    return usage_error(
566                        err,
567                        "--lasso tlc is not supported: dive does not reproduce TLC's lasso choice; use --lasso short (an independently validated counterexample)",
568                    );
569                }
570                _ => return usage_error(err, "--lasso expects `short` with --lncheck final"),
571            },
572            "--store" => match value().as_deref() {
573                Some("exact") => req.store = dive_api::Store::Exact,
574                Some("fp" | "fingerprint") => req.store = dive_api::Store::Fingerprint,
575                _ => return usage_error(err, "--store expects `fp` or `exact`"),
576            },
577            "--allow-io" => {
578                if host_access_given {
579                    return usage_error(err, "--allow-io given twice");
580                }
581                let Some(text) = value() else {
582                    return usage_error(err, "--allow-io expects categories");
583                };
584                match dive_api::HostAccess::parse(&text) {
585                    Ok(access) => req.host_access = access,
586                    Err(message) => return usage_error(err, message),
587                }
588                host_access_given = true;
589            }
590            "--seed" | "-seed" => {
591                let v = value();
592                match v.as_deref().and_then(dive_api::parse_seed) {
593                    Some(s) => req.seed = Some(s),
594                    None => return usage_error(err, "--seed expects a 64-bit integer"),
595                }
596            }
597            "--fp" | "-fp" => {
598                let v = value();
599                match number::<usize>(flag, v.as_ref(), err) {
600                    Some(n) if n < 131 => req.fp = Some(n),
601                    _ => return usage_error(err, "--fp expects a polynomial index from 0 to 130"),
602                }
603            }
604            "--workers" | "-workers" => {
605                let v = value();
606                if v.as_deref() == Some("auto") {
607                    req.workers = None;
608                } else {
609                    match number::<usize>(flag, v.as_ref(), err) {
610                        Some(n) if n > 0 => req.workers = Some(n),
611                        _ => {
612                            return usage_error(
613                                err,
614                                "--workers expects a positive number or `auto`",
615                            );
616                        }
617                    }
618                }
619            }
620            "-deadlock" => req.no_deadlock = true,
621            "--symmetry-liveness" => {
622                let Some(policy) = value().as_deref().and_then(symmetry_liveness) else {
623                    return usage_error(
624                        err,
625                        "--symmetry-liveness expects unreduced, refuse or tlc",
626                    );
627                };
628                req.symmetry_liveness = Some(policy);
629            }
630            "--action-composition" => match value().as_deref() {
631                Some("off") => req.action_composition = Some(dive_api::ActionComposition::Off),
632                Some("tlc") => req.action_composition = Some(dive_api::ActionComposition::Tlc),
633                Some("tla") => req.action_composition = Some(dive_api::ActionComposition::Tla),
634                _ => return usage_error(err, "--action-composition expects off, tlc or tla"),
635            },
636            // TLC's JVM switch, spelled as TLC users pass it.
637            "-Dtlc2.tool.impl.Tool.cdot" => match value().as_deref() {
638                Some("true") => req.action_composition = Some(dive_api::ActionComposition::Tlc),
639                _ => {
640                    return usage_error(
641                        err,
642                        "-Dtlc2.tool.impl.Tool.cdot expects true (or use --action-composition)",
643                    );
644                }
645            },
646            "--sequential" => req.sequential = true,
647            "--source-coverage" => req.source_coverage = true,
648            "--coverage" => match value().as_deref() {
649                Some("0") => req.tlc_coverage = true,
650                _ => {
651                    return usage_error(
652                        err,
653                        "--coverage currently supports final reporting only: use 0",
654                    );
655                }
656            },
657            "--engine" => {
658                if let Err(message) = engine_option(value().as_deref()) {
659                    return usage_error(err, &message);
660                }
661            }
662            "--core-sample" => match value().and_then(|v| v.parse().ok()) {
663                Some(n) => req.core_sample = Some(n),
664                None => return usage_error(err, "--core-sample expects a state count"),
665            },
666            "--seen-disk-entries" => match value().and_then(|v| v.parse().ok()) {
667                Some(n) => {
668                    seen_policy.limits.entries = n;
669                    seen_entries = true;
670                }
671                None => {
672                    return usage_error(
673                        err,
674                        "--seen-disk-entries expects a positive bounded entry count",
675                    );
676                }
677            },
678            "--seen-key-bytes" => match value().and_then(|v| v.parse().ok()) {
679                Some(n) => {
680                    seen_policy.limits.key_bytes = n;
681                    seen_extra = true;
682                }
683                None => return usage_error(err, "--seen-key-bytes expects a key byte bound"),
684            },
685            "--seen-probe-steps" => match value().and_then(|v| v.parse().ok()) {
686                Some(n) => {
687                    seen_policy.limits.probe_steps = n;
688                    seen_extra = true;
689                }
690                None => {
691                    return usage_error(err, "--seen-probe-steps expects a positive probe bound");
692                }
693            },
694            "--seen-summary-pairs" => match value().and_then(|v| v.parse().ok()) {
695                Some(n) => {
696                    seen_policy.limits.summary_pairs = n;
697                    seen_extra = true;
698                }
699                None => {
700                    return usage_error(
701                        err,
702                        "--seen-summary-pairs expects a pair-comparison bound",
703                    );
704                }
705            },
706            "--seen-directory" => match value() {
707                Some(dir) => {
708                    seen_policy.directory = Some(dir.into());
709                    seen_extra = true;
710                }
711                None => return usage_error(err, "--seen-directory expects a parent directory"),
712            },
713            "--candidate-memory-bytes" => match value().as_deref().map(str::parse::<usize>) {
714                Some(Ok(n)) => req.candidate_memory_bytes = Some(n),
715                _ => {
716                    return usage_error(
717                        err,
718                        "--candidate-memory-bytes expects a byte count (zero forces disk)",
719                    );
720                }
721            },
722            "--candidate-directory" => match value() {
723                Some(dir) => req.candidate_directory = Some(dir.into()),
724                None => return usage_error(err, "--candidate-directory expects a directory"),
725            },
726            "--store-compact-bytes" => match value().as_deref().map(str::parse::<usize>) {
727                Some(Ok(n)) => req.store_compact_bytes = Some(n),
728                _ => {
729                    return usage_error(
730                        err,
731                        "--store-compact-bytes expects a byte trigger (zero forces each completed level)",
732                    );
733                }
734            },
735            "--frontier-memory-bytes" => match value().as_deref().map(str::parse::<usize>) {
736                Some(Ok(n)) => req.frontier_memory_bytes = Some(n),
737                _ => {
738                    return usage_error(
739                        err,
740                        "--frontier-memory-bytes expects a byte count (zero forces disk)",
741                    );
742                }
743            },
744            "--frontier-directory" => match value() {
745                Some(dir) => req.frontier_directory = Some(dir.into()),
746                None => return usage_error(err, "--frontier-directory expects a directory"),
747            },
748            "--checkpoint" => match value() {
749                Some(path) if checkpoint_path.is_none() => checkpoint_path = Some(path.into()),
750                _ => return usage_error(err, "--checkpoint expects one native file"),
751            },
752            "--recover" => match value() {
753                Some(path) if recover_path.is_none() => recover_path = Some(path.into()),
754                _ => return usage_error(err, "--recover expects one native file"),
755            },
756            "--checkpoint-after-levels" => match value().and_then(|s| s.parse().ok()) {
757                Some(n) if checkpoint_after.is_none() => checkpoint_after = Some(n),
758                _ => {
759                    return usage_error(
760                        err,
761                        "--checkpoint-after-levels expects a nonnegative count",
762                    );
763                }
764            },
765            "--checkpoint-counters" => {
766                counters_given = true;
767                checkpoint_counters = match value().as_deref() {
768                    Some("tlc") => dive_api::checkpoint::Counters::Tlc,
769                    Some("retain") => dive_api::checkpoint::Counters::Retain,
770                    _ => return usage_error(err, "--checkpoint-counters expects tlc or retain"),
771                };
772            }
773            "--predecessor-memory-bytes" => {
774                let v = value();
775                match number::<usize>(flag, v.as_ref(), err) {
776                    Some(n) => req.predecessor_memory_bytes = Some(n),
777                    None => {
778                        return usage_error(
779                            err,
780                            "--predecessor-memory-bytes expects a nonnegative byte count",
781                        );
782                    }
783                }
784            }
785            "--predecessor-directory" => match value() {
786                Some(dir) => req.predecessor_directory = Some(dir.into()),
787                None => return usage_error(err, "--predecessor-directory expects a directory"),
788            },
789            "--time-limit" => match value().as_deref().map(time_limit) {
790                Some(Some(setting)) => req.time_limit = setting,
791                _ => {
792                    return usage_error(
793                        err,
794                        "--time-limit expects a positive duration (90, 90s, 500ms, 10m, 2h) or `none`",
795                    );
796                }
797            },
798            "--max-memory" => match value().as_deref().map(max_memory) {
799                Some(Some(setting)) => req.max_memory = setting,
800                _ => {
801                    return usage_error(
802                        err,
803                        "--max-memory expects a positive byte count (3g, 512m, 1048576), `auto` or `none`",
804                    );
805                }
806            },
807            "--max-states" | "--max-depth" => match value().as_deref().map(search_limit) {
808                Some(Ok(limit)) => {
809                    if flag == "--max-states" {
810                        req.max_states = limit;
811                    } else {
812                        req.max_depth = limit;
813                    }
814                }
815                _ => {
816                    return usage_error(
817                        err,
818                        &format!("{flag} expects a nonnegative integer or `none`"),
819                    );
820                }
821            },
822            // Hidden, test-only: randomized scheduling that must not change
823            // any result (chaos mode).
824            "--chaos" => match value().as_deref().map(str::parse::<u64>) {
825                Some(Ok(seed)) => req.chaos = Some(seed),
826                _ => return usage_error(err, "--chaos expects a 64-bit unsigned seed"),
827            },
828            "--library-path" | "--module-path" => match value() {
829                Some(dir) if flag == "--library-path" => req.library_paths.push(dir.into()),
830                Some(dir) => req.module_paths.push(dir.into()),
831                None => return usage_error(err, &format!("{flag} expects a directory")),
832            },
833            s if s.starts_with('-') => {
834                return usage_error(err, &format!("unknown option `{s}` for `dive check`"));
835            }
836            s => {
837                if file.replace(s).is_some() {
838                    return usage_error(err, "`dive check` takes one file");
839                }
840            }
841        }
842    }
843    let Some(file) = file else {
844        let _ = writeln!(err, "error: `dive check` needs a file\n\n{}", usage());
845        return ExitCode::from(EXIT_USAGE);
846    };
847    if seen_extra && !seen_entries {
848        return usage_error(
849            err,
850            "--seen-directory and seen limits require --seen-disk-entries",
851        );
852    }
853    if seen_entries {
854        if let Err(error) = seen_policy.limits.validate() {
855            return usage_error(err, &error.to_string());
856        }
857        if final_check {
858            return usage_error(
859                err,
860                "disk seen-state retention with temporal/capture is not implemented",
861            );
862        }
863        req.seen_disk = Some(seen_policy);
864    }
865    if final_check != short_lasso {
866        return usage_error(
867            err,
868            "bounded temporal checking needs --lncheck final and --lasso short",
869        );
870    }
871    if req.candidate_directory.is_some() && req.candidate_memory_bytes.is_none() {
872        return usage_error(
873            err,
874            "--candidate-directory requires --candidate-memory-bytes",
875        );
876    }
877    if req.frontier_directory.is_some() && req.frontier_memory_bytes.is_none() {
878        return usage_error(err, "--frontier-directory requires --frontier-memory-bytes");
879    }
880    if final_check && short_lasso {
881        req.temporal_refusal = Some(FINAL_SHORT_REFUSAL.into());
882    }
883    if req.predecessor_directory.is_some() && req.predecessor_memory_bytes.is_none() {
884        return usage_error(
885            err,
886            "--predecessor-directory requires --predecessor-memory-bytes",
887        );
888    }
889    let checkpoint = match (checkpoint_path, recover_path, checkpoint_after) {
890        (Some(path), None, Some(n)) => Some(dive_api::checkpoint::Request {
891            path,
892            action: dive_api::checkpoint::Action::PauseAfterLevels(n),
893            counters: checkpoint_counters,
894            config_source_sha256: None,
895        }),
896        (None, Some(path), None) => Some(dive_api::checkpoint::Request {
897            path,
898            action: dive_api::checkpoint::Action::Recover,
899            counters: checkpoint_counters,
900            config_source_sha256: None,
901        }),
902        (None, None, None) if !counters_given => None,
903        _ => {
904            return usage_error(
905                err,
906                "use --checkpoint FILE --checkpoint-after-levels N or --recover FILE, exclusively",
907            );
908        }
909    };
910    req.file = file.into();
911    if worker_mode {
912        if checkpoint.is_some() {
913            return usage_error(
914                err,
915                "worker command requires pure Core roles without checkpoint/recovery",
916            );
917        }
918        let Some(key) = worker_key else {
919            return usage_error(err, "worker requires --worker-key FILE");
920        };
921        let worker = match dive_api::prepare_core_worker(&req, &key, worker_timeout) {
922            Ok(worker) => worker,
923            Err(error) => {
924                let _ = writeln!(err, "{error}");
925                return ExitCode::from(EXIT_UNSUPPORTED);
926            }
927        };
928        let Some(address) = worker_listen else {
929            return usage_error(err, "missing worker listener");
930        };
931        let listener = match std::net::TcpListener::bind(address) {
932            Ok(listener) => listener,
933            Err(error) => {
934                let _ = writeln!(err, "worker listener: {error}");
935                return ExitCode::from(EXIT_USAGE);
936            }
937        };
938        let address = match listener.local_addr() {
939            Ok(address) => address,
940            Err(error) => {
941                let _ = writeln!(err, "worker address: {error}");
942                return ExitCode::from(EXIT_USAGE);
943            }
944        };
945        if json {
946            let _ = writeln!(
947                out,
948                "{}",
949                serde_json::json!({"command":"worker","status":"ready","address":address.to_string(),"process_id":std::process::id(),"model_proved":false})
950            );
951        } else {
952            let _ = writeln!(out, "native worker ready on {address}");
953        }
954        let _ = out.flush();
955        return match worker.serve(&listener, worker_max_units, &|| false) {
956            Ok(facts) => {
957                if json {
958                    let _ = writeln!(
959                        out,
960                        "{}",
961                        serde_json::json!({"command":"worker","status":"stopped","work":facts,"model_proved":false})
962                    );
963                }
964                ExitCode::SUCCESS
965            }
966            Err(error) => {
967                let _ = writeln!(err, "{error}");
968                ExitCode::from(EXIT_UNSUPPORTED)
969            }
970        };
971    }
972    if !remote_workers.is_empty() {
973        let distinct: std::collections::HashSet<_> = remote_workers.iter().collect();
974        if distinct.len() != remote_workers.len() {
975            return usage_error(err, "--distributed-worker endpoints must be distinct");
976        }
977        if !(2..=64).contains(&remote_workers.len()) {
978            return usage_error(
979                err,
980                "distributed safety requires 2..64 --distributed-worker endpoints",
981            );
982        }
983        let Some(key) = worker_key else {
984            return usage_error(err, "distributed safety requires --worker-key FILE");
985        };
986        let mut options = dive_api::DistributedOptions::new(remote_workers, key);
987        options.timeout = worker_timeout;
988        options.retries = worker_retries;
989        req.distributed = Some(options);
990    } else if worker_key.is_some() || worker_timeout_given || worker_retries_given {
991        return usage_error(
992            err,
993            "worker key/timeout/retry options require worker mode or --distributed-worker endpoints",
994        );
995    }
996    let checked = if let Some(request) = &checkpoint {
997        dive_api::check_file_checkpoint(&req, request)
998    } else {
999        dive_api::check_file(&req)
1000    };
1001    let report = match checked {
1002        Ok(r) => r,
1003        Err(dive_api::ApiError::BudgetStartup(error)) => {
1004            let _ = writeln!(err, "{error}; no verdict produced");
1005            return ExitCode::from(4);
1006        }
1007        Err(dive_api::ApiError::BudgetMeasurement(error)) => {
1008            let _ = writeln!(err, "{error}; no verdict produced");
1009            return ExitCode::from(4);
1010        }
1011        Err(e @ dive_api::ApiError::Unsupported { .. }) => {
1012            let _ = writeln!(err, "{e}; no verdict produced");
1013            return ExitCode::from(EXIT_UNSUPPORTED);
1014        }
1015        Err(e) => {
1016            let _ = writeln!(err, "error: {e}");
1017            return ExitCode::from(EXIT_USAGE);
1018        }
1019    };
1020    if json {
1021        let _ = writeln!(
1022            out,
1023            "{}",
1024            report.to_json_with_exit_convention(exit_convention)
1025        );
1026    } else {
1027        let _ = write!(
1028            out,
1029            "{}",
1030            report.render_human_with_exit_convention(exit_convention)
1031        );
1032    }
1033    ExitCode::from(report.exit_code_for(exit_convention))
1034}
1035
1036/// `dive validate-trace <file> --trace <trace.json> [--config cfg] [--claim ENDING]
1037/// [--compat=tlc] [--seed N] [--fp N] [--deadlock] [--output human|json] [--library-path DIR]... [--module-path DIR]...`.
1038///
1039/// Validates a counterexample or behavior against the specification with
1040/// the independent trace validator. The trace is in dive's format
1041/// or TLC's `-dumpTrace json` (which needs `--claim`, e.g.
1042/// `invariant:Inv`). `--seed` (and `--fp`) give the checking run's seed and
1043/// polynomial, so that random draws are replayed. Exit status: 0 valid, 1 invalid (or the specification
1044/// is rejected), 2 usage or unreadable input, 3 unsupported.
1045#[allow(
1046    clippy::too_many_lines,
1047    reason = "one command: its options, then loading, validating and reporting"
1048)]
1049fn validate_trace_command(
1050    args: &[String],
1051    out: &mut impl std::io::Write,
1052    err: &mut impl std::io::Write,
1053) -> ExitCode {
1054    let mut file: Option<&str> = None;
1055    let mut cfg: Option<&str> = None;
1056    let mut trace: Option<&str> = None;
1057    let mut input_report: Option<&str> = None;
1058    let mut claim: Option<&str> = None;
1059    let mut json = false;
1060    let mut sample = false;
1061    let mut seed: Option<i64> = None;
1062    let mut fp: Option<usize> = None;
1063    let mut opts = dive_api::trace::TraceOptions {
1064        compat_tlc: std::env::var("DIVE_COMPAT").is_ok_and(|v| v == "tlc"),
1065        ..Default::default()
1066    };
1067    let mut it = args.iter();
1068    let usage_error = |err: &mut dyn std::io::Write, msg: &str| {
1069        let _ = writeln!(err, "error: {msg}");
1070        ExitCode::from(EXIT_USAGE)
1071    };
1072    while let Some(a) = it.next() {
1073        match a.as_str() {
1074            "--sample" => sample = true,
1075            "--output" => match it.next().map(String::as_str) {
1076                Some("json") => json = true,
1077                Some("human") => json = false,
1078                other => {
1079                    return usage_error(
1080                        err,
1081                        &format!(
1082                            "--output expects `human` or `json`, got {}",
1083                            other.unwrap_or("nothing")
1084                        ),
1085                    );
1086                }
1087            },
1088            "--config" | "--trace" | "--claim" | "--inputs" => {
1089                let Some(v) = it.next() else {
1090                    return usage_error(err, &format!("{a} expects a value"));
1091                };
1092                let slot = match a.as_str() {
1093                    "--config" => &mut cfg,
1094                    "--trace" => &mut trace,
1095                    "--inputs" => &mut input_report,
1096                    _ => &mut claim,
1097                };
1098                if slot.replace(v).is_some() {
1099                    return usage_error(err, &format!("{a} given twice"));
1100                }
1101            }
1102            "--compat=tlc" => opts.compat_tlc = true,
1103            "--compat=dive" => opts.compat_tlc = false,
1104            "--compat" => match it.next().map(String::as_str) {
1105                Some("tlc") => opts.compat_tlc = true,
1106                Some("dive") => opts.compat_tlc = false,
1107                _ => return usage_error(err, "--compat expects `tlc` or `dive`"),
1108            },
1109            "--symmetry-liveness" => {
1110                let Some(policy) = it.next().and_then(|v| symmetry_liveness(v)) else {
1111                    return usage_error(
1112                        err,
1113                        "--symmetry-liveness expects unreduced, refuse or tlc",
1114                    );
1115                };
1116                opts.symmetry_liveness = Some(policy);
1117            }
1118            s if s.starts_with("--symmetry-liveness=") => {
1119                let Some(policy) = s
1120                    .strip_prefix("--symmetry-liveness=")
1121                    .and_then(symmetry_liveness)
1122                else {
1123                    return usage_error(
1124                        err,
1125                        "--symmetry-liveness expects unreduced, refuse or tlc",
1126                    );
1127                };
1128                opts.symmetry_liveness = Some(policy);
1129            }
1130            "--deadlock" | "-deadlock" => opts.no_deadlock = true,
1131            "--seed" | "-seed" => match it.next().and_then(|v| dive_api::parse_seed(v)) {
1132                Some(s) => seed = Some(s),
1133                None => return usage_error(err, "--seed expects a 64-bit integer"),
1134            },
1135            "--fp" | "-fp" => match it.next().and_then(|v| v.parse::<usize>().ok()) {
1136                Some(n) if n < 131 => fp = Some(n),
1137                _ => return usage_error(err, "--fp expects a polynomial index from 0 to 130"),
1138            },
1139            "--library-path" | "--module-path" => {
1140                let Some(dir) = it.next() else {
1141                    return usage_error(err, &format!("{a} expects a directory"));
1142                };
1143                if a == "--library-path" {
1144                    opts.library_paths.push(dir.into());
1145                } else {
1146                    opts.module_paths.push(dir.into());
1147                }
1148            }
1149            s if s.starts_with('-') => {
1150                return usage_error(
1151                    err,
1152                    &format!("unknown option `{s}` for `dive validate-trace`"),
1153                );
1154            }
1155            s => {
1156                if file.replace(s).is_some() {
1157                    return usage_error(err, "`dive validate-trace` takes one specification");
1158                }
1159            }
1160        }
1161    }
1162    let Some(file) = file else {
1163        return usage_error(
1164            err,
1165            &format!(
1166                "`dive validate-trace` needs a specification and --trace or --inputs\n\n{}",
1167                usage()
1168            ),
1169        );
1170    };
1171    let input_document = if let Some(path) = input_report {
1172        let report = match read_external_input_report(path) {
1173            Ok(report) => report,
1174            Err(message) => return usage_error(err, &message),
1175        };
1176        opts.inputs = match dive_api::host_inputs::inputs_from_report(&report) {
1177            Ok(inputs) => Some(inputs),
1178            Err(error) => return usage_error(err, &error.to_string()),
1179        };
1180        Some(report)
1181    } else {
1182        None
1183    };
1184    // The checking run's seed and polynomial, as `dive check` chose them:
1185    // without `--fp`, TLC's (under --compat=tlc) is derived from the seed.
1186    opts.run = match (seed, fp) {
1187        (Some(s), fp) => Some((
1188            s,
1189            fp.unwrap_or_else(|| {
1190                if opts.compat_tlc {
1191                    usize::try_from(s.unsigned_abs() % 131).unwrap_or(0)
1192                } else {
1193                    0
1194                }
1195            }),
1196        )),
1197        (None, Some(_)) => return usage_error(err, "--fp needs --seed"),
1198        (None, None) => None,
1199    };
1200    let spec = std::path::Path::new(file);
1201    // TLC's default: the configuration next to the specification.
1202    let cfg = cfg.map_or_else(|| spec.with_extension("cfg"), std::path::PathBuf::from);
1203    let document = if let Some(trace) = trace {
1204        let text = match std::fs::read_to_string(trace) {
1205            Ok(text) => text,
1206            Err(error) => return usage_error(err, &format!("cannot read {trace}: {error}")),
1207        };
1208        match serde_json::from_str(&text) {
1209            Ok(document) => document,
1210            Err(error) => return usage_error(err, &format!("{trace}: {error}")),
1211        }
1212    } else if let Some(report) = &input_document {
1213        report["counterexample"]["trace"].clone()
1214    } else {
1215        return usage_error(
1216            err,
1217            "validate-trace requires --trace or a check report supplied by --inputs",
1218        );
1219    };
1220    let mut doc = match dive_api::trace::TraceDoc::from_json(&document) {
1221        Ok(d) => d,
1222        Err(e) => return usage_error(err, &e),
1223    };
1224    if let Some(c) = claim {
1225        let ending = match dive_api::trace::Ending::parse(c) {
1226            Ok(e) => e,
1227            Err(e) => return usage_error(err, &format!("--claim: {e}")),
1228        };
1229        if doc.ending.as_ref().is_some_and(|d| *d != ending) {
1230            return usage_error(err, "--claim contradicts the trace's own `ending`");
1231        }
1232        doc = doc.with_ending(ending);
1233    }
1234    let model = match dive_api::trace::SpecModel::load(spec, &cfg, &opts) {
1235        Ok(m) => m,
1236        Err(e @ dive_api::ApiError::Unsupported { .. }) => {
1237            let _ = writeln!(err, "{e}; no result produced");
1238            return ExitCode::from(EXIT_UNSUPPORTED);
1239        }
1240        Err(e @ dive_api::ApiError::Rejected { .. }) => {
1241            let _ = writeln!(err, "error: {e}");
1242            return ExitCode::from(EXIT_REJECTED);
1243        }
1244        Err(e) => return usage_error(err, &e.to_string()),
1245    };
1246    let report = match if sample {
1247        model.try_validate_sample(&doc)
1248    } else {
1249        model.try_validate(&doc)
1250    } {
1251        Ok(report) => report,
1252        Err(error) => return validation_exception(out, err, &error, json),
1253    };
1254    if json {
1255        let mut document = dive_api::trace::report_json(&report);
1256        if sample {
1257            document["validation_goal"] = serde_json::json!("sample");
1258        }
1259        let _ = writeln!(out, "{document}");
1260    } else {
1261        let _ = write!(out, "{}", dive_api::trace::render_report(&report));
1262    }
1263    match report.validation {
1264        dive_api::trace::Validation::Valid => ExitCode::SUCCESS,
1265        dive_api::trace::Validation::Unsupported(_) => ExitCode::from(EXIT_UNSUPPORTED),
1266        // Invalid, or any other result that is not a validation.
1267        _ => ExitCode::from(EXIT_REJECTED),
1268    }
1269}
1270
1271fn read_external_input_report(path: &str) -> Result<serde_json::Value, String> {
1272    const LIMIT: usize = 8 << 20;
1273    let file = std::fs::File::open(path).map_err(|error| format!("cannot read {path}: {error}"))?;
1274    let mut reader = std::io::Read::take(file, u64::try_from(LIMIT + 1).unwrap_or(u64::MAX));
1275    let mut bytes = Vec::new();
1276    std::io::Read::read_to_end(&mut reader, &mut bytes)
1277        .map_err(|error| format!("cannot read {path}: {error}"))?;
1278    if bytes.len() > LIMIT {
1279        return Err("external input report exceeds 8 MiB".into());
1280    }
1281    serde_json::from_slice(&bytes).map_err(|error| format!("{path}: {error}"))
1282}
1283
1284fn validation_exception(
1285    out: &mut dyn std::io::Write,
1286    err: &mut dyn std::io::Write,
1287    error: &dive_api::trace::ValidationRunError,
1288    json: bool,
1289) -> ExitCode {
1290    use dive_api::trace::ValidationRunError;
1291    let (kind, progress, status) = match error {
1292        ValidationRunError::ResourceLimit { progress, .. } => {
1293            ("resource-limit", Some(progress), EXIT_UNSUPPORTED)
1294        }
1295        ValidationRunError::Interrupted { progress, .. } => ("interrupted", Some(progress), 5),
1296        ValidationRunError::EvaluationFailure { progress, .. }
1297        | ValidationRunError::BindingFailure { progress, .. } => {
1298            ("execution-error", Some(progress), 4)
1299        }
1300        // A thread failure, a control conflict, or any other failure without
1301        // validation progress.
1302        _ => ("execution-error", None, 4),
1303    };
1304    if json {
1305        let progress=progress.map(|progress|serde_json::json!({"checks_passed":progress.checks_passed,"state":progress.state,"check":progress.check.map(dive_api::trace::Check::name)}));
1306        let _ = writeln!(
1307            out,
1308            "{}",
1309            serde_json::json!({"schema_version":dive_api::REPORT_SCHEMA_VERSION,"command":"validate-trace","validation_completed":false,"error":{"kind":kind,"phase":"validation","message":error.to_string(),"progress":progress}})
1310        );
1311    } else {
1312        let _ = writeln!(
1313            err,
1314            "{error}; validation did not complete; no validation verdict produced"
1315        );
1316    }
1317    ExitCode::from(status)
1318}
1319
1320fn simulation_usage_error(err: &mut impl std::io::Write, message: &str) -> ExitCode {
1321    let _ = writeln!(err, "error: {message}");
1322    ExitCode::from(EXIT_USAGE)
1323}
1324
1325/// Finite seeded simulation, with explicit sampling metadata.
1326#[allow(
1327    clippy::too_many_lines,
1328    reason = "one command parser keeps finite sampling options and explicit refusals together"
1329)]
1330fn simulate_command(
1331    args: &[String],
1332    out: &mut impl std::io::Write,
1333    err: &mut impl std::io::Write,
1334) -> ExitCode {
1335    let mut request = dive_api::SimulateRequest {
1336        compat_tlc: std::env::var("DIVE_COMPAT").is_ok_and(|s| s == "tlc"),
1337        ..Default::default()
1338    };
1339    if let Err(message) = engine_from_env() {
1340        return simulation_usage_error(err, &message);
1341    }
1342    let mut json = false;
1343    let mut exit_convention = None;
1344    let mut file = None;
1345    let mut it = args.iter();
1346    while let Some(arg) = it.next() {
1347        match arg.as_str() {
1348            s if matches!(
1349                s.split('=').next(),
1350                Some("--predecessor-memory-bytes" | "--predecessor-directory")
1351            ) =>
1352            {
1353                let _ = writeln!(err, "predecessor spill with simulation is not implemented");
1354                return ExitCode::from(EXIT_UNSUPPORTED);
1355            }
1356            "--compat=tlc" => request.compat_tlc = true,
1357            value if value.starts_with("--time-limit=") => match time_limit(&value[13..]) {
1358                Some(setting) => request.time_limit = setting,
1359                None => {
1360                    return simulation_usage_error(
1361                        err,
1362                        "--time-limit expects a positive duration or none",
1363                    );
1364                }
1365            },
1366            value if value.starts_with("--max-memory=") => match max_memory(&value[13..]) {
1367                Some(setting) => request.max_memory = setting,
1368                None => {
1369                    return simulation_usage_error(
1370                        err,
1371                        "--max-memory expects a positive byte count, auto or none",
1372                    );
1373                }
1374            },
1375            "--time-limit" => match it.next().map(String::as_str).and_then(time_limit) {
1376                Some(setting) => request.time_limit = setting,
1377                None => {
1378                    return simulation_usage_error(
1379                        err,
1380                        "--time-limit expects a positive duration or none",
1381                    );
1382                }
1383            },
1384            "--max-memory" => match it.next().map(String::as_str).and_then(max_memory) {
1385                Some(setting) => request.max_memory = setting,
1386                None => {
1387                    return simulation_usage_error(
1388                        err,
1389                        "--max-memory expects a positive byte count, auto or none",
1390                    );
1391                }
1392            },
1393            "--engine" => {
1394                if let Err(message) = engine_option(it.next().map(String::as_str)) {
1395                    return simulation_usage_error(err, &message);
1396                }
1397            }
1398            name if name.starts_with("--engine=") => {
1399                if let Err(message) = engine_option(Some(&name[9..])) {
1400                    return simulation_usage_error(err, &message);
1401                }
1402            }
1403            "--config" => {
1404                let Some(value) = it.next() else {
1405                    return simulation_usage_error(err, "--config expects a path");
1406                };
1407                if request.config.replace(value.into()).is_some() {
1408                    return simulation_usage_error(err, "--config given twice");
1409                }
1410            }
1411            "--seed" => {
1412                let Some(value) = it.next() else {
1413                    return simulation_usage_error(err, "--seed expects an integer");
1414                };
1415                let Some(seed) = dive_api::parse_seed(value) else {
1416                    return simulation_usage_error(err, "invalid --seed");
1417                };
1418                if request.seed.replace(seed).is_some() {
1419                    return simulation_usage_error(err, "--seed given twice");
1420                }
1421            }
1422            "--aril" | "--depth" | "--traces" | "--workers" => {
1423                let Some(value) = it.next() else {
1424                    return simulation_usage_error(
1425                        err,
1426                        "simulation numeric option expects an integer",
1427                    );
1428                };
1429                let Ok(number) = value.parse::<u64>() else {
1430                    return simulation_usage_error(
1431                        err,
1432                        "simulation option must be a nonnegative integer",
1433                    );
1434                };
1435                match arg.as_str() {
1436                    "--aril" => request.aril = number,
1437                    "--traces" => request.traces = number,
1438                    "--depth" => {
1439                        let Ok(number) = usize::try_from(number) else {
1440                            return simulation_usage_error(err, "depth exceeds addressable range");
1441                        };
1442                        request.depth = Some(number);
1443                    }
1444                    _ => {
1445                        let Ok(number) = usize::try_from(number) else {
1446                            return simulation_usage_error(
1447                                err,
1448                                "worker count exceeds addressable range",
1449                            );
1450                        };
1451                        if number == 0 {
1452                            return simulation_usage_error(
1453                                err,
1454                                "simulation workers must be positive",
1455                            );
1456                        }
1457                        request.workers = Some(number);
1458                    }
1459                }
1460            }
1461            "--exit-codes" => {
1462                exit_convention = Some(match it.next().map(String::as_str) {
1463                    Some("native") => dive_api::ExitConvention::Native,
1464                    Some("tlc") => dive_api::ExitConvention::Tlc,
1465                    _ => return simulation_usage_error(err, "--exit-codes expects native or tlc"),
1466                });
1467            }
1468            "--stats" => match it.next().map(String::as_str) {
1469                Some("basic") => request.action_stats = true,
1470                Some("none") => request.action_stats = false,
1471                Some("full") => {
1472                    let _ = writeln!(err, "unsupported: simulation full action statistics");
1473                    return ExitCode::from(EXIT_UNSUPPORTED);
1474                }
1475                _ => return simulation_usage_error(err, "--stats expects none or basic"),
1476            },
1477            "-deadlock" => request.no_deadlock = true,
1478            "--output" => match it.next().map(String::as_str) {
1479                Some("json") => json = true,
1480                Some("human") => json = false,
1481                _ => return simulation_usage_error(err, "--output expects human or json"),
1482            },
1483            "--library-path" | "--module-path" => {
1484                let Some(path) = it.next() else {
1485                    return simulation_usage_error(err, "module option expects a path");
1486                };
1487                if arg == "--library-path" {
1488                    request.library_paths.push(path.into());
1489                } else {
1490                    request.module_paths.push(path.into());
1491                }
1492            }
1493            "--generate" => request.generation = true,
1494            "--continue"
1495            | "--probabilistic"
1496            | "--rl"
1497            | "--distributed"
1498            | "--frontier-memory-bytes"
1499            | "--store-compact-bytes"
1500            | "--frontier-directory" => {
1501                let _ = writeln!(err, "unsupported: simulation {arg}; no result produced");
1502                return ExitCode::from(EXIT_UNSUPPORTED);
1503            }
1504            value if value.starts_with('-') => {
1505                return simulation_usage_error(err, &format!("unknown simulation option {value}"));
1506            }
1507            value => {
1508                if file.replace(value).is_some() {
1509                    return simulation_usage_error(err, "simulate takes one specification file");
1510                }
1511            }
1512        }
1513    }
1514    let Some(file) = file else {
1515        return simulation_usage_error(err, "simulate needs a specification file and --traces N");
1516    };
1517    if request.traces == 0 {
1518        return simulation_usage_error(err, "simulate requires a positive finite --traces N");
1519    }
1520    request.file = file.into();
1521    let report = match dive_api::simulate_file(&request) {
1522        Ok(report) => report,
1523        Err(dive_api::ApiError::Unsupported { feature }) => {
1524            let _ = writeln!(err, "unsupported: {feature}; no result produced");
1525            return ExitCode::from(EXIT_UNSUPPORTED);
1526        }
1527        Err(
1528            error @ (dive_api::ApiError::BudgetStartup(_)
1529            | dive_api::ApiError::BudgetMeasurement(_)),
1530        ) => {
1531            let _ = writeln!(err, "{error}; no result produced");
1532            return ExitCode::from(4);
1533        }
1534        Err(error) => {
1535            let _ = writeln!(err, "error: {error}");
1536            return ExitCode::from(EXIT_REJECTED);
1537        }
1538    };
1539    if json {
1540        let document = exit_convention.map_or_else(
1541            || report.to_json(),
1542            |convention| report.to_json_with_exit_convention(convention),
1543        );
1544        let _ = writeln!(out, "{document}");
1545    } else {
1546        let _ = write!(out, "{}", report.render_human());
1547    }
1548    ExitCode::from(exit_convention.map_or_else(
1549        || report.exit_code(),
1550        |convention| report.exit_code_for(convention),
1551    ))
1552}
1553
1554/// Runs the native bounded iterative mode; unknown mode flags refuse by name.
1555#[allow(
1556    clippy::too_many_lines,
1557    reason = "explicit CLI options and typed validation"
1558)]
1559fn dfid_command(
1560    args: &[String],
1561    out: &mut impl std::io::Write,
1562    err: &mut impl std::io::Write,
1563) -> ExitCode {
1564    let mut req = dive_api::DfidRequest {
1565        compat_tlc: std::env::var("DIVE_COMPAT").is_ok_and(|v| v == "tlc"),
1566        ..dive_api::DfidRequest::default()
1567    };
1568    if let Err(message) = engine_from_env() {
1569        let _ = writeln!(err, "error: {message}");
1570        return ExitCode::from(EXIT_USAGE);
1571    }
1572    let mut json = false;
1573    let mut has_depth = false;
1574    let mut file = None;
1575    let mut it = args.iter();
1576    let usage_error = |err: &mut dyn std::io::Write, text: &str| {
1577        let _ = writeln!(err, "error: {text}");
1578        ExitCode::from(EXIT_USAGE)
1579    };
1580    while let Some(arg) = it.next() {
1581        let (flag, inline) = match arg.split_once('=') {
1582            Some((f, v)) if f.starts_with('-') => (f, Some(v.to_owned())),
1583            _ => (arg.as_str(), None),
1584        };
1585        let mut value = || inline.clone().or_else(|| it.next().cloned());
1586        match flag {
1587            "--predecessor-memory-bytes" | "--predecessor-directory" => {
1588                let _ = writeln!(err, "predecessor spill with DFID is not implemented");
1589                return ExitCode::from(EXIT_UNSUPPORTED);
1590            }
1591            "--output" => match value().as_deref() {
1592                Some("json") => json = true,
1593                Some("human") => json = false,
1594                _ => return usage_error(err, "--output expects human or json"),
1595            },
1596            "--compat" => match value().as_deref() {
1597                Some("tlc") => req.compat_tlc = true,
1598                Some("dive" | "none") => req.compat_tlc = false,
1599                _ => return usage_error(err, "--compat expects tlc or dive"),
1600            },
1601            "--engine" => {
1602                if let Err(message) = engine_option(value().as_deref()) {
1603                    return usage_error(err, &message);
1604                }
1605            }
1606            "--config" | "-config" => match value() {
1607                Some(v) => req.config = Some(v.into()),
1608                None => return usage_error(err, "--config expects a cfg file"),
1609            },
1610            "--max-level" | "--dfid" | "-dfid" => match value().and_then(|v| v.parse().ok()) {
1611                Some(n) => {
1612                    req.max_level = n;
1613                    has_depth = true;
1614                }
1615                None => return usage_error(err, "--max-level expects an unsigned integer"),
1616            },
1617            "--seed" | "-seed" => match value().as_deref().and_then(dive_api::parse_seed) {
1618                Some(seed) => req.seed = Some(seed),
1619                None => return usage_error(err, "--seed expects a 64-bit seed"),
1620            },
1621            "--worker-seeds" => match value().map(|v| {
1622                v.split(',')
1623                    .map(dive_api::parse_seed)
1624                    .collect::<Option<Vec<_>>>()
1625            }) {
1626                Some(Some(seeds)) if !seeds.is_empty() => req.worker_seeds = Some(seeds),
1627                _ => {
1628                    return usage_error(err, "--worker-seeds expects comma separated 64-bit seeds");
1629                }
1630            },
1631            "--workers" | "-workers" => match value().and_then(|v| v.parse().ok()) {
1632                Some(n) => req.workers = Some(n),
1633                None => return usage_error(err, "--workers expects an unsigned integer"),
1634            },
1635            "--fp" | "-fp" => match value().and_then(|v| v.parse::<usize>().ok()) {
1636                Some(n) if n < 131 => req.fp = n,
1637                _ => return usage_error(err, "--fp expects 0..130"),
1638            },
1639            "--time-limit" => match value().as_deref().and_then(time_limit) {
1640                Some(setting) => req.time_limit = setting,
1641                None => {
1642                    return usage_error(err, "--time-limit expects a positive duration or none");
1643                }
1644            },
1645            "--max-memory" => match value().as_deref().and_then(max_memory) {
1646                Some(setting) => req.max_memory = setting,
1647                None => {
1648                    return usage_error(
1649                        err,
1650                        "--max-memory expects a positive byte count, auto or none",
1651                    );
1652                }
1653            },
1654            "--store" => match value().as_deref() {
1655                Some("exact") => req.exact = true,
1656                Some("fp" | "fingerprint") => req.exact = false,
1657                _ => return usage_error(err, "--store expects fp or exact"),
1658            },
1659            "--library-path" => match value() {
1660                Some(v) => req.library_paths.push(v.into()),
1661                None => return usage_error(err, "--library-path expects a directory"),
1662            },
1663            "--module-path" => match value() {
1664                Some(v) => req.module_paths.push(v.into()),
1665                None => return usage_error(err, "--module-path expects a directory"),
1666            },
1667            "-deadlock" | "--no-deadlock" => req.no_deadlock = true,
1668            s if s.starts_with('-') => {
1669                let _ = writeln!(err, "unsupported DFID option: {s}; no checking performed");
1670                return ExitCode::from(EXIT_UNSUPPORTED);
1671            }
1672            s => {
1673                if file.replace(s).is_some() {
1674                    return usage_error(err, "dfid takes one specification file");
1675                }
1676            }
1677        }
1678    }
1679    let Some(file) = file else {
1680        return usage_error(err, "dfid requires a specification and --max-level N");
1681    };
1682    if !has_depth {
1683        return usage_error(err, "dfid requires explicit --max-level N");
1684    }
1685    req.file = file.into();
1686    let report = match dive_api::dfid_file(&req) {
1687        Ok(r) => r,
1688        Err(
1689            error @ (dive_api::ApiError::BudgetStartup(_)
1690            | dive_api::ApiError::BudgetMeasurement(_)),
1691        ) => {
1692            let _ = writeln!(err, "{error}; no result produced");
1693            return ExitCode::from(4);
1694        }
1695        Err(e) => {
1696            let _ = writeln!(err, "{e}");
1697            return ExitCode::from(EXIT_USAGE);
1698        }
1699    };
1700    if json {
1701        let _ = writeln!(out, "{}", report.to_json());
1702    } else {
1703        let _ = write!(out, "{}", report.render_human());
1704    }
1705    ExitCode::from(report.exit_status())
1706}
1707
1708/// Runs the shared CLI, including an executable whose basename is `tlc`.
1709///
1710/// Both installed binaries use this entrypoint; native command defaults remain
1711/// independent from the TLC checking adapter.
1712///
1713/// ```no_run
1714/// let status = dive_cli::main();
1715/// # let _ = status;
1716/// ```
1717#[must_use]
1718pub fn main() -> ExitCode {
1719    let mut arguments = std::env::args_os();
1720    let shim = arguments.next().is_some_and(|executable| {
1721        std::path::Path::new(&executable)
1722            .file_name()
1723            .is_some_and(|name| name == "tlc" || name == "tlc.exe")
1724    });
1725    let arguments: Vec<_> = arguments.collect();
1726    let adapter = shim || arguments.first().is_some_and(|argument| argument == "tlc");
1727    let args = arguments
1728        .into_iter()
1729        .map(std::ffi::OsString::into_string)
1730        .collect::<Result<Vec<_>, _>>();
1731    let mut stdout = std::io::stdout().lock();
1732    let mut stderr = std::io::stderr().lock();
1733    let Ok(args) = args else {
1734        let _ = writeln!(stderr, "DIVE-X0001: command arguments must be valid UTF-8");
1735        return ExitCode::from(if adapter { 1 } else { EXIT_USAGE });
1736    };
1737    if shim {
1738        return tlc::command(&args, &mut stdout, &mut stderr);
1739    }
1740    if let Some((command, arguments)) = args.split_first()
1741        && arguments
1742            .iter()
1743            .any(|argument| matches!(argument.as_str(), "-h" | "--help"))
1744        && let Some(help) = help::command(command)
1745    {
1746        let _ = write!(stdout, "{help}");
1747        return ExitCode::SUCCESS;
1748    }
1749    // Write failures (e.g. a closed pipe) are not actionable here.
1750    match args.first().map(String::as_str) {
1751        None | Some("-h" | "--help" | "help") => {
1752            let _ = write!(stdout, "{}", usage());
1753            ExitCode::SUCCESS
1754        }
1755        Some("-V" | "--version") => {
1756            let _ = writeln!(
1757                stdout,
1758                "dive {} ({})",
1759                env!("CARGO_PKG_VERSION"),
1760                env!("DIVE_GIT_DESCRIBE")
1761            );
1762            ExitCode::SUCCESS
1763        }
1764        Some("parse") => parse_command(&args[1..], &mut stdout, &mut stderr),
1765        Some("debug") => debug::command(&args[1..], &mut stdout, &mut stderr),
1766        Some("explain") => explain::command(&args[1..], &mut stdout, &mut stderr),
1767        Some("analyze") => analyze_command(&args[1..], &mut stdout, &mut stderr),
1768        Some("dfid") => dfid_command(&args[1..], &mut stdout, &mut stderr),
1769        Some("translate") => translate::command(&args[1..], &mut stdout, &mut stderr),
1770        Some("check") => check_command(&args[1..], &mut stdout, &mut stderr),
1771        Some("worker") => check_command_mode(&args[1..], &mut stdout, &mut stderr, true),
1772        Some("tlc") => tlc::command(&args[1..], &mut stdout, &mut stderr),
1773        Some("simulate") => simulate_command(&args[1..], &mut stdout, &mut stderr),
1774        Some("validate-trace") => validate_trace_command(&args[1..], &mut stdout, &mut stderr),
1775        Some(cmd @ "lsp") => {
1776            let _ = writeln!(
1777                stderr,
1778                "unsupported: `dive {cmd}` is not implemented yet; no verdict produced"
1779            );
1780            ExitCode::from(EXIT_UNSUPPORTED)
1781        }
1782        Some(other) => {
1783            let _ = write!(stderr, "error: unknown command `{other}`\n\n{}", usage());
1784            ExitCode::from(EXIT_USAGE)
1785        }
1786    }
1787}
1788
1789#[cfg(test)]
1790mod predecessor_tests {
1791    use super::*;
1792    #[test]
1793    fn orphan_directory_and_other_modes_refuse_before_input_access() {
1794        let args = [
1795            "missing.tla".into(),
1796            "--predecessor-directory".into(),
1797            "missing-parent".into(),
1798        ];
1799        let mut output = Vec::new();
1800        let mut errors = Vec::new();
1801        assert_eq!(
1802            check_command(&args, &mut output, &mut errors),
1803            ExitCode::from(EXIT_USAGE)
1804        );
1805        assert!(String::from_utf8_lossy(&errors).contains("requires --predecessor-memory-bytes"));
1806        for flag in [
1807            "--predecessor-memory-bytes=0",
1808            "--predecessor-directory=missing",
1809        ] {
1810            errors.clear();
1811            assert_eq!(
1812                simulate_command(&[flag.into()], &mut output, &mut errors),
1813                ExitCode::from(EXIT_UNSUPPORTED)
1814            );
1815            assert!(String::from_utf8_lossy(&errors).contains("predecessor spill with simulation"));
1816            errors.clear();
1817            assert_eq!(
1818                dfid_command(&[flag.into()], &mut output, &mut errors),
1819                ExitCode::from(EXIT_UNSUPPORTED)
1820            );
1821            assert!(String::from_utf8_lossy(&errors).contains("predecessor spill with DFID"));
1822        }
1823        assert_eq!(output, [] as [u8; 0]);
1824    }
1825}
1826
1827#[cfg(test)]
1828mod seen_tests {
1829    use super::*;
1830    #[test]
1831    fn malformed_or_orphan_disk_policy_refuses_before_reading_model() {
1832        for flags in [
1833            vec!["--seen-directory", "unused-parent"],
1834            vec!["--seen-key-bytes", "64"],
1835            vec!["--seen-probe-steps", "1"],
1836            vec!["--seen-summary-pairs", "0"],
1837            vec!["--seen-disk-entries", "0"],
1838            vec!["--seen-disk-entries", "4", "--seen-key-bytes", "0"],
1839            vec!["--seen-disk-entries", "4", "--seen-probe-steps", "0"],
1840            vec![
1841                "--seen-disk-entries",
1842                "4",
1843                "--lncheck",
1844                "final",
1845                "--lasso",
1846                "short",
1847            ],
1848        ] {
1849            let mut arguments = vec!["missing-seen-model.tla".to_owned()];
1850            arguments.extend(flags.iter().map(|s| (*s).to_owned()));
1851            let mut output = Vec::new();
1852            let mut errors = Vec::new();
1853            assert_eq!(
1854                check_command(&arguments, &mut output, &mut errors),
1855                ExitCode::from(EXIT_USAGE)
1856            );
1857            assert_eq!(output, [] as [u8; 0]);
1858            let error = String::from_utf8_lossy(&errors);
1859            assert!(!error.contains("cannot read"), "{error}");
1860            assert!(
1861                error.contains("--seen-directory and seen limits require --seen-disk-entries")
1862                    || error.contains("DIVE-S0700")
1863                    || error.contains("is not implemented"),
1864                "{error}"
1865            );
1866        }
1867    }
1868}
1869
1870#[cfg(test)]
1871mod budget_tests {
1872    use super::*;
1873    use dive_api::BudgetSetting::{Default, Explicit, Unlimited};
1874    use std::time::Duration;
1875
1876    #[test]
1877    fn time_limits_parse_units_and_none() {
1878        assert_eq!(time_limit("90"), Some(Explicit(Duration::from_secs(90))));
1879        assert_eq!(time_limit("90s"), Some(Explicit(Duration::from_secs(90))));
1880        assert_eq!(
1881            time_limit("500ms"),
1882            Some(Explicit(Duration::from_millis(500)))
1883        );
1884        assert_eq!(time_limit("10m"), Some(Explicit(Duration::from_secs(600))));
1885        assert_eq!(time_limit("2h"), Some(Explicit(Duration::from_secs(7200))));
1886        assert_eq!(time_limit("none"), Some(Unlimited));
1887        for bad in ["", "0", "-1", "1.5s", "10d", "s", "auto"] {
1888            assert_eq!(time_limit(bad), None, "{bad}");
1889        }
1890    }
1891
1892    #[test]
1893    fn memory_ceilings_parse_jvm_units_auto_and_none() {
1894        assert_eq!(max_memory("3g"), Some(Explicit(3 << 30)));
1895        assert_eq!(max_memory("512M"), Some(Explicit(512 << 20)));
1896        assert_eq!(max_memory("1048576"), Some(Explicit(1 << 20)));
1897        assert_eq!(max_memory("auto"), Some(Default));
1898        assert_eq!(max_memory("none"), Some(Unlimited));
1899        for bad in ["", "0", "0g", "-1", "3gb", "1.5g", "99999999999t"] {
1900            assert_eq!(max_memory(bad), None, "{bad}");
1901        }
1902    }
1903
1904    #[test]
1905    fn malformed_budgets_are_usage_errors_before_reading_the_model() {
1906        for flags in [
1907            ["--time-limit", "0"],
1908            ["--max-memory", "lots"],
1909            ["--max-states", "-1"],
1910            ["--max-depth", "1.5"],
1911        ] {
1912            let args: Vec<String> = std::iter::once("missing.tla")
1913                .chain(flags)
1914                .map(Into::into)
1915                .collect();
1916            let (mut output, mut errors) = (Vec::new(), Vec::new());
1917            assert_eq!(
1918                check_command(&args, &mut output, &mut errors),
1919                ExitCode::from(EXIT_USAGE)
1920            );
1921        }
1922    }
1923
1924    #[test]
1925    fn finite_mode_budgets_validate_before_loading_and_report_memory_stops() {
1926        for simulation in [false, true] {
1927            for bad in [
1928                vec!["--time-limit", "0"],
1929                vec!["--max-memory", "lots"],
1930                vec!["--time-limit=0"],
1931                vec!["--max-memory=lots"],
1932            ] {
1933                let mut args = vec!["missing.tla".to_owned()];
1934                args.extend(bad.into_iter().map(str::to_owned));
1935                let (mut output, mut errors) = (Vec::new(), Vec::new());
1936                let status = if simulation {
1937                    simulate_command(&args, &mut output, &mut errors)
1938                } else {
1939                    dfid_command(&args, &mut output, &mut errors)
1940                };
1941                assert_eq!(status, ExitCode::from(EXIT_USAGE));
1942                assert_eq!(output, [] as [u8; 0]);
1943            }
1944            let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1945                .join("../../docs/user/examples/Counter.tla");
1946            for compat in [false, true] {
1947                for inline in [false, true] {
1948                    let mut args =
1949                        vec![file.display().to_string(), "--output".into(), "json".into()];
1950                    args.extend(if simulation {
1951                        vec!["--traces".into(), "1".into()]
1952                    } else {
1953                        vec!["--max-level".into(), "8".into()]
1954                    });
1955                    args.extend(if inline {
1956                        vec!["--max-memory=1".into()]
1957                    } else {
1958                        vec!["--max-memory".into(), "1".into()]
1959                    });
1960                    if compat {
1961                        args.push("--compat=tlc".into());
1962                    }
1963                    let (mut output, mut errors) = (Vec::new(), Vec::new());
1964                    let status = if simulation {
1965                        simulate_command(&args, &mut output, &mut errors)
1966                    } else {
1967                        dfid_command(&args, &mut output, &mut errors)
1968                    };
1969                    assert_eq!(
1970                        status,
1971                        ExitCode::from(5),
1972                        "{}",
1973                        String::from_utf8_lossy(&errors)
1974                    );
1975                    assert!(String::from_utf8_lossy(&output).contains("\"result\":\"stopped\""));
1976                }
1977            }
1978        }
1979    }
1980
1981    #[test]
1982    fn finite_mode_engine_flags_reach_the_actual_compiled_backend() {
1983        let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1984            .join("../../docs/user/examples/Counter.tla");
1985        for simulation in [false, true] {
1986            for inline in [false, true] {
1987                let mut args = vec![
1988                    file.display().to_string(),
1989                    "--output=json".into(),
1990                    "-deadlock".into(),
1991                    "--time-limit=none".into(),
1992                    "--max-memory=none".into(),
1993                ];
1994                if simulation {
1995                    args[1] = "--output".into();
1996                    args.insert(2, "json".into());
1997                }
1998                args.extend(if simulation {
1999                    vec!["--traces".into(), "1".into(), "--depth".into(), "2".into()]
2000                } else {
2001                    vec!["--max-level".into(), "8".into()]
2002                });
2003                args.extend(if inline {
2004                    vec!["--engine=core".into()]
2005                } else {
2006                    vec!["--engine".into(), "core".into()]
2007                });
2008                let (mut output, mut errors) = (Vec::new(), Vec::new());
2009                let status = if simulation {
2010                    simulate_command(&args, &mut output, &mut errors)
2011                } else {
2012                    dfid_command(&args, &mut output, &mut errors)
2013                };
2014                assert_eq!(
2015                    status,
2016                    ExitCode::SUCCESS,
2017                    "{}",
2018                    String::from_utf8_lossy(&errors)
2019                );
2020                assert!(String::from_utf8_lossy(&output).contains("\"engine\":\"core\""));
2021            }
2022        }
2023    }
2024
2025    #[test]
2026    fn search_ceilings_parse_zero_exact_counts_and_none() {
2027        assert_eq!(search_limit("0"), Ok(Some(0)));
2028        assert_eq!(search_limit("42"), Ok(Some(42)));
2029        assert_eq!(search_limit("none"), Ok(None));
2030        for bad in ["", "-1", "1.5", "18446744073709551616", "auto"] {
2031            assert!(search_limit(bad).is_err(), "{bad}");
2032        }
2033    }
2034}
2035
2036fn symmetry_liveness(value: &str) -> Option<dive_api::SymmetryLiveness> {
2037    match value {
2038        "unreduced" => Some(dive_api::SymmetryLiveness::Unreduced),
2039        "refuse" => Some(dive_api::SymmetryLiveness::Refuse),
2040        "tlc" => Some(dive_api::SymmetryLiveness::Tlc),
2041        _ => None,
2042    }
2043}
2044
2045#[cfg(test)]
2046mod symmetry_liveness_tests {
2047    #![allow(clippy::expect_used, reason = "finite argument and report controls")]
2048    use super::*;
2049    fn arguments(args: &[&str]) -> Vec<String> {
2050        args.iter().map(|arg| (*arg).into()).collect()
2051    }
2052    #[test]
2053    fn unknown_modes_are_usage_errors_before_any_input_access() {
2054        for args in [
2055            arguments(&["Missing.tla", "--symmetry-liveness=unknown"]),
2056            arguments(&["--symmetry-liveness", "bad", "Missing.tla"]),
2057        ] {
2058            let mut out = Vec::new();
2059            let mut err = Vec::new();
2060            assert_eq!(
2061                check_command(&args, &mut out, &mut err),
2062                ExitCode::from(EXIT_USAGE)
2063            );
2064            assert!(String::from_utf8_lossy(&err).contains("--symmetry-liveness expects"));
2065            assert_eq!(out, [] as [u8; 0]);
2066            assert_eq!(
2067                validate_trace_command(&args, &mut out, &mut err),
2068                ExitCode::from(EXIT_USAGE)
2069            );
2070        }
2071    }
2072    #[test]
2073    fn explicit_mode_survives_native_profile_flag_order_and_adapter_transport() {
2074        let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2075            .join("../../conformance/corpus/probes/specifications/P4SymLive/P4SymLive.tla");
2076        let file = file.to_str().expect("fixture path");
2077        for native in [true, false] {
2078            for reverse in [false, true] {
2079                let mut args = if native {
2080                    arguments(&[
2081                        file,
2082                        "--output=json",
2083                        "--workers=1",
2084                        "--seed=0",
2085                        "--fp=0",
2086                        "--max-memory=none",
2087                        "--time-limit=none",
2088                    ])
2089                } else {
2090                    arguments(&[
2091                        file,
2092                        "--output=json",
2093                        "--workers=1",
2094                        "--seed=0",
2095                        "--fp=0",
2096                        "--max-memory=none",
2097                    ])
2098                };
2099                let selection = if reverse {
2100                    ["--symmetry-liveness=unreduced", "--compat=tlc"]
2101                } else {
2102                    ["--compat=tlc", "--symmetry-liveness=unreduced"]
2103                };
2104                if native {
2105                    args.extend(arguments(&selection));
2106                } else {
2107                    args.push("--symmetry-liveness=unreduced".into());
2108                }
2109                let mut out = Vec::new();
2110                let mut err = Vec::new();
2111                let status = if native {
2112                    check_command(&args, &mut out, &mut err)
2113                } else {
2114                    tlc::command(&args, &mut out, &mut err)
2115                };
2116                assert_eq!(
2117                    status,
2118                    ExitCode::SUCCESS,
2119                    "{}",
2120                    String::from_utf8_lossy(&err)
2121                );
2122                let report: serde_json::Value = serde_json::from_slice(&out).expect("actual JSON");
2123                assert_eq!(report["options"]["profile"], "tlc+overrides");
2124                assert_eq!(report["options"]["symmetry_liveness"], "unreduced");
2125                assert_eq!(report["symmetry_liveness"]["scope"], "whole-run");
2126                assert_eq!(report["statistics"]["distinct"], 2);
2127            }
2128        }
2129    }
2130}
2131
2132#[cfg(test)]
2133mod validation_exception_tests {
2134    #[test]
2135    fn aborted_validation_json_is_an_exception_without_a_result()
2136    -> Result<(), Box<dyn std::error::Error>> {
2137        let mut out = Vec::new();
2138        let mut err = Vec::new();
2139        let error = dive_api::trace::ValidationRunError::ThreadFailure(
2140            "test isolated thread did not return".into(),
2141        );
2142        let status = super::validation_exception(&mut out, &mut err, &error, true);
2143        assert_eq!(status, std::process::ExitCode::from(4));
2144        let value: serde_json::Value = serde_json::from_slice(&out)?;
2145        assert_eq!(value["schema_version"], 3);
2146        assert_eq!(value["command"], "validate-trace");
2147        assert_eq!(value["validation_completed"], false);
2148        assert_eq!(value["error"]["kind"], "execution-error");
2149        assert!(value.get("result").is_none());
2150        assert!(value.get("verdict").is_none());
2151        assert_eq!(err, [] as [u8; 0]);
2152        Ok(())
2153    }
2154}