Skip to main content

dive_api/
diagnostics.rs

1//! Explanations for stable syntax, selected semantic, temporal and command codes.
2//!
3//! Explanations describe a diagnostic family. A concrete report's message and
4//! source remain authoritative for the particular failure. An explanation is
5//! neither a model-checking result nor permission to discard a refusal.
6
7use serde_json::{Value, json};
8
9/// A diagnostic's cause and a concrete next action.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct Explanation {
12    /// Stable diagnostic code, never reused for another meaning.
13    pub code: &'static str,
14    /// What this diagnostic family means.
15    pub cause: &'static str,
16    /// An action that does not presume the refused model was checked.
17    pub remediation: &'static str,
18}
19
20macro_rules! explanations {
21    ($($code:literal => ($cause:literal, $help:literal);)*) => {
22        const CATALOGUE: &[Explanation] = &[$(Explanation {
23            code: $code,
24            cause: $cause,
25            remediation: $help,
26        },)*];
27    };
28}
29
30explanations! {
31    "DIVE-D0001" => ("A native debugger request, frame, handle or supported-session boundary is invalid or unavailable.", "Read the named protocol argument or boundary. Initialize and attach/launch the authorized local check, use handles from the current stop, and continue or terminate explicitly. A failed debugger request is not a model verdict.");
32    "DIVE-A0030" => ("The temporal model could not be bound.", "Fix the accompanying model/configuration diagnostic, then rerun the same check.");
33    "DIVE-A0031" => ("Independent validation rejected a generated temporal counterexample; this is an internal failure.", "Retain the source, configuration, seed, report and candidate trace and file a dive issue; do not treat the candidate as a violation.");
34    "DIVE-A0032" => ("Independent validation could not certify a generated temporal counterexample.", "Read the accompanying validation refusal; use the pinned TLC for the model until that feature is supported. An unvalidated candidate is not a violation.");
35    "DIVE-A0033" => ("A temporal counterexample could not be represented in the trace format.", "Retain the report, source and configuration and file a trace-format issue; do not publish the unrepresented candidate as a certified counterexample.");
36    "DIVE-A0034" => ("A temporal evaluation thread failed, so execution evidence is incomplete.", "Free host thread/memory resources and retry with --workers 1. If it repeats, retain the source, configuration, seed and report and file an issue.");
37    "DIVE-L0020" => ("Temporal planning encountered a feature whose semantics it cannot establish exactly.", "Inspect the named feature and its cause location. Use the pinned TLC for this model and include the smallest reproducer in a dive issue; no budget increase implements a missing feature.");
38    "DIVE-L0021" => ("Temporal formula construction reached an explicit bound.", "Use the pinned TLC for the unchanged model and report the named bound with the source/configuration. --max-memory does not raise formula-count bounds.");
39    "DIVE-L0022" => ("Temporal planning contains an invalid internal formula reference.", "Retain the source, configuration and report and file a dive issue; this is not a property verdict.");
40    "DIVE-L0023" => ("A constant expression failed during temporal source conversion.", "Inspect the expression at the reported source and the accompanying TLC error class; correct its arguments or configuration and rerun.");
41    "DIVE-L0030" => ("Temporal tableau construction failed.", "Inspect the named formula bound or reference failure. Use the pinned TLC for a bounded refusal; report an invalid internal reference as a bug.");
42    "DIVE-L0031" => ("Temporal product construction or acceptance search failed.", "For a named product/acceptance bound, use the pinned TLC and report the capacity limit; changing run budgets does not remove a count bound. For an invalid product shape or witness/search invariant, retain the inputs and report and file an internal bug; do not accept its candidate.");
43    "DIVE-L0032" => ("Safety exploration did not supply a completed behavior graph.", "Read the retained exploration verdict and progress. For a stopped run, follow its resource-specific hint; resolve an earlier model error before retrying liveness.");
44    "DIVE-L0033" => ("A temporal predicate failed evaluation or returned a non-Boolean value.", "Inspect the named property and source expression, including the closing action, and correct the reported value/type error. Retain a minimal reproducer if pinned TLC behaves differently.");
45    "DIVE-L0034" => ("A liveness analysis stage reached an explicit resource bound.", "Include the named bound and progress in a capacity issue and use the pinned TLC for the unchanged model. A resource refusal proves no property.");
46    "DIVE-L0035" => ("The requested temporal analysis mode is not implemented exactly.", "Inspect the named mode. If parallel temporal capture is refused, retry --workers 1; otherwise use the pinned TLC for the unchanged request.");
47    "DIVE-L0036" => ("Temporal acceptance and direct property attribution disagree internally.", "Retain the source, configuration, seed and report and file a dive issue; do not use the candidate as a property verdict.");
48    "DIVE-L0037" => ("The behavior-graph capture thread failed and lost execution evidence.", "Free host thread/memory resources and retry --workers 1; retain the report and file an issue if the failure repeats.");
49    "DIVE-L0038" => ("The run budget stopped temporal analysis before a verdict.", "Follow the stopped block's resource and hint: raise --time-limit or --max-memory only when the host can support it; --time-limit=none disables the time budget. Retain the original progress for comparison.");
50    "DIVE-R0001" => ("The run-budget watchdog could not start, so the requested limits cannot be enforced.", "Free host thread resources and retry. If deliberately running without both guards, pass --time-limit=none --max-memory=none explicitly; no model checking ran before this startup failure.");
51    "DIVE-R0002" => ("A required process-memory observation or physical-RAM lookup was unavailable, so the requested memory guard could not be established.", "Retry on a supported host; if deliberately accepting unlimited memory, pass --max-memory=none explicitly. For an unavailable auto ceiling, an explicit --max-memory value avoids physical-RAM lookup but still requires working process-memory observations. No unavailable reading is zero memory or a model verdict.");
52    "DIVE-X0001" => ("Command arguments are invalid or cannot be decoded as UTF-8.", "Run dive --help (or dive tlc -help), correct the named argument, and provide UTF-8 command arguments.");
53    "DIVE-X0002" => ("The TLC command adapter refused an option or could not transport or independently certify a generated counterexample.", "Read the particular refusal. Use the pinned TLC for an unsupported option; for trace transport, missing run metadata or validation refusal, retain the source/configuration, seed, report and trace and file an issue. An uncertified candidate is not a violation.");
54    "DIVE-X0003" => ("Independent validation rejected a generated TLC-adapter counterexample; this is an internal failure.", "Retain the source, configuration, seed, report and candidate trace and file a dive issue. Do not treat the independently rejected candidate as a property violation.");
55    "DIVE-X0004" => ("A requested specification or configuration file could not be read.", "Check the reported path, working directory and read permissions, then retry with the intended file.");
56}
57
58// The typed match is deliberately exhaustive: a newly assigned syntax code
59// must receive a concrete explanation before this crate can compile.
60macro_rules! syntax_explanations {
61    ($($variant:ident => ($code:literal, $cause:literal, $help:literal);)*) => {
62        const SYNTAX_CODES: &[dive_syntax::Code] = &[$(dive_syntax::Code::$variant,)*];
63
64        pub(crate) fn syntax_explanation(code: dive_syntax::Code) -> &'static Explanation {
65            match code {
66                $(dive_syntax::Code::$variant => &Explanation {
67                    code: $code,
68                    cause: $cause,
69                    remediation: $help,
70                },)*
71            }
72        }
73    };
74}
75
76syntax_explanations! {
77    UnexpectedCharacter => ("DIVE-S0001", "The source contains a character that cannot begin a TLA+ token.", "Inspect the highlighted character; replace it with the intended TLA+ symbol or put literal text inside a quoted string or comment.");
78    BadString => ("DIVE-S0002", "A string literal has an invalid escape or no closing quote.", "Close the string with a double quote and use valid TLA+ string escapes; escape embedded quotes and backslashes.");
79    UnterminatedComment => ("DIVE-S0003", "A block comment remains open at the end of the source.", "Close each open (* block comment with *), including any nested comment.");
80    NoModule => ("DIVE-S0004", "The source has no TLA+ module header.", "Start the module with ---- MODULE Name ---- and finish it with ====; use the file's base name for Name.");
81    MissingModuleEnd => ("DIVE-S0005", "The module ends before its closing delimiter.", "Add ==== after the module's final definition or proof; close any preceding nested module first.");
82    ModuleNameMismatch => ("DIVE-S0006", "The top-level module name differs from its file name.", "Rename the file to match the declared module name, or change the MODULE name to match the file's base name.");
83    InvalidUtf8 => ("DIVE-S0007", "The file contains invalid UTF-8 bytes, which were decoded as replacement characters.", "Save the file as UTF-8 and restore any characters replaced during decoding, then parse it again.");
84    UnexpectedToken => ("DIVE-S0010", "The grammar does not allow this token at the reported position.", "Inspect the highlighted token and its preceding construct; complete missing delimiters or keywords before changing the token.");
85    MissingExpression => ("DIVE-S0011", "A construct requires an expression at this position.", "Supply the missing expression, or remove the operator or separator that requires it; check the preceding definition and delimiters.");
86    PrecedenceConflict => ("DIVE-S0012", "Adjacent operators have overlapping precedence without an explicit grouping.", "Add parentheses around the intended subexpressions so their grouping is explicit.");
87    MissingOperator => ("DIVE-S0013", "Two expressions occur together without an operator between them.", "Insert the intended operator between the expressions, or add the missing delimiter that separates them.");
88    MisplacedOperator => ("DIVE-S0014", "An operator appears where its prefix, infix or postfix form cannot be used.", "Move the operator to its declared position and supply its operands; parenthesize the surrounding expression if needed.");
89    JunctionIndentation => ("DIVE-S0015", "A conjunction or disjunction list item extends left of its bullet's allowed indentation.", "Indent each list item's continuation to the right of its /\\ or \\/ bullet, and align sibling bullets.");
90    StepLevel => ("DIVE-S0020", "A proof step number has the wrong nesting level.", "Make the step's level consistent with its containing proof and sibling steps; use a deeper level only inside a nested proof.");
91    StepNumberMisuse => ("DIVE-S0021", "A proof step number occurs outside a proof or in an expression that cannot contain it.", "Move the numbered step into its proof, or replace the step-number token with the intended expression or reference.");
92    UnexpectedProof => ("DIVE-S0022", "A proof is attached to a construct that cannot take one.", "Attach the proof to a theorem or a proof step that admits a subproof; remove an accidental PROOF keyword.");
93    ProofTooDeep => ("DIVE-S0023", "Proof nesting exceeds SANY's 100-level limit.", "Restructure the proof into shallower subproofs or separate lemmas; increasing a run budget does not change this syntax limit.");
94    BadLabel => ("DIVE-S0030", "The label separator :: does not follow a valid label.", "Place a valid label before ::, or remove the separator if no expression label was intended.");
95    LabelChangesParse => ("DIVE-S0031", "Removing an expression label would change how its expression parses.", "Parenthesize the labeled expression so it has the same grouping with and without the label.");
96    TimesAsArgument => ("DIVE-S0032", "Cartesian product syntax is being used as an operator argument.", "Define a named operator that takes the required arguments and returns their Cartesian product, then pass that operator by name.");
97    SetMapWithIn => ("DIVE-S0033", "A mapped set's result is an unparenthesized membership expression.", "Parenthesize the result expression, for example {(a \\in b) : c \\in d}; keep the bound variables after the colon.");
98    AtInExcept => ("DIVE-S0034", "An EXCEPT selector uses @ as a field name.", "Use the intended field name after !.; use @ only in the replacement expression to refer to the previous value.");
99    BadFairness => ("DIVE-S0035", "A WF_ or SF_ fairness expression has an invalid structure.", "Use WF_vars(Action) or SF_vars(Action), with the state-variable expression after the underscore and the action in parentheses.");
100    NewWithArguments => ("DIVE-S0036", "A NEW declaration gives arguments to a symbol before a set-membership constraint.", "Declare a set-constrained NEW symbol without arguments; put any required operator constraint in a separate assumption.");
101    BadStructuralSelector => ("DIVE-S0037", "A structural selector uses a decimal number as a single selector.", "Separate structural selectors with !, for example Op!1!2; do not write Op!1.2.");
102    NestingTooDeep => ("DIVE-S0040", "Expression nesting exceeds the parser's supported depth.", "Split deeply nested expressions into named operator definitions, then parse the restructured module again.");
103    InputTooLarge => ("DIVE-S0041", "The input exceeds the parser's 4 GiB source-size capacity.", "Split the source into smaller modules and import their definitions; time and memory budgets do not change the source-offset capacity.");
104}
105
106// Semantic coverage is deliberately partial. Only these typed name-resolution
107// and argument-shape families are registered; another code must not borrow help.
108macro_rules! semantic_explanations {
109    ($($variant:ident => ($code:literal, $cause:literal, $help:literal);)*) => {
110        const SEMANTIC_CODES: &[dive_sema::Code] = &[$(dive_sema::Code::$variant,)*];
111
112        fn semantic_explanation(code: dive_sema::Code) -> Option<&'static Explanation> {
113            match code {
114                $(dive_sema::Code::$variant => Some(&Explanation {
115                    code: $code,
116                    cause: $cause,
117                    remediation: $help,
118                }),)*
119                _ => None,
120            }
121        }
122    };
123}
124
125semantic_explanations! {
126    UndefinedSymbol => ("DIVE-E0100", "The referenced name or qualified operator cannot be resolved in the current scope.", "Check the spelling and scope of the intended name. Define the intended operator, declare the intended CONSTANT or VARIABLE, or EXTENDS the module that defines it. For a named INSTANCE, check the Instance!Name qualification and the definitions exported by that instance.");
127    UndefinedOperatorSymbol => ("DIVE-E0101", "The operator symbol used here has no definition in the current scope.", "Extend the module that defines the intended operator, or supply its definition in scope. Arithmetic operators such as + need Naturals, Integers or Reals; unary minus needs Integers or Reals, and sequence concatenation needs Sequences. An operator argument or INSTANCE substitution must also have the required arity.");
128    WrongArgumentCount => ("DIVE-E0107", "An operator application supplies a different number of arguments than its declared arity.", "Match the application to the declared parameter list and the required/provided counts in the message. Reference a zero-argument operator without an argument list; apply function values using brackets.");
129    FunctionArgumentCount => ("DIVE-E0110", "A recognized function definition rules out the supplied number of comma-separated bracket arguments.", "Check the function definition and its bracketed indices. Match comma-separated index parameters; a tuple-pattern parameter counts as one index. A complete tuple index can be supplied as one expression when it matches the function's domain.");
130    OperatorArgumentExpected => ("DIVE-E0112", "A higher-order parameter requires an operator, but its argument is an expression.", "Pass an operator name of the required arity or a LAMBDA with that many parameters; inspect the declared higher-order parameter in the message.");
131    OperatorArgumentArity => ("DIVE-E0113", "An operator supplied to a higher-order parameter has the wrong number of formal parameters.", "Pass an operator with the arity required by the higher-order parameter. If an adapter is intended, define a named operator or LAMBDA with that parameter count and the intended body.");
132    LambdaArgumentArity => ("DIVE-E0114", "A LAMBDA supplied as an operator argument declares the wrong parameter count.", "Match the LAMBDA parameter list to the required operator arity in the message, and make its body use the intended arguments.");
133}
134
135pub(crate) fn semantic_help(code: dive_sema::Code, existing: Option<&str>) -> Option<String> {
136    existing
137        .map(str::to_owned)
138        .or_else(|| semantic_explanation(code).map(|entry| entry.remediation.to_owned()))
139}
140
141/// Looks up an explicitly documented code. Unknown codes return `None`;
142/// guessing an explanation from a code prefix would hide new failure classes.
143///
144/// ```
145/// let entry = dive_api::diagnostics::explain("DIVE-L0020").ok_or("known code")?;
146/// assert!(entry.remediation.contains("pinned TLC"));
147/// assert!(dive_api::diagnostics::explain("DIVE-L9999").is_none());
148/// # Ok::<(), Box<dyn std::error::Error>>(())
149/// ```
150#[must_use]
151pub fn explain(code: &str) -> Option<&'static Explanation> {
152    CATALOGUE
153        .iter()
154        .find(|entry| entry.code == code)
155        .or_else(|| {
156            SYNTAX_CODES
157                .iter()
158                .copied()
159                .find(|syntax| syntax.as_str() == code)
160                .map(syntax_explanation)
161        })
162        .or_else(|| {
163            SEMANTIC_CODES
164                .iter()
165                .copied()
166                .find(|semantic| semantic.as_str() == code)
167                .and_then(semantic_explanation)
168        })
169}
170
171/// A versioned informational report. `known` establishes catalogue coverage
172/// only; this operation does not parse, execute or prove a model.
173#[must_use]
174pub fn explanation_json(code: &str) -> Value {
175    let entry = explain(code);
176    json!({
177        "schema_version": crate::REPORT_SCHEMA_VERSION,
178        "command": "explain",
179        "code": code,
180        "known": entry.is_some(),
181        "explanation": entry.map(|entry| json!({
182            "cause": entry.cause,
183            "remediation": entry.remediation,
184        })),
185    })
186}
187
188/// Retains the actual planning/atom cause location. Stage-wide failures have
189/// no expression location; inventing a root expression would misdirect a fix.
190pub(crate) fn temporal_failure(failure: &crate::temporal::Failure) -> Value {
191    use crate::temporal::Error;
192    use dive_liveness::analyze::AnalysisError;
193    use dive_liveness::plan::PlanningError;
194    let error = failure.error();
195    let source = match error {
196        Error::Analysis(AnalysisError::Planning(PlanningError::Unsupported(refusal))) => {
197            Some(&refusal.cause)
198        }
199        Error::Analysis(
200            AnalysisError::Planning(
201                PlanningError::Evaluation { source, .. } | PlanningError::Formula { source, .. },
202            )
203            | AnalysisError::Atom { source, .. },
204        ) => Some(source.as_ref()),
205        _ => None,
206    };
207    let span = source.and_then(|source| {
208        source.origin.file.map(|file| {
209            json!({
210                "file": file.index(),
211                "start": source.origin.range.0,
212                "end": source.origin.range.1,
213            })
214        })
215    });
216    json!({
217        "code": error.code(),
218        "message": failure.to_string(),
219        "cause": error.to_string(),
220        "span": span,
221        "location": source.map(|source| source.location.as_str()),
222        "help": explain(error.code()).map(|entry| entry.remediation),
223    })
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn semantic_explanations_cover_only_the_selected_typed_codes() {
232        for &code in dive_sema::Code::ALL {
233            let expected = SEMANTIC_CODES.contains(&code);
234            let entry = semantic_explanation(code);
235            assert_eq!(entry.is_some(), expected, "{}", code.as_str());
236            assert_eq!(explain(code.as_str()), entry);
237            if let Some(entry) = entry {
238                assert_eq!(entry.code, code.as_str());
239                assert!(!entry.cause.is_empty() && !entry.remediation.is_empty());
240                assert_eq!(
241                    semantic_help(code, None).as_deref(),
242                    Some(entry.remediation)
243                );
244            } else {
245                assert_eq!(semantic_help(code, None), None);
246            }
247            for existing in ["", "specific producer suggestion"] {
248                assert_eq!(
249                    semantic_help(code, Some(existing)).as_deref(),
250                    Some(existing)
251                );
252            }
253        }
254        for code in ["DIVE-E9999", "DIVE-E0107 extra", "dive-e0107", "DIVE-E0102"] {
255            assert!(explain(code).is_none());
256            assert_eq!(explanation_json(code)["known"], false);
257        }
258    }
259
260    #[test]
261    fn syntax_codes_have_exact_explanations_without_prefix_guessing() {
262        for (index, &code) in SYNTAX_CODES.iter().enumerate() {
263            let entry = syntax_explanation(code);
264            assert_eq!(entry.code, code.as_str());
265            assert!(!entry.cause.is_empty() && !entry.remediation.is_empty());
266            assert!(!SYNTAX_CODES[..index].contains(&code));
267            assert_eq!(explain(code.as_str()), Some(entry));
268            let report = explanation_json(code.as_str());
269            assert_eq!(report["known"], true);
270            assert_eq!(report["schema_version"], crate::REPORT_SCHEMA_VERSION);
271            assert!(report.get("verdict").is_none());
272        }
273        for code in [
274            "DIVE-S0000",
275            "DIVE-S0008",
276            "DIVE-S0038",
277            "dive-s0011",
278            "DIVE-S0011 extra",
279        ] {
280            assert!(explain(code).is_none());
281        }
282    }
283
284    #[test]
285    fn parse_help_preserves_messages_spans_acceptance_and_specific_remediation() {
286        let mut specific = 0;
287        let mut fallback = 0;
288        for source in [
289            "---- MODULE Help ----\nA == \"λ\" /\\\n====\n",
290            "---- MODULE Help ----\nA == 1\n",
291            "---- MODULE Help ----\nA == {1 \\in {1} : c \\in {1}}\n====\n",
292        ] {
293            let raw = dive_syntax::parse_module(source);
294            assert_ne!(raw.diagnostics(), []);
295            let report = crate::parse_source("Help.tla", source);
296            assert_eq!(
297                report.accepted(),
298                !raw.diagnostics()
299                    .iter()
300                    .any(dive_syntax::Diagnostic::is_error)
301            );
302            assert_eq!(report.diagnostics().len(), raw.diagnostics().len());
303            let json = report.to_json(false);
304            for (index, (original, enriched)) in raw
305                .diagnostics()
306                .iter()
307                .zip(report.diagnostics())
308                .enumerate()
309            {
310                assert_eq!(original.code, enriched.code);
311                assert_eq!(original.message, enriched.message);
312                assert_eq!(original.severity, enriched.severity);
313                assert_eq!(original.range, enriched.range);
314                if original.help.is_some() {
315                    specific += 1;
316                } else {
317                    fallback += 1;
318                }
319                let expected = original
320                    .help
321                    .as_deref()
322                    .unwrap_or_else(|| syntax_explanation(original.code).remediation);
323                assert_eq!(enriched.help.as_deref(), Some(expected));
324                assert_eq!(json["diagnostics"][index]["help"], expected);
325                assert_eq!(
326                    json["diagnostics"][index]["span"]["start"],
327                    u32::from(original.range.start())
328                );
329                assert_eq!(
330                    json["diagnostics"][index]["span"]["end"],
331                    u32::from(original.range.end())
332                );
333                let (line, column) =
334                    dive_syntax::diagnostics::line_col(source, original.range.start());
335                assert_eq!(json["diagnostics"][index]["span"]["line"], line);
336                assert_eq!(json["diagnostics"][index]["span"]["column"], column);
337                assert!(report.render_human().contains(expected));
338            }
339        }
340        assert!(specific > 0 && fallback > 0);
341    }
342
343    #[test]
344    fn codes_are_unique_and_unknown_codes_never_borrow_an_explanation() {
345        for (index, entry) in CATALOGUE.iter().enumerate() {
346            assert!(!entry.cause.is_empty() && !entry.remediation.is_empty());
347            assert!(
348                CATALOGUE[..index]
349                    .iter()
350                    .all(|prior| prior.code != entry.code)
351            );
352            assert_eq!(explain(entry.code), Some(entry));
353        }
354        for unknown in [
355            "",
356            "DIVE-L9999",
357            "DIVE-L0020 extra",
358            "dive-l0020",
359            "DIVE-R9999",
360        ] {
361            let report = explanation_json(unknown);
362            assert_eq!(report["known"], false);
363            assert_eq!(report["code"], unknown);
364            assert!(report["explanation"].is_null());
365            assert!(report.get("verdict").is_none());
366        }
367    }
368
369    #[test]
370    fn temporal_diagnostics_retain_the_actual_cause_and_never_invent_a_span()
371    -> Result<(), Box<dyn std::error::Error>> {
372        use crate::temporal::{Error, Failure, Stage};
373        use dive_liveness::analyze::{self, AnalysisError, Limits};
374        use dive_liveness::plan::PlanningError;
375        let source = "---- MODULE Help ----\nEXTENDS TLC\nVARIABLE x\nInit == x=0\nNext == x'=x\nP == IF x'=x THEN [](x=0) ELSE [](x=0)\n====\n";
376        let analysis =
377            dive_sema::analyze_source("Help.tla", source, &dive_sema::Options::default());
378        assert!(analysis.accepted());
379        let ir = std::sync::Arc::new(dive_ir::lower(&analysis)?);
380        let config = dive_config::parse("INIT Init\nNEXT Next\nPROPERTY P\n")
381            .into_config()
382            .ok_or("valid configuration")?;
383        let model = dive_model::bind(ir, &config, &dive_model::BindOptions::tlc())
384            .map_err(|e| format!("{e:?}"))?;
385        // The planner's own refusal of an action-level temporal guard, as the
386        // checker reports it before any search.
387        let Err(planning) = dive_liveness::plan::lower_violation(
388            &model,
389            &model.property_claims()[0].pred,
390            Limits::default().formula,
391        ) else {
392            return Err("an action-level temporal guard must refuse".into());
393        };
394        let failure = Failure::before(
395            Error::Analysis(AnalysisError::Planning(planning)),
396            Stage::Analysis(analyze::Stage::Planning),
397        );
398        let Error::Analysis(AnalysisError::Planning(PlanningError::Unsupported(refusal))) =
399            failure.error()
400        else {
401            return Err(format!("expected source-aware refusal: {failure}").into());
402        };
403        let value = temporal_failure(&failure);
404        assert_eq!(value["code"], "DIVE-L0020");
405        assert_eq!(value["cause"], failure.error().to_string());
406        assert_eq!(value["location"], refusal.cause.location);
407        assert_eq!(value["span"]["start"], refusal.cause.origin.range.0);
408        assert_eq!(value["span"]["end"], refusal.cause.origin.range.1);
409        let (start, end) = refusal.cause.origin.range;
410        assert_eq!(&source[start as usize..end as usize], "x'=x");
411        assert!(value["span"]["file"].is_number());
412        assert!(
413            value["help"]
414                .as_str()
415                .is_some_and(|help| help.contains("pinned TLC"))
416        );
417        assert!(value.get("verdict").is_none());
418
419        let failure = Failure::before(
420            Error::Analysis(AnalysisError::Limit("properties")),
421            Stage::Analysis(analyze::Stage::Planning),
422        );
423        let value = temporal_failure(&failure);
424        assert_eq!(value["code"], "DIVE-L0034");
425        assert!(value["span"].is_null() && value["location"].is_null());
426        assert!(value["help"].is_string());
427        Ok(())
428    }
429}