Skip to main content

dive_api/
check.rs

1//! Model checking (`dive check`): load, bind and check a specification, and
2//! report the result as a versioned JSON document or TLC-style text.
3
4use std::path::PathBuf;
5use std::sync::Arc;
6use std::time::Duration;
7
8use dive_eval::Profile;
9use dive_runtime::{CheckOptions, CheckResult, Verdict};
10use dive_sema::{Options, SearchPath};
11use dive_store::StoreMode;
12use serde_json::{Value, json};
13
14use crate::{AnalyzeReport, ConfigReport};
15
16#[path = "candidate_error.rs"]
17mod candidate_error;
18
19/// Version of ordinary safety JSON documents produced by [`CheckReport::to_json`].
20pub const CHECK_SCHEMA_VERSION: u32 = crate::REPORT_SCHEMA_VERSION;
21
22/// Version of temporal JSON documents, shared with all public reports.
23/// Temporal claims require their actual final or prefix execution facts.
24pub const TEMPORAL_CHECK_SCHEMA_VERSION: u32 = crate::REPORT_SCHEMA_VERSION;
25
26/// Historical native exit codes, selected by `dive check --exit-codes native`
27/// and the dive profile's [`CheckReport::exit_code`]. The CLI default uses TLC's
28/// deciding status independently of evaluator profile (`EC.ExitStatus`: 0,
29/// 10–14, 75–77, 150, 151, 255). Codes below marked "both" keep their meaning.
30pub mod exit {
31    /// No error found.
32    pub const SUCCESS: u8 = 0;
33    /// The specification or configuration was rejected, or TLC's binding
34    /// of the model failed (dive profile; TLC's 150/151 under `--compat=tlc`).
35    pub const REJECTED: u8 = 1;
36    /// A malformed command line or unreadable input (both).
37    pub const USAGE: u8 = 2;
38    /// dive refused, naming the feature, or hit a resource limit; no verdict
39    /// (both).
40    pub const UNSUPPORTED: u8 = 3;
41    /// An internal error in dive; no verdict (both).
42    pub const INTERNAL: u8 = 4;
43    /// The run's budget (`--time-limit`, `--max-memory`) ran out; no verdict
44    /// (both).
45    pub const STOPPED: u8 = 5;
46    /// An invariant, property, action property or postcondition is violated.
47    pub const VIOLATION: u8 = 10;
48    /// A deadlock was reached.
49    pub const DEADLOCK: u8 = 11;
50    /// An assumption is false or failed to evaluate.
51    pub const ASSUMPTION: u8 = 12;
52    /// Evaluation failed: an error, a failed `Assert`, an overflow, an
53    /// incompletely specified state.
54    pub const EVALUATION: u8 = 13;
55}
56
57/// Process status conventions, independently of evaluator semantics.
58///
59/// `dive check` selects [`Self::Tlc`] by default. Existing
60/// [`CheckReport::exit_code`] callers retain their profile's historical status;
61/// select explicitly with [`CheckReport::exit_code_for`].
62///
63/// ```
64/// use dive_api::{CheckReport, ExitConvention};
65/// fn process_status(report: &CheckReport) -> u8 {
66///     report.exit_code_for(ExitConvention::Tlc)
67/// }
68/// # let _ = process_status;
69/// ```
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71#[non_exhaustive]
72pub enum ExitConvention {
73    /// Historical native statuses, including violation 10 and rejection 1.
74    Native,
75    /// The existing deciding TLC error-class status, without changing evaluation.
76    Tlc,
77}
78
79impl ExitConvention {
80    /// The CLI spelling reported in `options.exit_codes`.
81    #[must_use]
82    pub const fn as_str(self) -> &'static str {
83        match self {
84            Self::Native => "native",
85            Self::Tlc => "tlc",
86        }
87    }
88}
89
90/// The store `dive check` uses.
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
92#[non_exhaustive]
93pub enum Store {
94    /// Fingerprints (the default, as in TLC).
95    #[default]
96    Fingerprint,
97    /// Full states (`--store exact`): an exhaustive result with no
98    /// fingerprint-collision caveat.
99    Exact,
100}
101
102/// A run-budget setting: the profile's default, no limit, or an
103/// explicit value.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
105pub enum BudgetSetting<T> {
106    /// The profile's default: for the time limit none in both profiles, as in
107    /// TLC; for memory [`dive_runtime::budget::default_memory`] in both.
108    #[default]
109    Default,
110    /// No limit (`none`).
111    Unlimited,
112    /// This limit.
113    Explicit(T),
114}
115
116impl<T: Copy> BudgetSetting<T> {
117    pub(crate) fn resolve(self, default: Option<T>) -> (Option<T>, &'static str) {
118        match self {
119            Self::Default => (default, if default.is_some() { "default" } else { "none" }),
120            Self::Unlimited => (None, "none"),
121            Self::Explicit(value) => (Some(value), "explicit"),
122        }
123    }
124}
125
126/// Temporal checking strategy for a request.
127#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
128#[non_exhaustive]
129pub enum TemporalMode {
130    /// Ordinary checking. Eligible temporal requests use bounded final analysis
131    /// in the TLC profile and deterministic completed-level checks in the dive
132    /// profile.
133    #[default]
134    Ordinary,
135}
136
137/// What to check and how.
138#[derive(Clone, Debug, Default)]
139#[allow(
140    clippy::struct_excessive_bools,
141    reason = "independent public checking options retain their boolean API"
142)]
143pub struct CheckRequest {
144    /// Opt-in authenticated native pure-safety workers. None is TLC-equivalent.
145    /// Requires explicit Core, seed and fingerprint; secret bytes never enter reports.
146    ///
147    /// ```no_run
148    /// use dive_api::{CheckRequest, DistributedOptions, check_file};
149    /// let request = CheckRequest {
150    ///     file: "Counter.tla".into(), seed: Some(0), fp: Some(0),
151    ///     distributed: Some(DistributedOptions::new(
152    ///         vec!["127.0.0.1:7801".parse()?, "127.0.0.1:7802".parse()?],
153    ///         "worker.key".into(),
154    ///     )),
155    ///     ..CheckRequest::default()
156    /// };
157    /// let report = check_file(&request)?;
158    /// println!("{}", report.to_json());
159    /// # Ok::<(), Box<dyn std::error::Error>>(())
160    /// ```
161    pub distributed: Option<crate::DistributedOptions>,
162    /// Explicit producer-only Core debugger capability. None is the ordinary
163    /// TLC-equivalent setting; use `debug::Session` for a managed session.
164    pub debugger: Option<Arc<dyn dive_core::debug::Observer>>,
165    /// `--source-coverage`: native source-expression work. Core does not
166    /// implement it, so `true` is a named refusal.
167    pub source_coverage: bool,
168    /// `--coverage 0`: TLC's logical action-context costs. Core does not
169    /// implement them, so `true` is a named refusal.
170    pub tlc_coverage: bool,
171    /// Explicit spec host categories, default-empty in both profiles: a
172    /// specification gets host access only when it is granted.
173    /// The first slice supports source-binding environment and TXT/UTF-8 reads.
174    pub host_access: crate::HostAccess,
175    /// Explicit bounded transient disk seen-state route. None keeps the memory
176    /// reference; disk uses reported inline fallback and is not a total-RAM budget.
177    pub seen_disk: Option<dive_runtime::SeenOptions>,
178    /// Opt-in encoded frontier budget per current/next queue, in bytes. This
179    /// does not bound seen sets, candidates, traces, graphs or process memory.
180    pub frontier_memory_bytes: Option<usize>,
181    /// Parent directory for private transient frontier spill files. Requires
182    /// [`Self::frontier_memory_bytes`]; a directory alone is rejected.
183    pub frontier_directory: Option<PathBuf>,
184    /// Encoded candidate bytes per worker for explicit Core pure safety BFS.
185    /// Zero forces disk. This excludes active evaluator roots, codec scratch,
186    /// accepted Store values and whole-process memory.
187    pub candidate_memory_bytes: Option<usize>,
188    /// Parent directory for private candidate files; requires a candidate budget.
189    pub candidate_directory: Option<PathBuf>,
190    /// Opt-in completed-level measured Store-byte trigger under pure Core safety.
191    /// Zero forces every boundary. This is not a live-root or process-memory cap.
192    /// The TLC-equivalent setting is None. Recovery-only is supported.
193    pub store_compact_bytes: Option<usize>,
194    /// Separate retained predecessor-record capacity budget for safety BFS.
195    /// Zero spills immediately; omitted preserves the in-memory counterpart.
196    /// Reconstruction buffers and all other search storage are outside it.
197    pub predecessor_memory_bytes: Option<usize>,
198    /// Parent of private transient log directories. Requires a budget; omitted
199    /// uses the system temporary directory. Files are removed before certification.
200    pub predecessor_directory: Option<PathBuf>,
201    /// The root module file.
202    pub file: PathBuf,
203    /// The configuration; `<file stem>.cfg` beside it by default, as in TLC.
204    pub config: Option<PathBuf>,
205    /// Module directories searched before the standard modules.
206    pub library_paths: Vec<PathBuf>,
207    /// Module directories searched after the standard modules.
208    pub module_paths: Vec<PathBuf>,
209    /// `--compat=tlc`.
210    pub compat_tlc: bool,
211    /// Whole-run symmetry/liveness policy; profile default when omitted.
212    /// TLC-equivalent: `Tlc`, currently refused for quotient temporal checking.
213    pub symmetry_liveness: Option<dive_model::SymmetryLiveness>,
214    /// `--action-composition off|tlc|tla`; `None` is the profile's
215    /// setting: `tla` by default, `off` under `--compat=tlc` (TLC without
216    /// `-Dtlc2.tool.impl.Tool.cdot=true`).
217    pub action_composition: Option<dive_eval::ActionComposition>,
218    /// The store.
219    pub store: Store,
220    /// `--seed`; a fresh seed otherwise (always reported).
221    pub seed: Option<i64>,
222    /// `--core-sample N` (`--engine core`): after the search, compare the
223    /// successors of `N` sampled expanded states with the dive-eval
224    /// evaluator's. Diagnostic
225    /// only: every result is unchanged. `None` samples nothing.
226    pub core_sample: Option<usize>,
227    /// `--fp`; TLC picks one at random under `--compat=tlc`, dive uses 0.
228    pub fp: Option<usize>,
229    /// `--workers`; `None` is the profile's default (TLC's 1 under
230    /// `--compat=tlc`, the available parallelism otherwise).
231    pub workers: Option<usize>,
232    /// TLC's `-deadlock`: do not check for deadlock.
233    pub no_deadlock: bool,
234    /// `--sequential`: every level inline with one logical worker, as
235    /// sequential mode does. Results are identical.
236    pub sequential: bool,
237    /// Test-only chaos scheduling (`--chaos SEED`, or `DIVE_CHAOS`); see
238    /// `dive_runtime::CheckOptions::chaos`. Results must be identical.
239    pub chaos: Option<u64>,
240    /// Temporal checking strategy. `Ordinary` selects final analysis for
241    /// eligible TLC-profile temporal roles and deterministic completed-level
242    /// checks for eligible dive-profile roles. Unsupported combinations retain
243    /// named refusals.
244    pub temporal: TemporalMode,
245    /// CLI-internal: refuse the model's temporal properties instead of
246    /// checking them, appending this text to the refusal. The `dive` CLI sets
247    /// it for strategies it accepts but Core does not implement, such as
248    /// `--lncheck final --lasso short`. A model without temporal properties
249    /// is checked as usual. Not part of the supported API.
250    #[doc(hidden)]
251    pub temporal_refusal: Option<String>,
252    /// Completed-level schedule for ordinary dive-profile temporal checking
253    /// (TLC checks only at the end). The default is the documented [`PeriodicSchedule::DEFAULT`];
254    /// TLC-profile and explicit final requests ignore it and check once at the end.
255    pub periodic: PeriodicSchedule,
256    /// `--time-limit`: wall-clock time for the whole check.
257    pub time_limit: BudgetSetting<std::time::Duration>,
258    /// `--max-memory`: the whole process's resident-memory
259    /// ceiling, in bytes.
260    pub max_memory: BudgetSetting<u64>,
261    /// Maximum admitted distinct in-model identities; `None` is TLC-equivalent.
262    pub max_states: Option<u64>,
263    /// Maximum BFS discovery depth (Init is depth one); `None` is TLC-equivalent.
264    pub max_depth: Option<u64>,
265}
266
267/// Completed-level schedule for ordinary dive-profile temporal checking.
268pub use dive_liveness::analyze::periodic::Schedule as PeriodicSchedule;
269
270/// The phase a check ended in.
271#[derive(Debug)]
272enum Phase {
273    /// Resource exhaustion observed before model binding begins.
274    BudgetStopped(dive_runtime::budget::Stopped),
275    /// The specification was rejected by the front end.
276    SpecRejected(Box<AnalyzeReport>),
277    /// The configuration was rejected.
278    ConfigRejected(Box<ConfigReport>),
279    /// The specification could not be lowered (a refusal).
280    Unlowered(String),
281    /// The checker ran.
282    Checked(Box<CheckResult>),
283    /// Independently validated bounded temporal analysis.
284    Temporal(Box<crate::temporal::Report>),
285    /// No temporal verdict: a refusal, limit, evaluation or internal failure.
286    TemporalError(Box<crate::temporal::Failure>),
287}
288
289/// The outcome of `dive check`.
290#[derive(Debug)]
291pub struct CheckReport {
292    checkpoint_request: Option<dive_runtime::checkpoint::Request>,
293    checkpoint_receipt: Option<dive_runtime::checkpoint::Receipt>,
294    file: String,
295    config: String,
296    profile: Profile,
297    opts: CheckOptions,
298    seed_given: bool,
299    symmetry_liveness_explicit: bool,
300    fp_given: bool,
301    workers_requested: usize,
302    /// Where the time and memory limits came from: `default`, `explicit`
303    /// or `none`.
304    budget_sources: (&'static str, &'static str),
305    memory_requested_source: &'static str,
306    memory_samples: Option<dive_runtime::budget::MemorySamples>,
307    temporal_configuration: crate::temporal::Configuration,
308    phase: Phase,
309    /// The core engine's run, when `--engine=core` ran the check.
310    core: Option<Box<crate::core_engine::CoreRun>>,
311    /// Untrusted original source context captured while this run owns the IR.
312    next_error_endpoint: Option<dive_trace::NextStateEndpoint>,
313    /// Untrusted candidate-site observation; fresh replay proves its identities.
314    candidate_error_endpoint: Option<dive_trace::CandidateStateEndpoint>,
315    view_error_endpoint: Option<dive_trace::ViewSourceEndpoint>,
316    /// Observed partial candidate captured while its original IR is owned.
317    partial_terminal_endpoint: Option<dive_trace::PartialNextEndpoint>,
318}
319
320/// Names the first coordinator option that distributed safety does not admit,
321/// before the model, configuration or key file is read.
322fn distributed_refusal(req: &CheckRequest, checkpoint: bool) -> Option<String> {
323    let missing = if req.seed.is_none() {
324        Some("--seed")
325    } else if req.fp.is_none() {
326        Some("--fp")
327    } else {
328        None
329    };
330    if let Some(flag) = missing {
331        return Some(format!(
332            "distributed safety without an explicit {flag} is not implemented; give the same {flag} to the coordinator and every worker"
333        ));
334    }
335    let feature = if checkpoint {
336        "checkpoint or recovery"
337    } else if req.core_sample.is_some() {
338        "--core-sample"
339    } else if !req.host_access.is_empty() {
340        "spec host-access grants"
341    } else if req.sequential {
342        "--sequential"
343    } else if req.chaos.is_some() {
344        "chaos scheduling"
345    } else if req.source_coverage {
346        "source coverage"
347    } else if req.seen_disk.is_some() {
348        "disk-backed seen storage"
349    } else if req.candidate_memory_bytes.is_some() {
350        "candidate spill"
351    } else {
352        return None;
353    };
354    Some(format!(
355        "distributed safety with {feature} is not implemented"
356    ))
357}
358
359fn admit_storage_request(req: &CheckRequest) -> Result<(), crate::ApiError> {
360    if req.store_compact_bytes.is_some() && req.core_sample.is_some() {
361        return Err(crate::ApiError::Unsupported {
362            feature: "Store reclamation with temporal capture or sampling".into(),
363        });
364    }
365    if let Some(disk) = &req.seen_disk {
366        disk.limits
367            .validate()
368            .map_err(|error| crate::ApiError::Rejected {
369                message: error.to_string(),
370            })?;
371    }
372    if req.candidate_directory.is_some() && req.candidate_memory_bytes.is_none() {
373        return Err(crate::ApiError::Rejected {
374            message: "DIVE-A0102: candidate_directory requires candidate_memory_bytes".into(),
375        });
376    }
377    if req.frontier_directory.is_some() && req.frontier_memory_bytes.is_none() {
378        return Err(crate::ApiError::Rejected {
379            message: "DIVE-A0100: frontier_directory requires frontier_memory_bytes".into(),
380        });
381    }
382    if req.predecessor_directory.is_some() && req.predecessor_memory_bytes.is_none() {
383        return Err(crate::ApiError::Rejected {
384            message: "DIVE-A0101: predecessor directory requires predecessor memory budget".into(),
385        });
386    }
387    Ok(())
388}
389
390/// Loads, binds and checks the request with the compiled Core. What Core
391/// does not implement is an `unsupported` verdict naming it.
392///
393/// ```no_run
394/// use dive_api::{CheckRequest, check_file};
395/// let req = CheckRequest { file: "Spec.tla".into(), ..CheckRequest::default() };
396/// let report = check_file(&req).unwrap();
397/// println!("{}", report.to_json()["engine"]);
398/// ```
399///
400/// # Errors
401/// [`crate::ApiError`] if the root file or the configuration cannot be read.
402pub fn check_file(req: &CheckRequest) -> Result<CheckReport, crate::ApiError> {
403    check_file_in(req, None, false, None)
404}
405
406/// Checks with Core under explicit strategy switches, as
407/// `DIVE_CORE_OPT` gives them (for example `-memo,-delta-hash`); the
408/// environment variable is ignored. Every switch must leave every result
409/// unchanged.
410///
411/// # Errors
412/// As [`check_file`].
413pub fn check_file_core_opts(
414    req: &CheckRequest,
415    switches: &str,
416) -> Result<CheckReport, crate::ApiError> {
417    check_file_in(req, None, false, Some(switches))
418}
419
420/// Loads and checks files with TLC's configuration-first input error priority.
421///
422/// Used by the `dive tlc` and `tlc` checking entrypoints after resolving their
423/// filenames. Unlike [`check_file`], this reads and parses the configuration
424/// before analyzing the module: an unreadable or malformed configuration wins
425/// when both inputs are invalid. Request defaults and path spellings are unchanged.
426///
427/// ```no_run
428/// use dive_api::{CheckRequest, check_file_tlc_inputs};
429/// let request = CheckRequest {
430///     file: "Counter.tla".into(),
431///     compat_tlc: true,
432///     ..CheckRequest::default()
433/// };
434/// let report = check_file_tlc_inputs(&request)?;
435/// # Ok::<(), dive_api::ApiError>(())
436/// ```
437///
438/// # Errors
439/// [`crate::ApiError`] if the configuration or root file cannot be read.
440pub fn check_file_tlc_inputs(req: &CheckRequest) -> Result<CheckReport, crate::ApiError> {
441    check_file_in(req, None, true, None)
442}
443
444/// Runs the native pure-safety checkpoint/recovery slice. It refuses
445/// temporal combinations before loading files. Existing frontier/predecessor
446/// budgets configure transient storage; native archive work is separately bounded
447/// and excluded from both budgets. Recovery uses
448/// saved seed/fingerprint defaults when not explicitly supplied; profile/store
449/// and all semantic options must match. Actual workers are reported separately.
450///
451/// ```no_run
452/// use dive_api::{CheckRequest, check_file_checkpoint, checkpoint};
453/// let model = CheckRequest { file: "Counter.tla".into(), ..CheckRequest::default() };
454/// let native = checkpoint::Request {
455///     path: "counter.cp".into(),
456///     action: checkpoint::Action::PauseAfterLevels(2),
457///     counters: checkpoint::Counters::Tlc,
458///     config_source_sha256: None,
459/// };
460/// let report = check_file_checkpoint(&model, &native)?;
461/// assert_eq!(report.to_json()["options"]["checkpoint"]["action"], "pause");
462/// # Ok::<(), dive_api::ApiError>(())
463/// ```
464///
465/// # Errors
466/// File I/O or malformed native request/metadata, without a model verdict.
467pub fn check_file_checkpoint(
468    req: &CheckRequest,
469    checkpoint: &dive_runtime::checkpoint::Request,
470) -> Result<CheckReport, crate::ApiError> {
471    check_file_in(req, Some(checkpoint), false, None)
472}
473
474#[allow(
475    clippy::too_many_lines,
476    reason = "single ordered loader dispatch for ordinary and native recovery admission"
477)]
478fn check_file_in(
479    req: &CheckRequest,
480    checkpoint: Option<&dive_runtime::checkpoint::Request>,
481    config_first: bool,
482    core_switches: Option<&str>,
483) -> Result<CheckReport, crate::ApiError> {
484    if req.debugger.is_some() {
485        let feature = if req.store_compact_bytes.is_some() {
486            Some("compiled debugger with Store reclamation is not implemented")
487        } else if req.tlc_coverage {
488            Some("compiled debugger with TLC logical coverage is not implemented")
489        } else if req.source_coverage {
490            Some("compiled debugger with native source coverage is not implemented")
491        } else if req.distributed.is_some() {
492            Some("compiled debugger with distributed safety checking is not implemented")
493        } else {
494            None
495        };
496        if let Some(feature) = feature {
497            return Err(crate::ApiError::Unsupported {
498                feature: feature.into(),
499            });
500        }
501    }
502    admit_storage_request(req)?;
503    if req.debugger.is_some()
504        && (checkpoint.is_some() || req.temporal_refusal.is_some() || req.core_sample.is_some())
505    {
506        return Err(crate::ApiError::Unsupported { feature: "compiled debugger requires explicit Core ordinary safety checking without coverage, sampling or checkpoint".into() });
507    }
508    if req.distributed.is_some() && req.store_compact_bytes.is_some() {
509        return Err(crate::ApiError::Unsupported {
510            feature: "distributed safety with Store reclamation is not implemented".into(),
511        });
512    }
513    if req.distributed.is_some() && req.tlc_coverage {
514        return Err(crate::ApiError::Unsupported {
515            feature: "distributed safety with TLC logical coverage is not implemented".into(),
516        });
517    }
518    if req.distributed.is_some()
519        && let Some(feature) = distributed_refusal(req, checkpoint.is_some())
520    {
521        return Err(crate::ApiError::Unsupported { feature });
522    }
523    if req.store_compact_bytes.is_some()
524        && checkpoint
525            .is_some_and(|request| request.action != dive_runtime::checkpoint::Action::Recover)
526    {
527        return Err(crate::ApiError::Unsupported {
528            feature: "Store reclamation with checkpoint pause (discovery residency is unsupported)"
529                .into(),
530        });
531    }
532    if req.source_coverage && req.tlc_coverage {
533        return Err(crate::ApiError::Unsupported {
534            feature: "request native source work or TLC logical coverage separately".into(),
535        });
536    }
537    if req.source_coverage || req.tlc_coverage {
538        return Err(crate::ApiError::Unsupported { feature: "source coverage and TLC logical coverage (--source-coverage, --coverage) are not implemented on Core".into() });
539    }
540    if !req.host_access.is_empty() {
541        return Err(crate::ApiError::Unsupported {
542            feature: "external inputs (--allow-io, IOUtils/IOEnv) are not implemented on Core, nor with temporal checking or checkpoint/recovery"
543                .into(),
544        });
545    }
546    let profile = if req.compat_tlc {
547        Profile::Tlc
548    } else {
549        Profile::Dive
550    };
551    let recovered_defaults = if let Some(request) = checkpoint
552        && request.action == dive_runtime::checkpoint::Action::Recover
553    {
554        let defaults = crate::core_checkpoint::metadata(&request.path).map_err(|message| {
555            crate::ApiError::Rejected {
556                message: format!("DIVE-S0400: {message}"),
557            }
558        })?;
559        Some(defaults)
560    } else {
561        None
562    };
563    let seed = req
564        .seed
565        .or(recovered_defaults.map(|p| p.0))
566        .unwrap_or_else(dive_stdlib::random::fresh_seed);
567    let fp = req
568        .fp
569        .or(recovered_defaults.map(|p| p.1))
570        .unwrap_or_else(|| {
571            if req.compat_tlc {
572                // TLC: a random polynomial per run unless `-fp` is given
573                // (`TLC.java`); reported either way.
574                usize::try_from(seed.unsigned_abs() % 131).unwrap_or(0)
575            } else {
576                0
577            }
578        });
579    let workers_requested = req.workers.unwrap_or_else(|| {
580        if req.compat_tlc {
581            1
582        } else {
583            std::thread::available_parallelism().map_or(1, std::num::NonZero::get)
584        }
585    });
586    let mut opts = if req.compat_tlc {
587        CheckOptions::tlc(fp, seed)
588    } else {
589        let mut o = CheckOptions::dive(seed);
590        o.fp_index = fp;
591        o
592    };
593    opts.eval.host_access = req.host_access;
594    if !req.host_access.is_empty() {
595        opts.inputs = Some(Arc::new(dive_stdlib::inputs::LiveInputs::new(
596            req.host_access,
597        )));
598    }
599    opts.store = match req.store {
600        Store::Fingerprint => StoreMode::Fingerprint,
601        Store::Exact => StoreMode::Exact,
602    };
603    opts.no_deadlock = req.no_deadlock;
604    if let Some(policy) = req.symmetry_liveness {
605        opts.symmetry_liveness = policy;
606    }
607    if let Some(mode) = req.action_composition {
608        opts.eval.action_composition = mode;
609    }
610    opts.seen_disk.clone_from(&req.seen_disk);
611    opts.frontier_memory_bytes = req.frontier_memory_bytes;
612    opts.frontier_directory.clone_from(&req.frontier_directory);
613    opts.candidate_memory_bytes = req.candidate_memory_bytes;
614    opts.store_compact_bytes = req.store_compact_bytes;
615    opts.candidate_directory
616        .clone_from(&req.candidate_directory);
617    opts.workers = workers_requested;
618    opts.sequential = req.sequential;
619    opts.chaos = req.chaos;
620    opts.predecessor_memory_bytes = req.predecessor_memory_bytes;
621    opts.max_states = req.max_states;
622    opts.max_depth = req.max_depth;
623    opts.predecessor_directory
624        .clone_from(&req.predecessor_directory);
625    let (time, time_source) = req.time_limit.resolve(None);
626    let memory_resolution = resolve_memory(req.max_memory, dive_runtime::budget::default_memory);
627    let memory_requested_source = match req.max_memory {
628        BudgetSetting::Default => "default",
629        BudgetSetting::Explicit(_) => "explicit",
630        BudgetSetting::Unlimited => "none",
631    };
632    let (memory, memory_source) = memory_resolution.unwrap_or((None, "unavailable"));
633    opts.budget = dive_runtime::budget::Budget::new(time, memory);
634    let cfg_path = req
635        .config
636        .clone()
637        .unwrap_or_else(|| req.file.with_extension("cfg"));
638    let mut report = CheckReport {
639        checkpoint_request: checkpoint.cloned(),
640        checkpoint_receipt: None,
641        file: req.file.display().to_string(),
642        config: cfg_path.display().to_string(),
643        profile,
644        opts,
645        seed_given: req.seed.is_some(),
646        symmetry_liveness_explicit: req.symmetry_liveness.is_some(),
647        fp_given: req.fp.is_some(),
648        workers_requested,
649        budget_sources: (time_source, memory_source),
650        memory_requested_source,
651        memory_samples: None,
652        temporal_configuration: crate::temporal::file_configuration(),
653        phase: Phase::Unlowered(String::new()),
654        core: None,
655        next_error_endpoint: None,
656        candidate_error_endpoint: None,
657        view_error_endpoint: None,
658        partial_terminal_endpoint: None,
659    };
660    // TLC's Spec constructor parses ModelConfig before creating SpecProcessor
661    // (tlaplus 94d0c50). Keep the file API's existing module-first order.
662    let config = if config_first {
663        let cfg = crate::parse_config_file(&cfg_path)?;
664        if !cfg.accepted() {
665            report.phase = Phase::ConfigRejected(Box::new(cfg));
666            return Ok(report);
667        }
668        Some(cfg)
669    } else {
670        None
671    };
672    let search = Options {
673        search: SearchPath {
674            library_paths: req.library_paths.clone(),
675            after_standard: req.module_paths.clone(),
676        },
677        ..Options::default()
678    };
679    let analysis =
680        dive_sema::analyze_file(&req.file, &search).map_err(|error| crate::ApiError::Io {
681            path: report.file.clone(),
682            error,
683        })?;
684    if !analysis.accepted() {
685        report.phase = Phase::SpecRejected(Box::new(AnalyzeReport::from_analysis(
686            report.file.clone(),
687            analysis,
688        )));
689        return Ok(report);
690    }
691    let cfg = match config {
692        Some(cfg) => cfg,
693        None => crate::parse_config_file(&cfg_path)?,
694    };
695    let Some(model) = cfg.config().cloned() else {
696        report.phase = Phase::ConfigRejected(Box::new(cfg));
697        return Ok(report);
698    };
699    let ir = match dive_ir::lower(&analysis) {
700        Ok(ir) => Arc::new(ir),
701        Err(e) => {
702            report.phase = Phase::Unlowered(format!("lowering the specification: {e:?}"));
703            return Ok(report);
704        }
705    };
706    // One clock and one ceiling for every stage of the check itself; loading,
707    // parsing and lowering above are not budgeted.
708    memory_resolution.map_err(crate::ApiError::BudgetMeasurement)?;
709    let checking_started = std::time::Instant::now();
710    let (mut watchdog, armed) =
711        dive_runtime::budget::arm(&report.opts).map_err(|error| match error {
712            dive_runtime::budget::StartError::Measurement(error) => {
713                crate::ApiError::BudgetMeasurement(error)
714            }
715            error => crate::ApiError::BudgetStartup(error),
716        })?;
717    let armed = armed.into_owned();
718    report.phase = if let Some(exhausted) = armed
719        .budget
720        .poll()
721        .map_err(crate::ApiError::BudgetMeasurement)?
722    {
723        Phase::BudgetStopped(exhausted.during(dive_runtime::budget::Phase::Startup))
724    } else if let Some(request) = checkpoint {
725        let mut request = request.clone();
726        request.config_source_sha256 = Some(dive_runtime::checkpoint::config_source_hash(
727            cfg.source_bytes(),
728        ));
729        let (native, run) =
730            crate::core_checkpoint::check(&ir, &model, &armed, &request, profile == Profile::Tlc);
731        report.core = Some(Box::new(run));
732        report.checkpoint_receipt = native.receipt;
733        Phase::Checked(Box::new(native.check))
734    } else {
735        let config_hash = dive_runtime::checkpoint::config_source_hash(cfg.source_bytes());
736        let (result, run) = crate::core_engine::check(
737            &ir,
738            &model,
739            &armed,
740            req.compat_tlc,
741            core_switches,
742            req.core_sample,
743            core_route(req, &armed),
744            req.distributed
745                .as_ref()
746                .map(|options| (options, config_hash.as_str())),
747            req.debugger.as_ref(),
748        );
749        report.core = Some(Box::new(run));
750        result.into()
751    };
752    if report.core.is_some() {
753        report.temporal_configuration = crate::temporal::core_file_configuration();
754    }
755    // A refused temporal strategy: name it in Core's temporal refusal.
756    if report.core.is_some()
757        && let Some(reason) = &req.temporal_refusal
758        && let Phase::Checked(result) = &mut report.phase
759        && let Verdict::Unsupported { feature } = &mut result.verdict
760        && feature.contains("temporal properties (liveness checking)")
761    {
762        feature.push_str("; ");
763        feature.push_str(reason);
764    }
765    if let Phase::Checked(result) = &mut report.phase {
766        certify_next_receiver(&ir, &model, &armed, result);
767    }
768    if let Phase::Checked(result) = &report.phase
769        && let Verdict::EvaluationError {
770            site: dive_runtime::ErrorSite::Next,
771            cause,
772            reported,
773            code,
774            verified,
775            ..
776        } = &result.verdict
777    {
778        report.next_error_endpoint = if *verified && cause.exception_kind().is_some() {
779            dive_trace::NextStateEndpoint::from_ordered_error(&ir, cause, *reported, *code)
780        } else {
781            dive_trace::NextStateEndpoint::from_error(&ir, cause)
782        };
783    }
784    if let Phase::Checked(result) = &report.phase
785        && let Verdict::EvaluationError {
786            site,
787            cause,
788            reported,
789            code,
790            verified: true,
791            ..
792        } = &result.verdict
793        && matches!(
794            (cause.exception_kind(), *code),
795            (Some(dive_eval::ExceptionKind::ToolRuntime), 2103)
796                | (
797                    Some(dive_eval::ExceptionKind::EvalException),
798                    2132 | 2179 | 2178
799                )
800        )
801    {
802        let site = match site {
803            dive_runtime::ErrorSite::Constraint => Some(dive_trace::CandidateErrorSite::Constraint),
804            dive_runtime::ErrorSite::ActionConstraint => {
805                Some(dive_trace::CandidateErrorSite::ActionConstraint)
806            }
807            dive_runtime::ErrorSite::ImpliedAction => {
808                Some(dive_trace::CandidateErrorSite::ImpliedAction)
809            }
810            _ => None,
811        };
812        if let Some(site) = site {
813            report.candidate_error_endpoint =
814                dive_trace::CandidateStateEndpoint::from_error(&ir, cause, site, *reported, *code);
815        }
816    }
817    if let Phase::Checked(result) = &report.phase
818        && let Verdict::EvaluationError {
819            site: dive_runtime::ErrorSite::View,
820            cause,
821            reported,
822            code,
823            verified: true,
824            ..
825        } = &result.verdict
826        && matches!(
827            (cause.exception_kind(), *code),
828            (Some(dive_eval::ExceptionKind::ToolRuntime), 2103)
829                | (
830                    Some(dive_eval::ExceptionKind::EvalException),
831                    2132 | 2179 | 2178
832                )
833        )
834    {
835        report.view_error_endpoint =
836            dive_trace::ViewSourceEndpoint::from_error(&ir, cause, *reported, *code);
837    }
838    candidate_error::certify(&mut report, &ir, &model, &armed);
839    candidate_error::certify_view(&mut report, &ir, &model, &armed);
840    candidate_error::certify_invariant(&mut report, &ir, &model, &armed);
841    if let Phase::Checked(result) = &report.phase
842        && let Verdict::NotCompletelySpecified {
843            initial,
844            initial_candidate,
845            ..
846        } = &result.verdict
847        && let Some(partial) = if *initial {
848            initial_candidate.as_ref()
849        } else {
850            result
851                .counterexample
852                .as_ref()
853                .and_then(|cx| cx.states.last())
854                .and_then(|state| state.partial.as_ref())
855        }
856    {
857        let mut assignments = serde_json::Map::new();
858        let mut unassigned = Vec::new();
859        let mut encodable = true;
860        for (name, value) in result.var_names.iter().zip(&partial.values) {
861            if *initial && !matches!(armed.budget.poll(), Ok(None)) {
862                encodable = false;
863                break;
864            }
865            if let Some(value) = value {
866                // Init evidence must not force compound/deferred diagnostics
867                // after the actual controlled deciding event. Scalars retain
868                // the report's existing primitive serialization units.
869                if *initial && (value.as_set().is_some() || value.as_fcn().is_some()) {
870                    encodable = false;
871                    break;
872                }
873                if let Ok(value) = dive_trace::value_json::to_json(value, report.opts.eval.ctx) {
874                    assignments.insert(name.clone(), value);
875                } else {
876                    encodable = false;
877                    break;
878                }
879            } else {
880                unassigned.push(name.clone());
881            }
882        }
883        if encodable && partial.values.len() == result.var_names.len() {
884            report.partial_terminal_endpoint = if *initial {
885                dive_trace::PartialStateEndpoint::from_initial_candidate(
886                    &ir,
887                    partial.expression,
888                    assignments,
889                    unassigned,
890                )
891            } else {
892                dive_trace::PartialStateEndpoint::from_candidate(
893                    &ir,
894                    partial.expression,
895                    assignments,
896                    unassigned,
897                )
898            };
899        }
900    }
901    if report.partial_terminal_endpoint.is_none()
902        && let Phase::Checked(result) = &mut report.phase
903        && matches!(
904            result.verdict,
905            Verdict::NotCompletelySpecified { initial: true, .. }
906        )
907    {
908        result.notes.push("Init partial error witness remains unconfirmed: its observed source/bindings were unavailable, its compound assignment encoding is unsupported, or the controlling budget stopped evidence capture.".into());
909    }
910    if let Some(watchdog) = &mut watchdog {
911        let finished = watchdog.finish();
912        report.finish_budget(finished, checking_started.elapsed());
913    }
914    report.memory_samples = armed.budget.memory_samples();
915    drop(watchdog);
916    Ok(report)
917}
918
919/// The core's temporal route for this request: ordinary checking only,
920/// with the default profile's completed-level schedule or, under the TLC
921/// profile, the final check alone (as `check_backend` routes it). A refused
922/// temporal strategy has no route.
923fn core_route(req: &CheckRequest, options: &CheckOptions) -> Option<crate::core_temporal::Route> {
924    req.temporal_refusal
925        .is_none()
926        .then(|| (options.profile == dive_eval::Profile::Dive).then_some(req.periodic))
927}
928
929impl From<crate::core_engine::CoreOutcome> for Phase {
930    fn from(outcome: crate::core_engine::CoreOutcome) -> Self {
931        match outcome {
932            crate::core_engine::CoreOutcome::Checked(r) => Self::Checked(r),
933            crate::core_engine::CoreOutcome::Temporal(r) => Self::Temporal(r),
934            crate::core_engine::CoreOutcome::TemporalFailure(f) => Self::TemporalError(f),
935        }
936    }
937}
938
939pub(crate) fn resolve_memory(
940    setting: BudgetSetting<u64>,
941    default: impl FnOnce() -> Option<u64>,
942) -> Result<(Option<u64>, &'static str), dive_runtime::budget::MeasurementError> {
943    match setting {
944        BudgetSetting::Default => default()
945            .filter(|bytes| *bytes != 0)
946            .map(|bytes| (Some(bytes), "default"))
947            .ok_or_else(dive_runtime::budget::MeasurementError::default_ceiling_unavailable),
948        BudgetSetting::Explicit(bytes) => Ok((Some(bytes), "explicit")),
949        BudgetSetting::Unlimited => Ok((None, "none")),
950    }
951}
952
953/// Admit a diagnostic wrapper only after fresh source-bound word validation.
954/// The producer's typed receiver observation is a request, never a certificate.
955fn certify_next_receiver(
956    ir: &Arc<dive_ir::Ir>,
957    config: &dive_config::ModelConfig,
958    options: &CheckOptions,
959    result: &mut CheckResult,
960) {
961    let Verdict::EvaluationError {
962        site: dive_runtime::ErrorSite::Next,
963        cause,
964        reported,
965        verified: false,
966        ..
967    } = &result.verdict
968    else {
969        return;
970    };
971    if !cause.value_method().is_some_and(|receiver| {
972        receiver.method() == dive_eval::ValueMethod::FunctionMaterialize
973            && receiver.source().is_none()
974    }) {
975        return;
976    }
977    let Some(path) = result
978        .counterexample
979        .as_ref()
980        .filter(|path| path.states.len() == 1)
981    else {
982        return;
983    };
984    let Some(endpoint) =
985        dive_trace::NextStateEndpoint::from_ordered_error(ir, cause, *reported, 2147)
986    else {
987        return;
988    };
989    let request = trace_doc(
990        result,
991        &path.states,
992        options.eval.ctx,
993        Some(&endpoint),
994        None,
995        None,
996        None,
997    )
998    .and_then(|value| dive_trace::TraceDoc::from_json(&value));
999    let Ok(document) = request else {
1000        return;
1001    };
1002    let control = match dive_runtime::budget::EvaluationControl::new(
1003        &options.budget,
1004        dive_runtime::budget::Phase::Validation,
1005    ) {
1006        Ok(control) => control,
1007        Err(error) => {
1008            result
1009                .notes
1010                .push(format!("Next receiver proof refused: {error}"));
1011            return;
1012        }
1013    };
1014    let recipe = dive_model::Recipe::new(
1015        ir.clone(),
1016        config.clone(),
1017        options.eval,
1018        options.no_deadlock,
1019    )
1020    .with_symmetry_liveness(options.symmetry_liveness);
1021    let session = dive_trace::Session::new(recipe, None);
1022    match session.read_controlled(&document, control) {
1023        Ok((report, _)) if report.validation == dive_trace::Validation::Valid => {
1024            if let Verdict::EvaluationError { code, name, verified, .. } = &mut result.verdict {
1025                *code = 2147;
1026                *name = "TLC_FINGERPRINT_EXCEPTION";
1027                *verified = true;
1028            }
1029        }
1030        Ok((report, _)) => result.notes.push(format!(
1031            "Next function receiver diagnostic lifetime remains unproved: {:?}",
1032            report.validation
1033        )),
1034        Err(error) => result.notes.push(format!(
1035            "Next function receiver diagnostic proof stopped; the original cause, class and counts are retained: {error}"
1036        )),
1037    }
1038}
1039
1040impl CheckReport {
1041    fn finish_budget(
1042        &mut self,
1043        finished: Result<
1044            Option<dive_runtime::budget::Exhausted>,
1045            dive_runtime::budget::MeasurementError,
1046        >,
1047        elapsed: Duration,
1048    ) {
1049        match &mut self.phase {
1050            Phase::Checked(result) => {
1051                result.elapsed = elapsed;
1052                dive_runtime::budget::finish_result(
1053                    result,
1054                    finished,
1055                    dive_runtime::budget::Phase::Finalization,
1056                );
1057            }
1058            Phase::Temporal(report) => {
1059                if let Some(failure) = crate::temporal::finish_report(report, finished, elapsed) {
1060                    self.phase = Phase::TemporalError(Box::new(failure));
1061                }
1062            }
1063            // An earlier genuine error keeps its classification.
1064            _ => {}
1065        }
1066    }
1067    fn temporal_schema(&self) -> bool {
1068        matches!(&self.phase, Phase::Temporal(_) | Phase::TemporalError(_))
1069    }
1070
1071    /// The safety checker's result, including a safety stop in final/short
1072    /// checking. Temporal holds/violations use [`Self::temporal_result`].
1073    #[must_use]
1074    pub fn result(&self) -> Option<&CheckResult> {
1075        match &self.phase {
1076            Phase::Checked(r) => Some(r),
1077            _ => None,
1078        }
1079    }
1080
1081    /// Separate original initial-state diagnostic context. This is not a formal
1082    /// counterexample; its named cause and deciding replay need independent proof.
1083    #[must_use]
1084    pub fn diagnostic_witness(&self) -> Option<&dive_runtime::DiagnosticWitness> {
1085        self.result()
1086            .and_then(|result| result.diagnostic_witness.as_ref())
1087    }
1088
1089    /// The validated temporal result, when final/short checking ran. Safety
1090    /// stops are exposed through [`Self::result`] instead.
1091    #[must_use]
1092    pub fn temporal_result(&self) -> Option<&crate::temporal::Report> {
1093        if let Phase::Temporal(r) = &self.phase {
1094            Some(r)
1095        } else {
1096            None
1097        }
1098    }
1099
1100    /// The typed temporal failure, when temporal checking stopped without a
1101    /// verdict: its [`crate::temporal::Error`], stage and available evidence.
1102    #[must_use]
1103    pub fn temporal_failure(&self) -> Option<&crate::temporal::Failure> {
1104        if let Phase::TemporalError(failure) = &self.phase {
1105            Some(failure)
1106        } else {
1107            None
1108        }
1109    }
1110
1111    /// The verdict's name in the JSON document.
1112    #[must_use]
1113    pub fn verdict(&self) -> &'static str {
1114        match &self.phase {
1115            Phase::BudgetStopped(_) => "stopped",
1116            Phase::SpecRejected(_) | Phase::ConfigRejected(_) => "rejected",
1117            Phase::Unlowered(_) => "unsupported",
1118            Phase::Checked(r) => r.verdict.kind(),
1119            Phase::Temporal(r) => match r.outcome() {
1120                crate::temporal::Outcome::NativeHolds(_) => "success",
1121                crate::temporal::Outcome::NativeViolation(_)
1122                | crate::temporal::Outcome::NativePrefixViolation(_) => "liveness-violation",
1123                crate::temporal::Outcome::Safety(_) => "internal-error",
1124            },
1125            Phase::TemporalError(e) => temporal_failure_kind(e),
1126        }
1127    }
1128
1129    /// The historical API profile's exit code (see [`exit`]).
1130    ///
1131    /// This remains native for the dive profile and TLC for the TLC profile.
1132    /// The CLI's independent default is selected with [`Self::exit_code_for`].
1133    #[must_use]
1134    pub fn exit_code(&self) -> u8 {
1135        self.exit_code_for(if self.profile == Profile::Tlc {
1136            ExitConvention::Tlc
1137        } else {
1138            ExitConvention::Native
1139        })
1140    }
1141
1142    /// Selects a process status without changing the evaluator's profile.
1143    ///
1144    /// TLC statuses come from the deciding class, not its reported message.
1145    /// Refusal/resource 3 and internal error 4 are preserved in both conventions.
1146    /// This does not establish parity of an unverified class or model result.
1147    #[must_use]
1148    pub fn exit_code_for(&self, convention: ExitConvention) -> u8 {
1149        let tlc = convention == ExitConvention::Tlc;
1150        match &self.phase {
1151            Phase::BudgetStopped(_) => exit::STOPPED,
1152            Phase::SpecRejected(_) => {
1153                if tlc {
1154                    150
1155                } else {
1156                    exit::REJECTED
1157                }
1158            }
1159            Phase::ConfigRejected(_) => {
1160                if tlc {
1161                    151
1162                } else {
1163                    exit::REJECTED
1164                }
1165            }
1166            Phase::Unlowered(_) => exit::UNSUPPORTED,
1167            Phase::Temporal(r) => match r.outcome() {
1168                crate::temporal::Outcome::NativeHolds(_) => exit::SUCCESS,
1169                crate::temporal::Outcome::NativeViolation(_)
1170                | crate::temporal::Outcome::NativePrefixViolation(_) => {
1171                    if tlc {
1172                        13
1173                    } else {
1174                        exit::VIOLATION
1175                    }
1176                }
1177                crate::temporal::Outcome::Safety(_) => exit::INTERNAL,
1178            },
1179            Phase::TemporalError(e) => match temporal_failure_kind(e) {
1180                "internal-error" => exit::INTERNAL,
1181                "stopped" => exit::STOPPED,
1182                "model-error" => {
1183                    if tlc {
1184                        if let crate::temporal::Error::Binding(failure) = e.error() {
1185                            failure
1186                                .error
1187                                .code()
1188                                .map_or(exit::INTERNAL, dive_runtime::tlc_exit_status)
1189                        } else {
1190                            exit::INTERNAL
1191                        }
1192                    } else {
1193                        exit::REJECTED
1194                    }
1195                }
1196                "evaluation-error" => {
1197                    if tlc {
1198                        if temporal_startup_tautology(e) {
1199                            dive_runtime::tlc_exit_status(
1200                                dive_model::Ec::TlcLiveFormulaTautology.code(),
1201                            )
1202                        } else {
1203                            temporal_evaluation(e).map_or(exit::INTERNAL, |error| {
1204                                dive_runtime::tlc_exit_status(error.ec().code())
1205                            })
1206                        }
1207                    } else {
1208                        exit::EVALUATION
1209                    }
1210                }
1211                _ => exit::UNSUPPORTED,
1212            },
1213            Phase::Checked(r) => {
1214                let v = &r.verdict;
1215                match v {
1216                    Verdict::Unsupported { .. } | Verdict::ResourceLimit { .. } => {
1217                        exit::UNSUPPORTED
1218                    }
1219                    Verdict::Stopped(_) => exit::STOPPED,
1220                    Verdict::InternalError { .. } | Verdict::BudgetMeasurement { .. } => {
1221                        exit::INTERNAL
1222                    }
1223                    _ if tlc => v.tlc().map_or(exit::INTERNAL, |c| c.exit),
1224                    Verdict::Success => exit::SUCCESS,
1225                    Verdict::InvariantViolated { .. }
1226                    | Verdict::PropertyViolatedInitially { .. }
1227                    | Verdict::ActionPropertyViolated { .. }
1228                    | Verdict::PostconditionFalse { .. } => exit::VIOLATION,
1229                    Verdict::Deadlock => exit::DEADLOCK,
1230                    Verdict::AssumptionFalse { .. }
1231                    | Verdict::EvaluationError {
1232                        site: dive_runtime::ErrorSite::Assumption,
1233                        ..
1234                    } => exit::ASSUMPTION,
1235                    Verdict::ModelError { .. } => exit::REJECTED,
1236                    Verdict::EvaluationError { .. } | Verdict::NotCompletelySpecified { .. } => {
1237                        exit::EVALUATION
1238                    }
1239                    _ => exit::INTERNAL,
1240                }
1241            }
1242        }
1243    }
1244
1245    fn profile_name(&self) -> &'static str {
1246        match self.profile {
1247            Profile::Tlc
1248                if self.opts.eval.action_composition == dive_eval::ActionComposition::Tla
1249                    || self.checkpoint_request.as_ref().is_some_and(|r| {
1250                        r.counters == dive_runtime::checkpoint::Counters::Retain
1251                    })
1252                    // TLC has no time limit. A memory ceiling is TLC's
1253                    // `-Xmx` counterpart, a host resource.
1254                    || self.budget_sources.0 == "explicit"
1255                    || self.opts.max_states.is_some() || self.opts.max_depth.is_some()
1256                    || self.opts.symmetry_liveness != dive_model::SymmetryLiveness::Tlc =>
1257            {
1258                "tlc+overrides"
1259            }
1260            Profile::Tlc => "tlc",
1261            Profile::Dive => "dive",
1262        }
1263    }
1264
1265    fn profile_for_exit_convention(&self, convention: ExitConvention) -> &'static str {
1266        if self.profile == Profile::Tlc && convention == ExitConvention::Native {
1267            "tlc+overrides"
1268        } else {
1269            self.profile_name()
1270        }
1271    }
1272
1273    /// Reports an explicitly selected physical status and its convention.
1274    ///
1275    /// The underlying evaluator settings and deciding class are unchanged.
1276    /// Native statuses with TLC evaluation are labeled `tlc+overrides`.
1277    /// [`Self::to_json`] retains its historical API document.
1278    #[must_use]
1279    pub fn to_json_with_exit_convention(&self, convention: ExitConvention) -> Value {
1280        let mut document = self.to_json();
1281        document["exit_code"] = json!(self.exit_code_for(convention));
1282        document["options"]["exit_codes"] = json!(convention.as_str());
1283        document["options"]["semantic_profile"] = json!(if self.profile == Profile::Tlc {
1284            "tlc"
1285        } else {
1286            "dive"
1287        });
1288        document["options"]["profile"] = json!(self.profile_for_exit_convention(convention));
1289        document
1290    }
1291
1292    /// Human output with the resolved physical status and compatibility label.
1293    /// [`Self::render_human`] retains its historical API output.
1294    #[must_use]
1295    pub fn render_human_with_exit_convention(&self, convention: ExitConvention) -> String {
1296        use std::fmt::Write as _;
1297        let mut output = self.render_human_profile(self.profile_for_exit_convention(convention));
1298        let _ = writeln!(
1299            output,
1300            "Exit codes: {} (process status {})",
1301            convention.as_str(),
1302            self.exit_code_for(convention)
1303        );
1304        output
1305    }
1306
1307    /// The `options` block: profile, options and seed.
1308    fn symmetry_liveness(&self) -> Option<&dive_model::SymmetryLivenessResolution> {
1309        match &self.phase {
1310            Phase::Checked(result) => result.symmetry_liveness.as_ref(),
1311            Phase::Temporal(report) => report.symmetry_liveness(),
1312            Phase::TemporalError(failure) => failure.symmetry_liveness(),
1313            _ => None,
1314        }
1315    }
1316
1317    fn analysis_configuration(&self) -> crate::temporal::Configuration {
1318        match &self.phase {
1319            Phase::Temporal(report) => report.configuration(),
1320            Phase::TemporalError(failure) => failure.configuration(),
1321            _ => None,
1322        }
1323        .unwrap_or(self.temporal_configuration)
1324    }
1325
1326    #[allow(
1327        clippy::too_many_lines,
1328        reason = "one resolved options document retains option sources and storage policies"
1329    )]
1330    fn options_json(&self) -> Value {
1331        let o = &self.opts;
1332        let e = &o.eval;
1333        let int = match e.ctx.int_mode {
1334            dive_value::IntMode::Tlc => "tlc",
1335            dive_value::IntMode::Big => "big",
1336        };
1337        let order = match e.ctx.order {
1338            dive_value::ValueOrder::Tlc => "tlc",
1339            dive_value::ValueOrder::Canonical => "canonical",
1340        };
1341        let explore = match e.exploration {
1342            dive_eval::ExplorationOrder::Tlc => "tlc",
1343            dive_eval::ExplorationOrder::Value => "value",
1344        };
1345        let comparisons = match e.comparisons {
1346            dive_eval::Comparisons::Tlc => "tlc",
1347            dive_eval::Comparisons::Tla => "tla",
1348        };
1349        let fingerprint = (o.store == StoreMode::Fingerprint).then(|| {
1350            json!({
1351                "polynomial_index": o.fp_index,
1352                "polynomial_source": if self.fp_given { "flag" } else if self.checkpoint_request.as_ref().is_some_and(|r| r.action == dive_runtime::checkpoint::Action::Recover) { "checkpoint" } else if self.profile == Profile::Tlc { "random" } else { "default" },
1353                "scheme": if o.tlc_fingerprints { "tlc" } else { "dive" },
1354            })
1355        });
1356        let mut options = json!({
1357            "profile": self.profile_name(),
1358            "symmetry_liveness": o.symmetry_liveness.as_str(),
1359            "symmetry_liveness_source": if self.symmetry_liveness_explicit { "explicit" } else { "profile-default" },
1360            "int": int,
1361            "choose_order": order,
1362            "explore_order": explore,
1363            "comparisons": comparisons,
1364            "warnings": e.warnings,
1365            "allow_io": e.host_access.names(),
1366            "action_composition": match e.action_composition {
1367                dive_eval::ActionComposition::Off => "off",
1368                dive_eval::ActionComposition::Tlc => "tlc",
1369                dive_eval::ActionComposition::Tla => "tla",
1370            },
1371            "store": o.store.name(),
1372            "fingerprint": fingerprint,
1373            "seed": o.seed,
1374            "seed_source": if self.seed_given { "flag" } else if self.checkpoint_request.as_ref().is_some_and(|r| r.action == dive_runtime::checkpoint::Action::Recover) { "checkpoint" } else { "fresh" },
1375            "deadlock_flag": o.no_deadlock,
1376            "workers": self.workers_json(),
1377            "candidate_memory_bytes_per_worker": o.candidate_memory_bytes,
1378            "store_compact_trigger_bytes": o.store_compact_bytes,
1379            "candidate_record_bytes_limit": o.candidate_memory_bytes.map(|_| dive_store::spill::MAX_RECORD_BYTES),
1380            "frontier_memory_bytes_per_queue": o.frontier_memory_bytes,
1381            "frontier_record_bytes_limit": o.frontier_memory_bytes.map(|_| dive_store::spill::MAX_RECORD_BYTES),
1382            "frontier_codec_nodes_per_value_limit": o.frontier_memory_bytes.filter(|_| self.core.is_none()).map(|_| dive_value::codec::FRONTIER_MAX_NODES),
1383            "predecessor_memory_bytes": o.predecessor_memory_bytes,
1384            "predecessor_path_steps_limit": o.predecessor_memory_bytes.map(|_| dive_store::predecessor::MAX_PATH_STEPS),
1385            "budget": {
1386                "time_limit_ms": o.budget.time.map(|t| u64::try_from(t.as_millis()).unwrap_or(u64::MAX)),
1387                "time_limit_source": self.budget_sources.0,
1388                "max_memory_bytes": o.budget.memory,
1389                "max_memory_source": self.budget_sources.1,
1390                "max_memory_requested_source": self.memory_requested_source,
1391                "max_states": o.max_states,
1392                "max_depth": o.max_depth,
1393                "scope": "the check after loading: evaluator-backed fresh model binding after structural configuration/evaluator construction, safety search, graph capture, temporal analysis and fresh native temporal-candidate validation including its rebinding, and producer ASSUME using existing amortized loop checkpoints; structural binding, independent validation ASSUME, post-binding symmetry preparation, serialization, quiet value/bulk/native units, deferred providers retained by other evaluators and diagnostic reconstruction after a deciding event are not interrupted; legacy TLC/session and standalone validation are not controlled; memory of the whole process",
1394            },
1395        });
1396        if let Some(disk) = &o.seen_disk {
1397            options["seen_disk"] = json!({"entries_limit": disk.limits.entries, "key_bytes_limit": disk.limits.key_bytes, "probe_steps_limit": disk.limits.probe_steps, "summary_pairs_limit": disk.limits.summary_pairs, "directory": disk.directory, "execution": "inline-fallback", "resident_key_collection_bytes": 0, "total_memory_budget": false});
1398        }
1399        if self.temporal_schema() {
1400            options["lncheck"] = json!(self.temporal_result().map_or_else(
1401                || if let Phase::TemporalError(failure) = &self.phase {
1402                    if failure.periodic().is_some() {
1403                        "deterministic"
1404                    } else {
1405                        "final"
1406                    }
1407                } else {
1408                    "final"
1409                },
1410                crate::temporal::Report::lncheck
1411            ));
1412            options["lasso"] = json!("short");
1413            options["temporal_bounds"] = temporal_limits_json(self.analysis_configuration());
1414            options["tlc_exact_temporal"] = json!(false);
1415        }
1416        if let Some(request) = &self.checkpoint_request {
1417            options["checkpoint"] = json!({
1418                "path": request.path,
1419                "action": match request.action { dive_runtime::checkpoint::Action::Recover => "recover", dive_runtime::checkpoint::Action::PauseAfterLevels(_) => "pause" },
1420                "pause_after_levels": match request.action { dive_runtime::checkpoint::Action::PauseAfterLevels(n) => Some(n), dive_runtime::checkpoint::Action::Recover => None },
1421                "counters": request.counters,
1422                "max_payload_bytes": dive_runtime::checkpoint::MAX_PAYLOAD_BYTES,
1423                "max_states": dive_runtime::checkpoint::MAX_STATES,
1424                // Core has no separate state-image limit, also when the run
1425                // stops before Core starts (a parse error, say).
1426                "max_state_bytes": Value::Null,
1427                "backend": "core",
1428                "archive_bounds_scope": "archive admission only; ordinary search, Store, codec workspaces and process memory are separate",
1429                "max_level": dive_runtime::checkpoint::MAX_LEVEL,
1430                "max_counter": dive_runtime::checkpoint::MAX_COUNTER,
1431                "trusted_local_archive": true,
1432                "independent_certificate": false,
1433                "parallel_recovery": true,
1434            });
1435        }
1436        options
1437    }
1438
1439    /// The workers requested and used: `{ requested, used, sequential,
1440    /// reason, chaos }`. These, with the timings, are the only fields of the
1441    /// document that may differ between worker counts.
1442    fn workers_json(&self) -> Value {
1443        if let Phase::TemporalError(failure) = &self.phase {
1444            return match failure.workers(self.workers_requested) {
1445                Some(w) => json!({
1446                    "requested": w.requested, "used": w.used,
1447                    "sequential": w.sequential, "reason": w.reason,
1448                    "chaos": self.opts.chaos,
1449                }),
1450                None => json!({
1451                    "requested": self.workers_requested, "used": null,
1452                    "sequential": null, "reason": "execution evidence unavailable",
1453                    "chaos": self.opts.chaos,
1454                }),
1455            };
1456        }
1457        let w = self
1458            .result()
1459            .map(|r| r.workers.clone())
1460            .or_else(|| {
1461                self.temporal_result()
1462                    .and_then(temporal_evidence)
1463                    .map(|c| c.workers)
1464            })
1465            .unwrap_or_else(|| dive_runtime::Workers {
1466                requested: self.workers_requested,
1467                used: 0,
1468                sequential: false,
1469                reason: Some("no search ran".to_owned()),
1470            });
1471        json!({
1472            "requested": w.requested,
1473            "used": w.used,
1474            "sequential": w.sequential,
1475            "reason": w.reason,
1476            "chaos": self.opts.chaos,
1477        })
1478    }
1479
1480    /// The workers used, for the human header.
1481    fn workers_used(&self) -> String {
1482        match &self.phase {
1483            Phase::Checked(r) => r.workers.used.to_string(),
1484            Phase::Temporal(r) => temporal_evidence(r)
1485                .map_or(0, |c| c.workers.used)
1486                .to_string(),
1487            Phase::TemporalError(failure) => failure
1488                .workers(self.workers_requested)
1489                .map_or_else(|| "unknown".into(), |w| w.used.to_string()),
1490            _ => "0".into(),
1491        }
1492    }
1493
1494    /// The JSON document (schema [`CHECK_SCHEMA_VERSION`]). `check_kind` names
1495    /// the safety or temporal request/report family; it does not assert that
1496    /// checking ran or that capture completed. Final/short safety failures
1497    /// retain the temporal family and their actual execution evidence:
1498    ///
1499    /// ```text
1500    /// { "schema_version": 3, "command": "check", "file", "config",
1501    ///   "verdict": "success" | "invariant-violation" | "property-violation"
1502    ///            | "action-property-violation" | "deadlock" | "assumption-failure"
1503    ///            | "postcondition-failure" | "assertion-failure" | "overflow"
1504    ///            | "evaluation-error" | "incomplete-state" | "model-error"
1505    ///            | "rejected" | "unsupported" | "resource-limit" | "stopped"
1506    ///            | "internal-error",
1507    ///   "property": string | null, "message": string | null,
1508    ///   "error_site": string | null,
1509    ///   "tlc": { "code", "name", "exit_status", "reported", "verified" } | null,
1510    ///   "statistics": { "generated", "distinct", "left_on_queue", "depth",
1511    ///                   "initial_generated", "reported_by_tlc" } | null,
1512    ///   "counterexample": { "length", "ending": "finite",
1513    ///                       "states": [ { "index", "label", "action",
1514    ///                                     "values": { var: TLC JSON }, "text" } ],
1515    ///                       "trace": dive-trace document | null } | null,
1516    ///   "diagnostic_witness": { "trace": native-v2 named cause document }, // optional
1517    ///   "collision": { "store", "scheme", "optimistic", "actual", "assumption" } | null,
1518    ///   "output": [ string ], "warnings": [ { "code", "message" } ],
1519    ///   "diagnostics": [ ... ], "notes": [ string ],
1520    ///   "stopped": { "resource": "time" | "memory" | "states" | "depth", "limit", "observed", "elapsed_ms",
1521    ///                "unit": "ms" | "bytes" | "states" | "levels", "phase", "hint" }   (only when stopped),
1522    ///   "options": { "profile", "int", "choose_order", "explore_order",
1523    ///                "comparisons", "warnings", "store", "fingerprint",
1524    ///                "seed", "seed_source", "deadlock_flag",
1525    ///                "budget": { "time_limit_ms", "time_limit_source",
1526    ///                            "max_memory_bytes", "max_memory_source", "max_states", "max_depth", "scope" },
1527    ///                "workers": { "requested", "used", "sequential", "reason",
1528    ///                             "chaos" } },
1529    ///   "elapsed_ms" }
1530    /// ```
1531    ///
1532    /// `tlc` is how TLC classifies the result: `code` decides TLC's exit
1533    /// status, and `reported` is the code of the error message TLC prints
1534    /// first (an invariant that fails to evaluate is reported as
1535    /// `TLC_INVARIANT_EVALUATION_FAILED`, for example); `verified: false`
1536    /// means dive does not yet reproduce TLC's error class at that site and
1537    /// does not claim it. `reported_by_tlc` is false where TLC prints no statistics
1538    /// (a stop while generating initial states). Explicit final-only schema 3
1539    /// also declares the schedule/selection, fixed entry/work bounds and actual
1540    /// failure stage. Periodic traces include all configured property names and
1541    /// a stuttering ending or one-based lasso target; independent replay precedes
1542    /// any private-certified temporal violation.
1543    #[must_use]
1544    #[allow(clippy::too_many_lines, reason = "one document")]
1545    pub fn to_json(&self) -> Value {
1546        let mut doc = json!({
1547            "schema_version": CHECK_SCHEMA_VERSION,
1548            "check_kind": if self.temporal_schema() { "temporal" } else { "safety" },
1549            "command": "check",
1550            "file": self.file,
1551            "config": self.config,
1552            "verdict": self.verdict(),
1553            "property": Value::Null,
1554            "message": Value::Null,
1555            "error_site": Value::Null,
1556            "tlc": Value::Null,
1557            "statistics": Value::Null,
1558            "counterexample": Value::Null,
1559            "collision": Value::Null,
1560            "frontier_storage": Value::Null,
1561            "output": [],
1562            "warnings": [],
1563            "diagnostics": [],
1564            "notes": [],
1565            "options": self.options_json(),
1566            "symmetry_liveness": self.symmetry_liveness().map(symmetry_liveness_json),
1567            "elapsed_ms": 0,
1568        });
1569        if let Some(inputs) = &self.opts.inputs {
1570            doc["external_inputs"] = crate::host_inputs::inputs_json(&inputs.recorded());
1571        }
1572        let samples = self.memory_samples.unwrap_or_default();
1573        doc["resources"] = json!({"memory": {
1574            "metric": if cfg!(target_os = "linux") { "rss+swap" } else if cfg!(target_os = "macos") { "rss" } else { "unavailable" },
1575            "status": if self.opts.budget.memory.is_none() { if self.budget_sources.1 == "unavailable" { "unavailable" } else { "disabled" } } else if samples.unavailable.is_some() { "unavailable" } else if self.memory_samples.is_some() { "sampled" } else { "not-started" },
1576            "samples": samples.count, "observed_max_bytes": samples.maximum,
1577            "initial_sampled": samples.initial, "final_sampled": samples.final_sample,
1578            "unavailable_at": samples.unavailable.map(dive_runtime::budget::SamplePoint::name),
1579            "scope": "sampled process memory, not an allocation-time hard cap or a measurement of the true peak; excursions between observations are possible"
1580        }});
1581        match &self.phase {
1582            Phase::BudgetStopped(stopped) => {
1583                doc["message"] = json!(stopped.to_string());
1584                doc["stopped"] = stopped_json(stopped);
1585                doc["elapsed_ms"] = json!(stopped.elapsed_ms);
1586                doc["resources"]["checking_started"] = json!(false);
1587                if self.temporal_schema() {
1588                    doc["execution"] = json!({"stage": "check-startup", "capture_completed": false, "started": false});
1589                }
1590            }
1591            Phase::SpecRejected(a) => {
1592                doc["diagnostics"] = a.to_json()["diagnostics"].clone();
1593                // TLC reports every spec SANY rejects, in its parse or its
1594                // semantic phase, as `TLC_PARSING_FAILED` (3002), exit 150.
1595                // Verified against captured runs of the pinned TLC: harness
1596                // fixtures `ParseError` and `SemanticError`, and the goldens
1597                // of the probes `M1Syntax` (a syntax error) and `M2Undefined`
1598                // (an undefined name) in `conformance/corpus/probes/`. Like
1599                // every other verdict's class, it is reported in both
1600                // profiles.
1601                doc["tlc"] = json!({"code": 3002, "name": "TLC_PARSING_FAILED", "exit_status": 150, "verified": true});
1602            }
1603            Phase::ConfigRejected(c) => {
1604                doc["diagnostics"] = c.to_json()["diagnostics"].clone();
1605            }
1606            Phase::Unlowered(why) => doc["message"] = Value::from(why.as_str()),
1607            Phase::Temporal(r) => {
1608                temporal_json(&mut doc, r, self.opts.tlc_fingerprints);
1609                let violation = matches!(
1610                    r.outcome(),
1611                    crate::temporal::Outcome::NativeViolation(_)
1612                        | crate::temporal::Outcome::NativePrefixViolation(_)
1613                );
1614                doc["execution"]["exhausted"] =
1615                    json!(r.periodic().is_none_or(|checks| checks.exhausted));
1616                doc["tlc"] = if violation {
1617                    json!({"code":2116,"name":"TLC_TEMPORAL_PROPERTY_VIOLATED","exit_status":13,"verified":true})
1618                } else {
1619                    json!({"code":2193,"name":"TLC_SUCCESS","exit_status":0,"verified":true})
1620                };
1621            }
1622            Phase::TemporalError(e) => {
1623                if let Some(progress) = e.validation_progress() {
1624                    doc["resources"]["validation"] = json!({
1625                        "checks_passed": progress.checks_passed,
1626                        "state": progress.state,
1627                        "check": progress.check.map(dive_trace::Check::name),
1628                    });
1629                }
1630                doc["message"] = json!(e.to_string());
1631                doc["diagnostics"] = json!([crate::diagnostics::temporal_failure(e)]);
1632                doc["execution"] =
1633                    json!({"stage": e.stage().name(), "capture_completed": e.capture_completed()});
1634                if e.stage() == crate::temporal::Stage::Binding
1635                    && e.exploration().is_none()
1636                    && !matches!(e.error(), crate::temporal::Error::Binding(_))
1637                {
1638                    doc["resources"]["checking_started"] = json!(false);
1639                }
1640                if let Some(checks) = e.periodic() {
1641                    doc["periodic"] = periodic_json(checks);
1642                }
1643                doc["elapsed_ms"] =
1644                    json!(u64::try_from(e.elapsed().as_millis()).unwrap_or(u64::MAX));
1645                if let crate::temporal::Error::Binding(failure) = e.error()
1646                    && let Some(class) = Verdict::from(&failure.error).tlc()
1647                {
1648                    doc["tlc"] = json!({
1649                        "code": class.code,
1650                        "name": class.name,
1651                        "exit_status": class.exit,
1652                        "reported": class.reported,
1653                        "verified": class.verified,
1654                    });
1655                } else if temporal_startup_tautology(e) {
1656                    let class = dive_model::Ec::TlcLiveFormulaTautology;
1657                    doc["tlc"] = json!({
1658                        "code": class.code(), "name": class.name(),
1659                        "reported": class.code(), "verified": true,
1660                        "exit_status": dive_runtime::tlc_exit_status(class.code()),
1661                    });
1662                } else if let Some(error) = temporal_evaluation(e) {
1663                    let code = error.ec().code();
1664                    doc["tlc"] = json!({
1665                        "code": code,
1666                        "name": error.ec().name(),
1667                        "exit_status": dive_runtime::tlc_exit_status(code),
1668                        "verified": if e.capture_row_error().is_some() { true } else if temporal_action_evaluation(e).is_some() {
1669                            error.ec() == dive_eval::Ec::General && !error.is_eval_exception()
1670                        } else { error.ec() == dive_eval::Ec::ExpectedValue },
1671                    });
1672                }
1673                if temporal_action_evaluation(e).is_some() {
1674                    doc["error_site"] = json!("temporal-action");
1675                }
1676                if let crate::temporal::Error::Analysis(
1677                    dive_liveness::analyze::AnalysisError::Stopped(stopped),
1678                ) = e.error()
1679                {
1680                    doc["stopped"] = stopped_json(stopped);
1681                }
1682                if let Some(capture) = e.exploration() {
1683                    temporal_evidence_json(&mut doc, capture, self.opts.tlc_fingerprints);
1684                    doc["notes"] = json!([
1685                        "Temporal checking failed; capture_completed records whether these actual exploration statistics describe completion. No temporal verdict was produced."
1686                    ]);
1687                } else {
1688                    doc["warnings"] = json!(
1689                        e.binding_output()
1690                            .iter()
1691                            .filter_map(|m| {
1692                                if let dive_model::Message::Warning { code, message } = m {
1693                                    Some(json!({"code": code.code(), "message": message}))
1694                                } else {
1695                                    None
1696                                }
1697                            })
1698                            .collect::<Vec<_>>()
1699                    );
1700                    doc["output"] = json!(
1701                        e.binding_output()
1702                            .iter()
1703                            .filter_map(|m| match m {
1704                                dive_model::Message::Print(text) => Some(text.clone()),
1705                                dive_model::Message::Warning { .. } => None,
1706                            })
1707                            .collect::<Vec<_>>()
1708                    );
1709                }
1710                if let Some((error, document, _)) = e.capture_row_error() {
1711                    doc["message"] = json!(error.to_string());
1712                    doc["error_site"] =
1713                        json!(if e.state_evaluation().is_some_and(|state| state.site()
1714                            == dive_liveness::analyze::StateEvaluationSite::CaptureSourceRow)
1715                        {
1716                            "temporal-source-row"
1717                        } else {
1718                            "temporal-state-row"
1719                        });
1720                    doc["tlc"]["reported"] = json!(error.ec().code());
1721                    doc["statistics"]["reported_by_tlc"] = json!(true);
1722                    doc["counterexample"] = json!({
1723                        "length": document.states.len(), "ending": "finite",
1724                        "states": document.states.iter().enumerate().map(|(i, values)| json!({"index":i+1,"label": if i==0 {Some("<Initial predicate>")} else {None},"action":null,"values":values,"text":null})).collect::<Vec<_>>(),
1725                        "trace": document.to_json(), "validation": "valid",
1726                    });
1727                    doc["notes"] = json!([
1728                        "The finite behavior and first ordered temporal demand error were independently reconstructed and validated on a fresh source-bound runtime. No BFS counters, lasso or violated-property claim is certified by endpoint validation."
1729                    ]);
1730                }
1731            }
1732            Phase::Checked(r) => {
1733                if let Some(storage) = &r.seen {
1734                    let facts = |s: dive_store::seen::Stats| json!({ "physical_entries": s.physical_entries, "expected_disk_bytes": s.disk_bytes, "resident_key_collection_bytes": s.resident_key_bytes, "poisoned": s.poisoned, "cleanup_completed": s.cleanup_completed });
1735                    doc["seen_storage"] = json!({
1736                        "mode": "fallible-disk", "admitted_keys": storage.admitted_keys,
1737                        "scope": "seen-key/offset collections only; supplied keys, state values, frontiers, predecessors, candidates, traces, graphs, OS page cache and native archives are outside these bounds",
1738                        "before_cleanup": storage.before_cleanup.map(facts), "after_cleanup": storage.after_cleanup.map(facts),
1739                        "first_failure": storage.first_failure.as_ref().map(|failure| json!({"phase": format!("{:?}", failure.phase), "operation": format!("{:?}", failure.error.operation), "code": failure.error.code(), "message": failure.error.message, "cleanup_failure": failure.error.cleanup_failure, "generated": failure.generated, "predecessor": failure.predecessor, "successor_ordinal": failure.successor_ordinal})),
1740                        "deciding_event_before_failure": storage.deciding_event_before_failure.as_ref().map(|v| format!("{v:?}")),
1741                        "replay": storage.replay.as_ref().map(|r| json!({"original_error": format!("{:?}", r.original_error), "predecessor": r.predecessor, "stopped_successor_ordinal": r.stopped_successor_ordinal, "generated": r.generated, "admitted_keys": r.admitted_keys, "queued": r.queued, "unproved_print_output": r.unproved_print_output, "halted_by": r.halted_by.as_ref().map(|v| format!("{v:?}"))})),
1742                        "crash_durable": false, "checkpoint_import_supported": false,
1743                        "checkpoint_key_reconstitution": self.core.is_some() && self.checkpoint_request.is_some(),
1744                    });
1745                }
1746                doc["frontier_storage"] = json!({
1747                    "mode": if r.frontier.memory_bytes_per_queue.is_some() { "encoded-spill" } else { "memory-reference" },
1748                    "scope": if self.core.is_some() && r.frontier.memory_bytes_per_queue.is_some() {
1749                        "encoded current and next frontier capacities observed at queue operations only; retained live Store and construction history, decoded chunks, seen sets, candidates, arenas, traces, allocator workspace and native archives are not measured or bounded"
1750                    } else { "encoded current and next frontier queues only; legacy value-frontier heap, candidates, seen sets, traces, graphs and native archive work are not measured or bounded" },
1751                    "memory_bytes_per_queue": r.frontier.memory_bytes_per_queue,
1752                    "max_record_bytes": r.frontier.max_record_bytes,
1753                    "max_codec_nodes_per_value": r.frontier.memory_bytes_per_queue.filter(|_| self.core.is_none()).map(|_| dive_value::codec::FRONTIER_MAX_NODES),
1754                    "peak_retained_bytes": r.frontier.peak_retained_bytes,
1755                    "retained_bytes": r.frontier.retained_bytes,
1756                    "committed_spill_bytes": r.frontier.spilled_bytes,
1757                    "write_accounting_complete": r.frontier.failures.is_empty(),
1758                    "failures": r.frontier.failures,
1759                    "search_event_before_storage_failure": r.frontier.deciding_event_before_failure,
1760                });
1761                if self.opts.predecessor_memory_bytes.is_some() {
1762                    let p = &r.predecessor;
1763                    doc["predecessor_storage"] = json!({
1764                        "scope": "predecessor-record-capacity-only",
1765                        "retained_bytes_before_cleanup": p.storage.retained_bytes,
1766                        "peak_retained_bytes": p.storage.peak_retained_bytes,
1767                        "confirmed_write_bytes": p.storage.written_bytes,
1768                        "committed_records": p.storage.records,
1769                        "spilled": p.storage.spilled,
1770                        "write_accounting_complete": p.failures.is_empty(),
1771                        "cleanup_completed": p.cleanup_completed,
1772                        "failures": p.failures,
1773                        "deciding_event_before_failure": p.deciding_event_before_failure,
1774                        "excludes": ["seen-set", "frontiers", "candidate-vectors", "graphs", "reconstructed-paths", "decoded-states", "allocator-workspace", "native-archive-work"]
1775                    });
1776                }
1777                let ctx = self.opts.eval.ctx;
1778                let v = &r.verdict;
1779                doc["property"] = v.property().map_or(Value::Null, Value::from);
1780                doc["message"] = match v {
1781                    Verdict::AssumptionFalse { message, .. }
1782                    | Verdict::EvaluationError { message, .. }
1783                    | Verdict::ModelError { message, .. }
1784                    | Verdict::PostconditionFalse { message, .. }
1785                    | Verdict::NotCompletelySpecified { message, .. }
1786                    | Verdict::ResourceLimit { message }
1787                    | Verdict::InternalError { message } => Value::from(message.as_str()),
1788                    Verdict::Unsupported { feature } => Value::from(feature.as_str()),
1789                    Verdict::Stopped(stopped) => Value::from(stopped.to_string()),
1790                    Verdict::BudgetMeasurement { error } => Value::from(error.to_string()),
1791                    _ => Value::Null,
1792                };
1793                if let Verdict::BudgetMeasurement { error } = v {
1794                    doc["diagnostics"] = json!([{"code": dive_runtime::budget::MEASUREMENT_FAILURE_CODE, "message": error.to_string(), "cause": error.to_string(), "span": null, "help": crate::diagnostics::explain(dive_runtime::budget::MEASUREMENT_FAILURE_CODE).map(|entry| entry.remediation)}]);
1795                }
1796                if let Verdict::Stopped(stopped) = v {
1797                    doc["stopped"] = stopped_json(stopped);
1798                }
1799                if let Verdict::EvaluationError { site, .. } = v {
1800                    doc["error_site"] = Value::from(site.name());
1801                }
1802                if let Some(c) = v.tlc() {
1803                    doc["tlc"] = json!({
1804                        "code": c.code,
1805                        "name": c.name,
1806                        "exit_status": c.exit,
1807                        "reported": c.reported,
1808                        "verified": c.verified,
1809                    });
1810                }
1811                if let Some(s) = &r.stats {
1812                    doc["statistics"] = json!({
1813                        "generated": s.generated,
1814                        "distinct": s.distinct,
1815                        "left_on_queue": s.left_on_queue,
1816                        "depth": s.depth,
1817                        "initial_generated": s.initial_generated,
1818                        // A stop's statistics are progress, not TLC's report.
1819                        "reported_by_tlc": r.tlc_prints_stats
1820                            && !matches!(r.verdict, Verdict::Stopped(_) | Verdict::BudgetMeasurement { .. }),
1821                    });
1822                }
1823                if let Some(cx) = &r.counterexample {
1824                    let states: Vec<Value> = cx
1825                        .states
1826                        .iter()
1827                        .enumerate()
1828                        .map(|(i, s)| {
1829                            let values: serde_json::Map<String, Value> = r
1830                                .tlc_var_order
1831                                .iter()
1832                                .filter_map(|&k| {
1833                                    let name = r.var_names.get(k)?.clone();
1834                                    let v = s.values.get(k)?;
1835                                    let j = dive_value::json::to_tlc_json(v, ctx)
1836                                        .ok()
1837                                        .and_then(|t| serde_json::from_str(&t).ok())
1838                                        .unwrap_or(Value::Null);
1839                                    Some((name, j))
1840                                })
1841                                .collect();
1842                            json!({
1843                                "index": i + 1,
1844                                "label": s.label,
1845                                "action": s.action,
1846                                "values": values,
1847                                "text": dive_runtime::format_trace_state(r, s, ctx),
1848                            })
1849                        })
1850                        .collect();
1851                    let transported = trace_doc(
1852                        r,
1853                        &cx.states,
1854                        ctx,
1855                        self.next_error_endpoint.as_ref(),
1856                        self.partial_terminal_endpoint.as_ref(),
1857                        self.candidate_error_endpoint.as_ref(),
1858                        self.view_error_endpoint.as_ref(),
1859                    );
1860                    doc["counterexample"] = json!({
1861                        "length": states.len(),
1862                        "ending": "finite",
1863                        "states": states,
1864                        "trace": transported.unwrap_or(Value::Null),
1865                    });
1866                }
1867                if let Some(witness) = &r.diagnostic_witness {
1868                    let transported = trace_doc(r, witness.states(), ctx, None, None, None, None);
1869                    doc["diagnostic_witness"] =
1870                        json!({"trace": transported.unwrap_or(Value::Null)});
1871                }
1872                if matches!(
1873                    r.verdict,
1874                    Verdict::NotCompletelySpecified { initial: true, .. }
1875                ) && let Some(endpoint) = &self.partial_terminal_endpoint
1876                {
1877                    let witness = dive_trace::TraceDoc {
1878                        variables: r.var_names.clone(),
1879                        states: Vec::new(),
1880                        labels: Vec::new(),
1881                        ending: Some(dive_trace::Ending::PartialInit {
1882                            endpoint: endpoint.clone(),
1883                        }),
1884                        length: Some(1),
1885                        source: dive_trace::Source::Dive,
1886                        properties: Vec::new(),
1887                    };
1888                    doc["error_witness"] = witness.to_json();
1889                }
1890                if let Some(c) = &r.collision {
1891                    doc["collision"] = json!({
1892                        "store": "fingerprint",
1893                        "scheme": if r.tlc_fingerprints { "tlc" } else { "dive" },
1894                        "optimistic": c.optimistic,
1895                        "actual": c.actual,
1896                        "assumption": "fingerprints behave as random 64-bit values (TLC's assumption too)",
1897                    });
1898                }
1899                doc["output"] = json!(r.output);
1900                doc["warnings"] = r
1901                    .warnings
1902                    .iter()
1903                    .map(|(c, m)| json!({"code": c, "message": m}))
1904                    .collect();
1905                doc["notes"] = json!(r.notes);
1906                doc["elapsed_ms"] = json!(u64::try_from(r.elapsed.as_millis()).unwrap_or(u64::MAX));
1907            }
1908        }
1909        if self.checkpoint_request.is_some() {
1910            doc["checkpoint"] = json!(self.checkpoint_receipt);
1911        }
1912        let measurement_failure = match &self.phase {
1913            Phase::Checked(result) => matches!(result.verdict, Verdict::BudgetMeasurement { .. }),
1914            Phase::TemporalError(failure) => {
1915                matches!(
1916                    failure.error(),
1917                    crate::temporal::Error::Analysis(
1918                        dive_liveness::analyze::AnalysisError::BudgetMeasurement(_)
1919                    )
1920                ) || matches!(failure.error(), crate::temporal::Error::Analysis(dive_liveness::analyze::AnalysisError::Exploration(result)) if matches!(result.verdict, Verdict::BudgetMeasurement { .. }))
1921            }
1922            _ => false,
1923        };
1924        if (self.verdict() == "stopped" || measurement_failure) && doc["statistics"].is_object() {
1925            doc["statistics"]["exhaustive"] = json!(false);
1926        }
1927        if let Some(core) = &self.core {
1928            doc["engine"] = json!("core");
1929            doc["core"] = json!({"disabled": core.opts, "metrics": core.metrics});
1930            if !core.sample.is_null() {
1931                doc["core"]["sample"] = core.sample.clone();
1932            }
1933        }
1934        doc
1935    }
1936
1937    /// The TLC-style text report (see `dive_runtime::render_human`), preceded
1938    /// by the run's options and the `Print` output.
1939    #[must_use]
1940    pub fn render_human(&self) -> String {
1941        self.render_human_profile(self.profile_name())
1942    }
1943
1944    #[allow(clippy::too_many_lines, reason = "one complete human check report")]
1945    fn render_human_profile(&self, profile: &str) -> String {
1946        use std::fmt::Write as _;
1947        let mut out = String::new();
1948        let o = &self.opts;
1949        let fp = if o.store == StoreMode::Fingerprint {
1950            format!(" (fp {})", o.fp_index)
1951        } else {
1952            String::new()
1953        };
1954        let _ = writeln!(
1955            out,
1956            "dive check {}: profile {}, store {}{fp}, seed {}, {} worker(s) requested, {} used",
1957            self.file,
1958            profile,
1959            o.store.name(),
1960            o.seed,
1961            self.workers_requested,
1962            self.workers_used()
1963        );
1964        if !o.eval.host_access.is_empty() {
1965            let _ = writeln!(
1966                out,
1967                "External inputs: explicit {} grants; recorded source-binding values are assumptions.",
1968                o.eval.host_access.names().join(",")
1969            );
1970        }
1971        if let Some(symmetry) = self.symmetry_liveness()
1972            && symmetry.unreduced()
1973        {
1974            let _ = writeln!(
1975                out,
1976                "Declared SYMMETRY {}; whole-run policy unreduced (no symmetry reduction); actual progress follows.",
1977                symmetry.declared().unwrap_or_default()
1978            );
1979        }
1980        if let Phase::Checked(r) = &self.phase
1981            && let Some(why) = &r.workers.reason
1982        {
1983            let _ = writeln!(out, "{why}");
1984        }
1985        if let Some(request) = &self.checkpoint_request {
1986            let _ = writeln!(
1987                out,
1988                "native checkpoint {:?}, counters {:?}; trusted local archive, not an independent certificate",
1989                request.action, request.counters
1990            );
1991            if let Some(receipt) = &self.checkpoint_receipt {
1992                let _ = writeln!(
1993                    out,
1994                    "{}: {} discoveries, {} queued, next level{}",
1995                    receipt.status, receipt.discovered, receipt.queued, receipt.next_level
1996                );
1997            }
1998        }
1999        match &self.phase {
2000            Phase::BudgetStopped(stopped) => {
2001                let _ = writeln!(out, "{stopped}; no verdict produced");
2002            }
2003            Phase::SpecRejected(a) => out.push_str(&a.render_human()),
2004            Phase::ConfigRejected(c) => out.push_str(&c.render_human()),
2005            Phase::Unlowered(why) => {
2006                let _ = writeln!(out, "unsupported: {why}; no verdict produced");
2007            }
2008            Phase::Temporal(r) => out.push_str(&temporal_human(r)),
2009            Phase::TemporalError(e) => {
2010                let _ = writeln!(
2011                    out,
2012                    "{}: {e}; no verdict produced",
2013                    temporal_failure_kind(e)
2014                );
2015                let _ = writeln!(out, "Execution stage: {}", e.stage().name());
2016                if let Some(explanation) = crate::diagnostics::explain(e.error().code()) {
2017                    let _ = writeln!(out, "Help: {}", explanation.remediation);
2018                }
2019                if let Some(capture) = e.exploration() {
2020                    for (_, warning) in &capture.warnings {
2021                        let _ = writeln!(out, "Warning: {warning}");
2022                    }
2023                    for line in &capture.output {
2024                        let _ = writeln!(out, "{line}");
2025                    }
2026                    let stats = &capture.stats;
2027                    let completion = match e.capture_completed() {
2028                        Some(true) => "completed",
2029                        Some(false) => "incomplete",
2030                        None => "completion unknown",
2031                    };
2032                    let _ = writeln!(
2033                        out,
2034                        "Capture {completion}: {} generated, {} distinct, depth {}; no temporal verdict.",
2035                        stats.generated, stats.distinct, stats.depth
2036                    );
2037                } else if !matches!(e.error(), crate::temporal::Error::Binding(_)) {
2038                    for message in e.binding_output() {
2039                        match message {
2040                            dive_model::Message::Print(text) => {
2041                                let _ = writeln!(out, "{text}");
2042                            }
2043                            dive_model::Message::Warning { message, .. } => {
2044                                let _ = writeln!(out, "Warning: {message}");
2045                            }
2046                        }
2047                    }
2048                }
2049                if let Some((_, document, _)) = e.capture_row_error() {
2050                    let _ = writeln!(out, "The behavior up to this point is:");
2051                    for (index, state) in document.states.iter().enumerate() {
2052                        let _ = writeln!(out, "State {}: {}", index + 1, json!(state));
2053                    }
2054                }
2055            }
2056            Phase::Checked(r) => {
2057                for (_, w) in &r.warnings {
2058                    let _ = writeln!(out, "Warning: {w}");
2059                }
2060                for line in &r.output {
2061                    let _ = writeln!(out, "{line}");
2062                }
2063                out.push_str(&dive_runtime::render_human(r, o.eval.ctx));
2064            }
2065        }
2066        out
2067    }
2068}
2069
2070/// The counterexample in `dive-trace`'s format, the
2071/// document the independent validator reads: `dive
2072/// validate-trace` and the conformance harness take it from
2073/// `counterexample.trace`. `null` when a value has no JSON form or the
2074/// verdict has no ending the format names.
2075fn trace_doc(
2076    r: &dive_runtime::CheckResult,
2077    recorded: &[dive_runtime::TraceState],
2078    ctx: dive_value::Ctx,
2079    next_endpoint: Option<&dive_trace::NextStateEndpoint>,
2080    partial_endpoint: Option<&dive_trace::PartialNextEndpoint>,
2081    candidate_endpoint: Option<&dive_trace::CandidateStateEndpoint>,
2082    view_endpoint: Option<&dive_trace::ViewSourceEndpoint>,
2083) -> Result<Value, String> {
2084    use dive_runtime::Verdict as V;
2085    use dive_trace::Ending;
2086    let ending = match &r.verdict {
2087        V::InvariantViolated { property, .. } => Ending::Invariant(property.clone()),
2088        V::PropertyViolatedInitially { property } | V::ActionPropertyViolated { property } => {
2089            Ending::Property(property.clone())
2090        }
2091        V::Deadlock => Ending::Deadlock,
2092        V::NotCompletelySpecified { initial: false, .. } if partial_endpoint.is_some() => {
2093            Ending::PartialNext {
2094                endpoint: partial_endpoint
2095                    .cloned()
2096                    .ok_or("missing partial Next source")?,
2097            }
2098        }
2099        // A named word preserves its original cause. The independent reader
2100        // must separately prove the initial2147/2102 diagnostic relationship;
2101        // the successor2111 relationship retains its existing checks.
2102        V::EvaluationError {
2103            site: dive_runtime::ErrorSite::Invariant,
2104            code,
2105            reported,
2106            verified: true,
2107            invariant: Some(name),
2108            cause,
2109            ..
2110        } if (*reported == 2102 && *code == 2147)
2111            || (*reported == 2111
2112                && (matches!(*code, 2111 | 2103) || *code == cause.ec().code())) =>
2113        {
2114            Ending::InvariantError {
2115                name: name.clone(),
2116                ec: cause.ec().name().to_owned(),
2117            }
2118        }
2119        V::EvaluationError {
2120            site: dive_runtime::ErrorSite::Next,
2121            cause,
2122            ..
2123        } if next_endpoint.is_some() => Ending::NextStateError {
2124            ec: cause.ec().name().to_owned(),
2125            endpoint: next_endpoint.cloned().ok_or("missing Next error source")?,
2126        },
2127        V::EvaluationError { cause, .. } if view_endpoint.is_some() => Ending::ViewSourceError {
2128            ec: cause.ec().name().to_owned(),
2129            endpoint: view_endpoint.cloned().ok_or("missing VIEW source")?,
2130        },
2131        V::EvaluationError { cause, .. } if candidate_endpoint.is_some() => {
2132            Ending::CandidateStateError {
2133                ec: cause.ec().name().to_owned(),
2134                endpoint: candidate_endpoint
2135                    .cloned()
2136                    .ok_or("missing candidate source")?,
2137            }
2138        }
2139        V::EvaluationError { cause, .. } => {
2140            if cause.ec() == dive_eval::Ec::AssertFailed {
2141                Ending::Assertion
2142            } else {
2143                Ending::Error {
2144                    ec: Some(cause.ec().name().to_owned()),
2145                }
2146            }
2147        }
2148        _ => return Err("verdict has no supported trace ending".into()),
2149    };
2150    let mut states = Vec::with_capacity(recorded.len());
2151    let mut labels = Vec::with_capacity(recorded.len());
2152    for (i, s) in recorded.iter().enumerate() {
2153        if s.partial.is_some() {
2154            if i + 1 != recorded.len() || !matches!(ending, Ending::PartialNext { .. }) {
2155                return Err("partial bindings must be a separate final terminal descriptor".into());
2156            }
2157            continue;
2158        }
2159        let mut m = serde_json::Map::new();
2160        for (k, name) in r.var_names.iter().enumerate() {
2161            let Some(v) = s.values.get(k) else {
2162                return Err("counterexample has an unassigned variable".into());
2163            };
2164            m.insert(name.clone(), dive_trace::value_json::to_json(v, ctx)?);
2165        }
2166        states.push(m);
2167        labels.push(if i == 0 {
2168            None
2169        } else {
2170            s.action.as_ref().map(|name| dive_trace::Label {
2171                name: name.clone(),
2172                location: Some(s.label.clone()),
2173            })
2174        });
2175    }
2176    let doc = dive_trace::TraceDoc {
2177        variables: r.var_names.clone(),
2178        states,
2179        labels,
2180        ending: Some(ending),
2181        length: Some(recorded.len()),
2182        source: dive_trace::Source::Dive,
2183        properties: Vec::new(),
2184    };
2185    Ok(doc.to_json())
2186}
2187
2188/// The `stopped` block of a run its budget stopped.
2189pub(crate) fn stopped_json(stopped: &dive_runtime::budget::Stopped) -> Value {
2190    json!({
2191        "resource": stopped.resource.name(),
2192        "limit": stopped.limit,
2193        "observed": stopped.observed,
2194        "elapsed_ms": stopped.elapsed_ms,
2195        "unit": stopped.resource.unit(),
2196        "phase": stopped.phase.name(),
2197        "hint": stopped.hint(),
2198    })
2199}
2200
2201fn temporal_planning_evaluation(error: &crate::temporal::Error) -> Option<&dive_eval::EvalError> {
2202    match error {
2203        crate::temporal::Error::Analysis(dive_liveness::analyze::AnalysisError::Planning(
2204            dive_liveness::plan::PlanningError::Evaluation { error, .. },
2205        )) => Some(error),
2206        _ => None,
2207    }
2208}
2209
2210fn temporal_action_evaluation(failure: &crate::temporal::Failure) -> Option<&dive_eval::EvalError> {
2211    let action = failure.action_evaluation()?;
2212    // TLC combines negated claims before simplification; this backend still
2213    // analyzes them separately. Do not invent a verified error for an action
2214    // that a different property could eliminate from the combined formula.
2215    let cause = action.core_cause()?;
2216    (action.properties() == 1
2217        && action.direct_operand()
2218        && cause.class() == dive_eval::ErrorClass::Eval
2219        && cause.ec() == dive_eval::Ec::General
2220        && !cause.is_eval_exception())
2221    .then_some(cause)
2222}
2223
2224fn temporal_evaluation(failure: &crate::temporal::Failure) -> Option<&dive_eval::EvalError> {
2225    failure
2226        .capture_row_error()
2227        .map(|(cause, _, _)| cause)
2228        .or_else(|| temporal_action_evaluation(failure))
2229        .or_else(|| temporal_planning_evaluation(failure.error()))
2230}
2231
2232fn temporal_startup_tautology(failure: &crate::temporal::Failure) -> bool {
2233    matches!(
2234        failure.error(),
2235        crate::temporal::Error::Analysis(
2236            dive_liveness::analyze::AnalysisError::StartupTautology { .. }
2237        )
2238    )
2239}
2240
2241fn temporal_failure_kind(failure: &crate::temporal::Failure) -> &'static str {
2242    use crate::temporal::Error;
2243    use dive_liveness::analyze::AnalysisError;
2244    use dive_liveness::formula::FormulaError;
2245    use dive_liveness::plan::PlanningError;
2246    use dive_liveness::product::ProductError;
2247    if matches!(failure.error(), Error::Analysis(AnalysisError::Stopped(_))) {
2248        return "stopped";
2249    }
2250    if temporal_startup_tautology(failure) || failure.capture_row_error().is_some() {
2251        return "evaluation-error";
2252    }
2253    if let Some(action) = failure.action_evaluation() {
2254        return match action.cause().class() {
2255            dive_eval::ErrorClass::Eval if temporal_action_evaluation(failure).is_some() => {
2256                "evaluation-error"
2257            }
2258            dive_eval::ErrorClass::Eval | dive_eval::ErrorClass::Unsupported => "unsupported",
2259            dive_eval::ErrorClass::ResourceLimit => "resource-limit",
2260            dive_eval::ErrorClass::Bug | dive_eval::ErrorClass::Interrupted => "internal-error",
2261        };
2262    }
2263    match failure.error() {
2264        Error::Analysis(AnalysisError::Exploration(result))
2265            if matches!(result.verdict, Verdict::BudgetMeasurement { .. }) =>
2266        {
2267            "internal-error"
2268        }
2269        Error::Analysis(AnalysisError::Planning(PlanningError::Evaluation { .. })) => {
2270            "evaluation-error"
2271        }
2272        Error::NativeValidation { report, .. }
2273        | Error::Validation { report, .. }
2274        | Error::PrefixValidation { report, .. }
2275        | Error::EndpointValidation { report }
2276            if matches!(report.validation, dive_trace::Validation::Invalid(_)) =>
2277        {
2278            "internal-error"
2279        }
2280        Error::Thread(_)
2281        | Error::Document(_)
2282        | Error::Analysis(
2283            AnalysisError::Inconsistent(_)
2284            | AnalysisError::CaptureThread(_)
2285            | AnalysisError::BudgetStartup(_)
2286            | AnalysisError::BudgetMeasurement(_)
2287            | AnalysisError::Tableau(FormulaError::Reference(_))
2288            | AnalysisError::Planning(PlanningError::Formula {
2289                error: FormulaError::Reference(_),
2290                ..
2291            }),
2292        ) => "internal-error",
2293        Error::Binding(f) => match f.error.kind {
2294            dive_model::ErrorKind::Bug => "internal-error",
2295            dive_model::ErrorKind::Tlc(_) | dive_model::ErrorKind::Eval { .. } => "model-error",
2296            dive_model::ErrorKind::Unsupported { .. } => "unsupported",
2297        },
2298        Error::ValidationResource(_)
2299        | Error::Analysis(
2300            AnalysisError::Product(ProductError::Limit(_))
2301            | AnalysisError::Limit(_)
2302            | AnalysisError::Tableau(FormulaError::Limit(_))
2303            | AnalysisError::Planning(PlanningError::Formula {
2304                error: FormulaError::Limit(_),
2305                ..
2306            }),
2307        ) => "resource-limit",
2308        _ => "unsupported",
2309    }
2310}
2311
2312fn temporal_native_complete(
2313    report: &crate::temporal::Report,
2314) -> Option<&dive_runtime::capture::CompleteEvidence> {
2315    match report.outcome() {
2316        crate::temporal::Outcome::NativeHolds(evidence) => Some(evidence),
2317        crate::temporal::Outcome::NativeViolation(word) => Some(word.evidence()),
2318        _ => None,
2319    }
2320}
2321
2322fn producer_facts(
2323    result: &CheckResult,
2324    stats: dive_runtime::Stats,
2325) -> dive_liveness::analyze::ExplorationEvidence {
2326    dive_liveness::analyze::ExplorationEvidence {
2327        stats,
2328        workers: result.workers.clone(),
2329        collision: result.collision.clone(),
2330        output: result.output.clone(),
2331        warnings: result.warnings.clone(),
2332    }
2333}
2334
2335fn temporal_evidence(
2336    report: &crate::temporal::Report,
2337) -> Option<dive_liveness::analyze::ExplorationEvidence> {
2338    if let Some(complete) = temporal_native_complete(report) {
2339        return Some(producer_facts(complete.safety_result(), complete.stats()));
2340    }
2341    if let crate::temporal::Outcome::NativePrefixViolation(word) = report.outcome() {
2342        return Some(producer_facts(
2343            word.evidence().safety_result(),
2344            word.evidence().stats(),
2345        ));
2346    }
2347    None
2348}
2349
2350/// The store of the exploration behind a temporal report.
2351fn temporal_store(report: &crate::temporal::Report) -> Option<dive_store::StoreMode> {
2352    if let Some(complete) = temporal_native_complete(report) {
2353        return Some(complete.safety_result().store);
2354    }
2355    if let crate::temporal::Outcome::NativePrefixViolation(word) = report.outcome() {
2356        return Some(word.evidence().safety_result().store);
2357    }
2358    None
2359}
2360
2361fn temporal_word(report: &crate::temporal::Report) -> Option<(&str, &dive_trace::TraceDoc, usize)> {
2362    match report.outcome() {
2363        crate::temporal::Outcome::NativeViolation(word) => Some((
2364            &word.word().target_property,
2365            word.document(),
2366            word.word().back_to,
2367        )),
2368        crate::temporal::Outcome::NativePrefixViolation(word) => Some((
2369            &word.word().target_property,
2370            word.document(),
2371            word.word().back_to,
2372        )),
2373        crate::temporal::Outcome::NativeHolds(_) | crate::temporal::Outcome::Safety(_) => None,
2374    }
2375}
2376
2377fn periodic_json(checks: dive_liveness::analyze::periodic::Checks) -> Value {
2378    json!({"min_states": checks.schedule.min_states,
2379        "growth_factor": checks.schedule.growth_factor,
2380        "prefix_checks": checks.prefixes, "last_level": checks.last_level, "last_size": checks.last_size,
2381        "exhausted": checks.exhausted, "final_check": checks.final_check,
2382        "bounds_scope": "capture cumulative; label and product per property per check; no total-run work or byte cap"})
2383}
2384
2385const TEMPORAL_NOTE: &str = "Bounded short-lasso analysis: TLC-exact lasso selection and periodic timing are not claimed. Only independently validated periodic counterexamples are returned; prefix statistics describe the actual committed boundary.";
2386
2387fn temporal_evidence_json(
2388    doc: &mut Value,
2389    capture: &dive_liveness::analyze::ExplorationEvidence,
2390    tlc_fingerprints: bool,
2391) {
2392    let s = &capture.stats;
2393    doc["statistics"] = json!({
2394        "generated": s.generated, "distinct": s.distinct,
2395        "left_on_queue": s.left_on_queue, "depth": s.depth,
2396        "initial_generated": s.initial_generated, "reported_by_tlc": false,
2397    });
2398    doc["output"] = json!(capture.output);
2399    doc["warnings"] = json!(
2400        capture
2401            .warnings
2402            .iter()
2403            .map(|(code, message)| { json!({"code": code, "message": message}) })
2404            .collect::<Vec<_>>()
2405    );
2406    if let Some(collision) = &capture.collision {
2407        doc["collision"] = json!({
2408            "store": "fingerprint", "scheme": if tlc_fingerprints {"tlc"} else {"dive"},
2409            "optimistic": collision.optimistic, "actual": collision.actual,
2410            "assumption": "fingerprints behave as random 64-bit values (TLC's assumption too)",
2411        });
2412    }
2413}
2414
2415fn temporal_json(doc: &mut Value, report: &crate::temporal::Report, tlc_fingerprints: bool) {
2416    let Some(evidence) = temporal_evidence(report) else {
2417        doc["verdict"] = json!("internal-error");
2418        doc["message"] = json!("safety stop was not routed through the safety report");
2419        return;
2420    };
2421    let complete = temporal_native_complete(report).is_some();
2422    doc["execution"] = json!({"stage": if complete {"complete"} else {"prefix"}, "capture_completed": complete, "exhausted": complete});
2423    if let crate::temporal::Outcome::NativePrefixViolation(word) = report.outcome() {
2424        doc["execution"]["level"] = json!(word.evidence().level());
2425    }
2426    if let Some(checks) = report.periodic() {
2427        doc["periodic"] = periodic_json(checks);
2428    }
2429    temporal_evidence_json(doc, &evidence, tlc_fingerprints);
2430    doc["notes"] = json!([TEMPORAL_NOTE]);
2431    doc["elapsed_ms"] = json!(u64::try_from(report.elapsed().as_millis()).unwrap_or(u64::MAX));
2432    if let Some((_, document, back_to)) = temporal_word(report) {
2433        doc["property"] = json!(temporal_property_names(&document.properties));
2434        doc["properties"] = json!(document.properties);
2435        doc["counterexample"] = json!({
2436            "length": document.states.len(), "ending": "lasso", "back_to": back_to + 1,
2437            "states": document.states.iter().enumerate().map(|(i,s)| json!({"index":i+1,"label":null,"action":null,"values":s})).collect::<Vec<_>>(),
2438            "trace": document.to_json(), "validation": "valid",
2439        });
2440    }
2441}
2442
2443// Pinned TLC MP::TLC_TEMPORAL_PROPERTY_VIOLATED names the properties false
2444// on the actual printed word, in configured order.
2445fn temporal_property_names(names: &[String]) -> String {
2446    match names.split_last() {
2447        None => String::new(),
2448        Some((last, [])) => last.clone(),
2449        Some((last, [first])) => format!("{first} and {last}"),
2450        Some((last, rest)) => format!("{}, and {last}", rest.join(", ")),
2451    }
2452}
2453
2454fn temporal_human(report: &crate::temporal::Report) -> String {
2455    use std::fmt::Write as _;
2456    let mut out = String::new();
2457    let Some(complete) = temporal_evidence(report) else {
2458        return "internal-error: unrouted temporal safety stop; no verdict produced\n".to_owned();
2459    };
2460    for (_, warning) in &complete.warnings {
2461        let _ = writeln!(out, "Warning: {warning}");
2462    }
2463    for line in &complete.output {
2464        let _ = writeln!(out, "{line}");
2465    }
2466    if let Some(reason) = &complete.workers.reason {
2467        let _ = writeln!(out, "{reason}");
2468    }
2469    if matches!(report.outcome(), crate::temporal::Outcome::NativeHolds(_)) {
2470        let _ = writeln!(
2471            out,
2472            "Complete final temporal analysis: no error has been found."
2473        );
2474    } else if let Some((_, document, back_to)) = temporal_word(report) {
2475        let names = temporal_property_names(&document.properties);
2476        if document.properties.len() == 1 {
2477            let _ = writeln!(out, "Temporal property {names} was violated.");
2478        } else {
2479            let _ = writeln!(out, "Temporal properties {names} were violated.");
2480        }
2481        let _ = writeln!(out, "Independently validated counterexample:");
2482        for (i, state) in document.states.iter().enumerate() {
2483            let _ = writeln!(out, "State {}: {}", i + 1, json!(state));
2484        }
2485        let _ = writeln!(out, "Back to state {}.", back_to + 1);
2486    }
2487    if let Some(checks) = report.periodic() {
2488        let _ = writeln!(
2489            out,
2490            "Deterministic liveness: {} prefix checks, final check {}, exhausted {}.",
2491            checks.prefixes, checks.final_check, checks.exhausted
2492        );
2493    }
2494    let s = &complete.stats;
2495    let _ = writeln!(
2496        out,
2497        "{} states generated, {} distinct states, depth {}.",
2498        s.generated, s.distinct, s.depth
2499    );
2500    // The store, not the absence of collision figures, decides the claim:
2501    // Core computes no collision probability for temporal runs (ADR 0158).
2502    match (temporal_store(report), &complete.collision) {
2503        (Some(dive_store::StoreMode::Exact), _) => {
2504            let _ = writeln!(out, "Exact full-state storage.");
2505        }
2506        (_, Some(c)) => {
2507            let _ = writeln!(
2508                out,
2509                "Fingerprint collision probability (random 64-bit assumption): optimistic {}, actual {}.",
2510                c.optimistic,
2511                c.actual.as_deref().unwrap_or("not reported")
2512            );
2513        }
2514        (_, None) => {
2515            let _ = writeln!(
2516                out,
2517                "Fingerprint storage (64-bit); collision probability not computed."
2518            );
2519        }
2520    }
2521    let _ = writeln!(out, "{TEMPORAL_NOTE}");
2522    out
2523}
2524
2525fn temporal_limits_json(configuration: crate::temporal::Configuration) -> Value {
2526    use dive_liveness::analyze::GraphLabelPolicy;
2527    use dive_liveness::product::AcceptancePolicy;
2528    let limits = configuration.limits;
2529    let graph_labels = match configuration.graph_labels {
2530        GraphLabelPolicy::Cells(cells) => json!({"kind": "cells", "cells": cells}),
2531        GraphLabelPolicy::NoCellLimit => json!({"kind": "run-budgets"}),
2532    };
2533    let (acceptance, bytes, work) = match configuration.acceptance {
2534        AcceptancePolicy::Cells => (
2535            json!({"kind": "cells", "cells": limits.product.acceptance_cells}),
2536            None,
2537            None,
2538        ),
2539        AcceptancePolicy::Buffers { bytes, work } => (
2540            json!({"kind": "buffers", "bytes": bytes, "materialization_work": work}),
2541            Some(bytes),
2542            Some(work),
2543        ),
2544    };
2545    json!({
2546        "kind": "entry-work-counts-and-acceptance-buffers", "states": limits.capture.states,
2547        "edges": limits.capture.edges, "generated": limits.capture.generated,
2548        "successors_per_unit": limits.capture.successors_per_unit,
2549        "max_expansion_units": dive_runtime::capture::MAX_EXPANSION_UNITS,
2550        "properties": limits.properties,
2551        "cell_limits": {
2552            "graph_labels": graph_labels,
2553            "attribution_rows": {"kind": "cells", "cells": limits.atom_cells},
2554            "word_truth": {"kind": "cells", "cells": limits.atom_cells},
2555        },
2556        "formula_nodes": limits.formula.formula_nodes,
2557        "tableau_nodes": limits.formula.tableau_nodes,
2558        "formula_steps": limits.formula.expansion_steps,
2559        "product_vertices": limits.product.vertices,
2560        "product_edges": limits.product.edges,
2561        "acceptance_buffer_bytes": bytes,
2562        "acceptance_materialization_work": work,
2563        "acceptance_policy": acceptance,
2564        "total_memory_budget": false,
2565        "product_steps": limits.product.steps,
2566    })
2567}
2568
2569#[cfg(test)]
2570#[allow(clippy::expect_used, clippy::panic, reason = "test assertions")]
2571mod evidence_controls {
2572    use super::*;
2573
2574    /// A Core report for `source` and `cfg` under `--compat=tlc`, from files
2575    /// in a fresh directory.
2576    fn core_check(source: &str, cfg: &str, req: CheckRequest) -> CheckReport {
2577        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2578        let directory = std::env::temp_dir().join(format!(
2579            "dive-evidence-controls-{}-{}",
2580            std::process::id(),
2581            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2582        ));
2583        std::fs::create_dir_all(&directory).expect("directory");
2584        let file = directory.join("M.tla");
2585        std::fs::write(&file, source).expect("module");
2586        std::fs::write(file.with_extension("cfg"), cfg).expect("configuration");
2587        let report = check_file_in(
2588            &CheckRequest {
2589                file,
2590                compat_tlc: true,
2591                seed: Some(0),
2592                workers: Some(1),
2593                ..req
2594            },
2595            None,
2596            false,
2597            None,
2598        )
2599        .expect("report");
2600        let _ = std::fs::remove_dir_all(&directory);
2601        report
2602    }
2603
2604    #[test]
2605    fn terminal_sampling_preserves_completed_progress_without_a_proof() {
2606        let source = "---- MODULE M ----\nVARIABLE x\nInit == x = FALSE\nNext == x' = ~x\nP == []<>(x \\/ ~x)\n====\n";
2607        for finished in [
2608            Err(dive_runtime::budget::MeasurementError::unavailable(
2609                dive_runtime::budget::SamplePoint::Final,
2610            )),
2611            Ok(Some(dive_runtime::budget::Exhausted {
2612                resource: dive_runtime::budget::Resource::Memory,
2613                limit: 100,
2614                observed: 101,
2615                elapsed_ms: 2,
2616            })),
2617        ] {
2618            let mut report = core_check(
2619                source,
2620                "INIT Init\nNEXT Next\nPROPERTY P\n",
2621                CheckRequest::default(),
2622            );
2623            assert_eq!(report.verdict(), "success", "{}", report.to_json());
2624            report.finish_budget(finished, Duration::from_millis(2));
2625            let json = report.to_json();
2626            assert_eq!(json["execution"]["stage"], "finalization", "{json}");
2627            assert_eq!(json["execution"]["capture_completed"], true);
2628            assert_eq!(json["statistics"]["distinct"], 2);
2629            assert_eq!(json["statistics"]["generated"], 3);
2630            assert_eq!(json["statistics"]["depth"], 2);
2631            assert_eq!(json["statistics"]["exhaustive"], false);
2632            assert!(json["tlc"].is_null());
2633            assert!(json["counterexample"].is_null());
2634            if finished.is_err() {
2635                assert_eq!(json["verdict"], "internal-error");
2636                assert_eq!(
2637                    json["diagnostics"][0]["code"],
2638                    dive_runtime::budget::MEASUREMENT_FAILURE_CODE
2639                );
2640                assert!(json["stopped"].is_null());
2641            } else {
2642                assert_eq!(json["verdict"], "stopped");
2643                assert_eq!(json["stopped"]["phase"], "finalization");
2644                assert_eq!(json["stopped"]["observed"], 101);
2645            }
2646        }
2647    }
2648
2649    #[test]
2650    fn a_safety_measurement_error_has_actionable_help_without_an_invented_span() {
2651        let mut report = core_check(
2652            "---- MODULE M ----\nVARIABLE x\nInit == x = FALSE\nNext == x' = ~x\n====\n",
2653            "INIT Init\nNEXT Next\n",
2654            CheckRequest::default(),
2655        );
2656        assert_eq!(report.verdict(), "success", "{}", report.to_json());
2657        report.finish_budget(
2658            Err(dive_runtime::budget::MeasurementError::unavailable(
2659                dive_runtime::budget::SamplePoint::Final,
2660            )),
2661            Duration::from_millis(2),
2662        );
2663        let json = report.to_json();
2664        assert_eq!(json["verdict"], "internal-error");
2665        assert_eq!(
2666            json["diagnostics"][0]["code"],
2667            dive_runtime::budget::MEASUREMENT_FAILURE_CODE
2668        );
2669        assert_eq!(json["diagnostics"][0]["cause"], json["message"]);
2670        assert!(
2671            json["diagnostics"][0]["help"]
2672                .as_str()
2673                .is_some_and(|help| help.contains("--max-memory=none"))
2674        );
2675        assert!(json["diagnostics"][0]["span"].is_null());
2676        assert_eq!(json["statistics"]["exhaustive"], false);
2677        assert_eq!(report.exit_code(), exit::INTERNAL);
2678        assert!(json["tlc"].is_null());
2679        assert!(json["stopped"].is_null());
2680        assert!(json["counterexample"].is_null());
2681    }
2682
2683    #[test]
2684    fn default_ceiling_resolution_failure_is_distinct_and_never_unlimited() {
2685        use dive_runtime::budget::{MeasurementKind, SamplePoint};
2686        let error = resolve_memory(BudgetSetting::Default, || None).expect_err("RAM unknown");
2687        assert_eq!(error.kind, MeasurementKind::DefaultCeiling);
2688        assert_eq!(error.point, SamplePoint::Initial);
2689        assert!(resolve_memory(BudgetSetting::Default, || Some(0)).is_err());
2690        assert_eq!(
2691            resolve_memory(BudgetSetting::Explicit(1), || None),
2692            Ok((Some(1), "explicit"))
2693        );
2694        assert_eq!(
2695            resolve_memory(BudgetSetting::Unlimited, || None),
2696            Ok((None, "none"))
2697        );
2698    }
2699}
2700
2701#[cfg(test)]
2702mod binding_report_controls;
2703
2704// Explanatory bound metadata only. It never supplies execution or proof facts.
2705fn symmetry_liveness_json(resolution: &dive_model::SymmetryLivenessResolution) -> Value {
2706    json!({
2707        "declared": resolution.declared(),
2708        "requested": resolution.requested().as_str(),
2709        "genuine_temporal": resolution.genuine_temporal(),
2710        "effective": resolution.effective(),
2711        "scope": if resolution.unreduced() { Some("whole-run") } else { None },
2712    })
2713}
2714
2715#[cfg(test)]
2716#[allow(
2717    clippy::expect_used,
2718    reason = "finite configuration serialization assertions"
2719)]
2720mod product_vertex_report_controls {
2721    use super::*;
2722
2723    #[test]
2724    fn actual_scalar_is_reported_without_changing_other_owner_settings() {
2725        let file = crate::temporal::file_configuration();
2726        assert_eq!(file.limits.product.vertices, usize::MAX);
2727        let mut legacy = file;
2728        legacy.limits = dive_liveness::analyze::Limits::default();
2729        assert_eq!(legacy.limits.product.vertices, 1_000_000);
2730        for vertices in [0, 1, 2, 1_000_000, usize::MAX] {
2731            let mut configured = legacy;
2732            configured.limits.product.vertices = vertices;
2733            let actual = temporal_limits_json(configured);
2734            assert_eq!(actual["product_vertices"], json!(vertices));
2735            let mut expected = temporal_limits_json(file);
2736            expected["product_vertices"] = json!(vertices);
2737            assert_eq!(actual, expected, "only the vertex scalar differs");
2738        }
2739    }
2740}