smix-error 13.1.0

smix-error — ExpectationFailure + FailureCode + AI-readable to_prompt + buildSuggestions (stone, cold path).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
#![doc = include_str!("../README.md")]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]

//! smix-error — ExpectationFailure + FailureCode + AI-readable
//! `to_prompt()` + `build_suggestions` (stone, cold path).
//!
//! `build_suggestions` behavior: threshold > 0.5, top 3, sort by score
//! descending → field (name > id > text) → DFS index ascending.
//!
//! # Why a separate stone
//!
//! SDK / driver / runner-client all throw / catch `ExpectationFailure`. As
//! the canonical failure type it must live in a leaf crate that everyone
//! can depend on. Failure messages MUST be AI-readable — `to_prompt()`
//! is the canonical render.

#![doc(html_root_url = "https://docs.smix.dev/smix-error")]

use serde::{Deserialize, Serialize};
use smix_screen::{ElementSummary, ScreenFacts, WindowInfo, WindowKind};
use smix_selector::{Selector, describe_selector};
use std::fmt;

/// All failure codes smix surfaces back to the SDK / MCP / CLI
/// (SCREAMING_SNAKE_CASE wire).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
// New codes keep arriving — two in two releases — and on an exhaustive
// enum each one is a major, because a consumer matching every arm stops
// compiling. That is the wrong price for smix naming a failure more
// precisely, and it was about to be paid for the second time.
//
// The cost lands once, here, in a major that was already owed: every
// downstream `match` needs a catch-all arm from now on. What it buys is
// that the next code is additive.
//
// The guard that made a new variant fail to compile lives inside this
// crate now (see `the_vocabulary_is_pinned` below). From out here
// `non_exhaustive` would have made it accept anything, so it moved
// rather than being weakened.
#[non_exhaustive]
pub enum FailureCode {
    /// Selector matched zero elements in the visible tree.
    ElementNotFound,
    /// Element matched but failed the visibility filter.
    NotVisible,
    /// Element matched but `enabled = false`.
    NotEnabled,
    /// Selector matched multiple elements (when uniqueness was required).
    Ambiguous,
    /// Operation exceeded the implicit-wait budget.
    Timeout,
    /// `expect` assertion (e.g. `toHaveText`) did not hold.
    AssertionFailed,
    /// Target app exited or never launched.
    AppNotRunning,
    /// Simulator device is not booted.
    SimulatorNotBooted,
    /// The touch was synthesised, and it did not land inside the
    /// element the selector matched.
    ///
    /// Distinct from `ElementNotFound` because the two send a reader
    /// somewhere different: not-found means fix the selector, missed
    /// means the element was there and the touch went elsewhere — a
    /// stale frame, or something moved between the tree fetch and the
    /// tap.
    TapMissed,
    /// The screen is described in one coordinate space and the touch
    /// would be delivered in another, so no aim can land where the tree
    /// says the element is.
    ///
    /// Distinct from `TapMissed`, and the distinction is the whole
    /// point: a miss says the element was there and the touch went
    /// elsewhere, which invites another attempt with a better point.
    /// There is no better point here — whatever is passed gets
    /// recomputed against the app's frame and then read against the
    /// device's. Retrying is the trap, and the consumer who found this
    /// spent an afternoon in it.
    CoordinateSpaceMismatch,
    /// Catch-all for runner / driver / IO failures.
    DriverError,
    /// The device's capture path is under load and refusing frames for a
    /// stated window — the screenshot pacer's circuit is open.
    ///
    /// Separate from [`Self::DriverError`] because the two want opposite
    /// responses and only one of them is a defect. A driver error means
    /// something is broken; this means "not now, try again shortly", and
    /// a caller with time left can simply keep waiting. It arrived as a
    /// `DriverError` until 7.1, which is how a consumer's release gate
    /// met it: `FAIL [DRIVER_ERROR]` from `waitForAnimationToEnd`, a
    /// verb whose entire meaning is to wait.
    CaptureBackpressure,
}

/// Structured failure thrown by SDK matchers and driver calls. Shape
/// is AI-feed-back-ready.
///
/// `selector` is the typed `Selector` rather than the wire
/// `serde_json::Value` — callers raising failures from the driver / SDK
/// side already have the typed selector, and `to_prompt` invokes
/// `describe_selector` for stable rendering.
///
/// Serializes as `{ ok: false, code, message, selector, suggestions,
/// visibleElements, hint, screenshot, deviceLog }`; the `ok = false`
/// discriminant identifies the failure branch of a `Result` wire.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExpectationFailure {
    /// Always `false` for failures. Round-trip discriminator for
    /// `Result<T, ExpectationFailure>` wire.
    pub ok: False,
    /// Failure code discriminator.
    pub code: FailureCode,
    /// Human-readable summary (and AI-readable when fed into `to_prompt`).
    pub message: String,
    /// Originating selector, when one is available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selector: Option<Selector>,
    /// Ranked near-miss suggestions (edit-distance to label / id / etc.).
    #[serde(default)]
    pub suggestions: Vec<String>,
    /// Snapshot of visible+enabled elements at failure time.
    #[serde(default)]
    pub visible_elements: Vec<ElementSummary>,
    /// Optional one-line hint (e.g. "try `app.wait_for(...)` first").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
    /// The smix that produced this failure.
    ///
    /// Not decoration. A consumer wrote up two defects against smix
    /// behaviour that had been fixed hours earlier, quoting an error
    /// message the current build no longer emits — they had no way to
    /// tell whether the smix in front of them contained the fix for
    /// the thing they had just hit. A failure that names its version
    /// makes that answerable from the failure itself.
    ///
    /// Set by [`ExpectationFailure::new`] from the crate version, so no
    /// call site can forget it.
    #[serde(default)]
    pub smix_version: String,
    /// base64-encoded PNG; omitted from default rendering to keep logs lean.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshot: Option<String>,
    /// Last-N-lines of captured device log, folded into AI-readable
    /// output for failure-window system context.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub device_log: Vec<String>,
    /// How many elements `visible_elements` was cut from.
    ///
    /// A list of ten read as the whole screen: a consumer built a
    /// detector on it that called every Android failure blind, because
    /// the ten were always the status bar. The total says it is a
    /// sample.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub visible_total: Option<usize>,
    /// The windows the screen held when this failed, focused app first.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub windows: Vec<WindowInfo>,
    /// Windows the reader could not read. "The app is not in the tree"
    /// and "the app's window could not be read" are different failures.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unreadable_windows: Option<u32>,
}

/// Newtype around `false` — used as the [`ExpectationFailure::ok`]
/// discriminator. Serializes/deserializes as the JSON literal `false`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct False(pub bool);

/// Builder/Init form for ergonomic construction.
#[derive(Default)]
pub struct FailureInit {
    /// Optional failure code (defaults to `DriverError` if `None`).
    pub code: Option<FailureCode>,
    /// Human-readable / AI-readable message.
    pub message: String,
    /// Originating selector, when one is available.
    pub selector: Option<Selector>,
    /// Pre-built ranked near-miss suggestions.
    pub suggestions: Vec<String>,
    /// Captured visible+enabled elements at failure time.
    pub visible_elements: Vec<ElementSummary>,
    /// Optional one-line hint string.
    pub hint: Option<String>,
    /// Optional base64 PNG screenshot at failure time.
    pub screenshot: Option<String>,
    /// Optional captured device log tail.
    pub device_log: Vec<String>,
    /// See [`ExpectationFailure::visible_total`].
    pub visible_total: Option<usize>,
    /// See [`ExpectationFailure::windows`].
    pub windows: Vec<WindowInfo>,
    /// See [`ExpectationFailure::unreadable_windows`].
    pub unreadable_windows: Option<u32>,
}

impl FailureInit {
    /// The screen the failure happened on: its elements (already in the
    /// order a reader should meet them), how many there were, whose
    /// windows they sat in, and how many windows could not be read.
    ///
    /// One entry point, so a call site cannot hand over the list and
    /// forget the count that says it is a sample.
    #[must_use]
    pub fn with_screen(mut self, facts: ScreenFacts) -> Self {
        self.visible_elements = facts.elements;
        self.visible_total = Some(facts.total);
        self.windows = facts.windows;
        self.unreadable_windows = (facts.unreadable > 0).then_some(facts.unreadable);
        self
    }

    /// The screen an earlier failure described, carried into a new one.
    ///
    /// For a failure that re-states another (a timeout reported as "not
    /// visible"): copying `visible_elements` by hand left the count and
    /// the windows behind, and the next field added would be left behind
    /// the same way.
    #[must_use]
    pub fn with_screen_from(mut self, earlier: &ExpectationFailure) -> Self {
        self.visible_elements = earlier.visible_elements.clone();
        self.visible_total = earlier.visible_total;
        self.windows = earlier.windows.clone();
        self.unreadable_windows = earlier.unreadable_windows;
        self
    }
}

impl ExpectationFailure {
    /// Construct from an init struct. `code` defaults to `DriverError`
    /// if `init.code` was None (defensive; SDK callers should always
    /// set it).
    pub fn new(init: FailureInit) -> Self {
        ExpectationFailure {
            ok: False(false),
            code: init.code.unwrap_or(FailureCode::DriverError),
            message: init.message,
            selector: init.selector,
            suggestions: init.suggestions,
            visible_elements: init.visible_elements,
            hint: init.hint,
            smix_version: env!("CARGO_PKG_VERSION").to_string(),
            screenshot: init.screenshot,
            device_log: init.device_log,
            visible_total: init.visible_total,
            windows: init.windows,
            unreadable_windows: init.unreadable_windows,
        }
    }

    /// AI-facing rendering. Designed so the output can be pasted back
    /// as a user message into a coding agent.
    #[must_use]
    pub fn to_prompt(&self) -> String {
        let mut lines: Vec<String> = Vec::new();
        lines.push(format!(
            "FAIL [{}]: {}",
            format_code(self.code),
            self.message
        ));
        // The version, on every failure, because the reader's next
        // question after "what went wrong" is often "is my smix old".
        // A consumer once wrote up two defects that had been fixed
        // hours earlier, quoting a message this build no longer emits.
        if !self.smix_version.is_empty() {
            lines.push(format!("  smix: {}", self.smix_version));
        }
        if let Some(sel) = &self.selector {
            lines.push(format!("  selector: {}", describe_selector(sel)));
        }
        if !self.suggestions.is_empty() {
            lines.push("  suggestions:".into());
            for s in &self.suggestions {
                lines.push(format!("    - {}", s));
            }
        }
        if let Some(line) = on_screen_line(&self.windows, self.unreadable_windows) {
            lines.push(line);
        }
        if !self.visible_elements.is_empty() {
            let n = self.visible_elements.len().min(10);
            lines.push(match self.visible_total {
                Some(total) if self.windows.iter().any(|w| w.focused) => {
                    format!("  visible elements ({n} of {total}, the focused app's first):")
                }
                Some(total) => format!("  visible elements ({n} of {total}):"),
                None => format!("  visible elements (top {n}):"),
            });
            for el in self.visible_elements.iter().take(10) {
                lines.push(format!("    - {}", render_element(el)));
            }
        }
        if let Some(h) = &self.hint {
            lines.push(format!("  hint: {}", h));
        }
        if !self.device_log.is_empty() {
            // LOG_PROMPT_CAP — defensive ceiling for AI prompt size.
            const LOG_PROMPT_CAP: usize = 200;
            let n = self.device_log.len();
            lines.push(format!("  device log (last {} lines):", n));
            let start = n.saturating_sub(LOG_PROMPT_CAP);
            for dl in &self.device_log[start..] {
                lines.push(format!("    - {}", dl));
            }
        }
        lines.join("\n")
    }
}

impl fmt::Display for ExpectationFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_prompt())
    }
}

impl std::error::Error for ExpectationFailure {}

/// One line naming the windows a failure's screen held.
///
/// Repeats collapse (`×2`) because a status bar and a navigation bar are
/// both `com.android.systemui`, and listing it twice says nothing the
/// count does not. `None` when there is nothing to say — a tree that
/// carries no window information gets no line rather than an empty one.
fn on_screen_line(windows: &[WindowInfo], unreadable: Option<u32>) -> Option<String> {
    let mut parts: Vec<(String, usize)> = Vec::new();
    for w in windows {
        let who = w.package.as_deref().unwrap_or("(package not reported)");
        let kind = match w.kind {
            WindowKind::Application => "application",
            WindowKind::InputMethod => "keyboard",
            WindowKind::System => "system",
            WindowKind::Other => "other",
        };
        let label = if w.focused {
            format!("{who} ({kind}, focused)")
        } else {
            format!("{who} ({kind})")
        };
        match parts.last_mut() {
            Some((last, n)) if *last == label => *n += 1,
            _ => parts.push((label, 1)),
        }
    }
    let mut bits: Vec<String> = parts
        .into_iter()
        .map(|(l, n)| if n > 1 { format!("{l} ×{n}") } else { l })
        .collect();
    match unreadable {
        Some(1) => bits.push("1 window unreadable".into()),
        Some(n) if n > 1 => bits.push(format!("{n} windows unreadable")),
        _ => {}
    }
    (!bits.is_empty()).then(|| format!("  on screen: {}", bits.join(" · ")))
}

fn format_code(c: FailureCode) -> &'static str {
    match c {
        FailureCode::ElementNotFound => "ELEMENT_NOT_FOUND",
        FailureCode::NotVisible => "NOT_VISIBLE",
        FailureCode::NotEnabled => "NOT_ENABLED",
        FailureCode::Ambiguous => "AMBIGUOUS",
        FailureCode::Timeout => "TIMEOUT",
        FailureCode::AssertionFailed => "ASSERTION_FAILED",
        FailureCode::AppNotRunning => "APP_NOT_RUNNING",
        FailureCode::SimulatorNotBooted => "SIMULATOR_NOT_BOOTED",
        FailureCode::TapMissed => "TAP_MISSED",
        FailureCode::CoordinateSpaceMismatch => "COORDINATE_SPACE_MISMATCH",
        FailureCode::DriverError => "DRIVER_ERROR",
        FailureCode::CaptureBackpressure => "CAPTURE_BACKPRESSURE",
    }
}

fn render_element(el: &ElementSummary) -> String {
    let role_str = el.role.map(|r| r.as_str()).unwrap_or("unknown");
    let mut bits: Vec<String> = vec![role_str.to_string()];
    if let Some(n) = &el.name {
        bits.push(format!("name={:?}", n));
    }
    if let Some(i) = &el.id {
        bits.push(format!("id=\"{}\"", i));
    }
    if let Some(t) = &el.text
        && Some(t) != el.name.as_ref()
    {
        bits.push(format!("text={:?}", t));
    }
    if !el.enabled {
        bits.push("disabled".into());
    }
    bits.join(" ")
}

// -------------------- buildSuggestions ----------------------------------

const SUGGESTION_THRESHOLD: f64 = 0.5;
const SUGGESTION_TOP_N: usize = 3;

/// Generate "Did you mean ...?" suggestions from the current visible
/// element list. Contract: threshold > 0.5, top 3, score desc →
/// field (name > text) → DFS index asc.
///
/// `target = None` → empty vec.
#[must_use]
pub fn build_suggestions(target: Option<&str>, visible: &[ElementSummary]) -> Vec<String> {
    let Some(target) = target else {
        return Vec::new();
    };
    let lower_target = target.to_lowercase();
    let mut candidates: Vec<(f64, &'static str, String, usize)> = Vec::new();
    for (i, el) in visible.iter().enumerate() {
        let mut best: Option<(f64, &'static str, String)> = None;
        if let Some(name) = &el.name
            && !name.is_empty()
        {
            let s = similarity(&name.to_lowercase(), &lower_target);
            if s > SUGGESTION_THRESHOLD {
                best = Some((s, "name", name.clone()));
            }
        }
        if let Some(id) = &el.id
            && !id.is_empty()
        {
            let s = similarity(&id.to_lowercase(), &lower_target);
            if s > SUGGESTION_THRESHOLD && best.as_ref().map(|(bs, _, _)| s > *bs).unwrap_or(true) {
                best = Some((s, "id", id.clone()));
            }
        }
        if let Some(text) = &el.text
            && !text.is_empty()
        {
            let s = similarity(&text.to_lowercase(), &lower_target);
            if s > SUGGESTION_THRESHOLD && best.as_ref().map(|(bs, _, _)| s > *bs).unwrap_or(true) {
                best = Some((s, "text", text.clone()));
            }
        }
        if let Some((score, field, value)) = best {
            candidates.push((score, field, value, i));
        }
    }
    // Sort: score desc → field name>text → index asc.
    let field_rank = |f: &str| match f {
        "name" => 0,
        "id" => 1,
        _ => 2, // text
    };
    candidates.sort_by(|a, b| {
        b.0.partial_cmp(&a.0)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| field_rank(a.1).cmp(&field_rank(b.1)))
            .then_with(|| a.3.cmp(&b.3))
    });
    candidates
        .into_iter()
        .take(SUGGESTION_TOP_N)
        .map(|(score, field, value, _)| {
            format!(
                "Did you mean {:?}? (similarity {:.2}, field {})",
                value, score, field
            )
        })
        .collect()
}

/// Normalized `[0, 1]` string similarity. 1 = identical,
/// 0 = completely different.
#[must_use]
pub fn similarity(a: &str, b: &str) -> f64 {
    if a == b {
        return 1.0;
    }
    let (longer, shorter) = if a.chars().count() >= b.chars().count() {
        (a, b)
    } else {
        (b, a)
    };
    let llen = longer.chars().count();
    if llen == 0 {
        return 1.0;
    }
    let dist = edit_distance(longer, shorter);
    (llen as f64 - dist as f64) / llen as f64
}

/// Levenshtein edit distance (Wagner-Fischer).
#[must_use]
pub fn edit_distance(a: &str, b: &str) -> usize {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let a_len = a_chars.len();
    let b_len = b_chars.len();
    let mut dp: Vec<usize> = (0..=b_len).collect();
    for i in 1..=a_len {
        let mut prev = dp[0];
        dp[0] = i;
        for j in 1..=b_len {
            let tmp = dp[j];
            dp[j] = if a_chars[i - 1] == b_chars[j - 1] {
                prev
            } else {
                1 + dp[j].min(dp[j - 1]).min(prev)
            };
            prev = tmp;
        }
    }
    dp[b_len]
}

impl FailureCode {
    /// Every code, once.
    ///
    /// Exported because the alternative is a second hand-written copy,
    /// and there was one: `tests/it/sdk_failure_code_parity.rs` kept its
    /// own `all_variants()` list, and every assertion in that file —
    /// the three SDK declarations and the errors guide — is derived
    /// from it. Its docstring said adding a variant would stop the file
    /// compiling. That stopped being true when the exhaustiveness guard
    /// moved in here, because `#[non_exhaustive]` makes an outside
    /// `match` accept anything; adding `CaptureBackpressure` in 7.1 left
    /// all seven of those assertions green while no SDK declared it.
    ///
    /// [`Self::ALL`] is the one list. The exhaustive match in
    /// `the_vocabulary_is_pinned` guards it from in here, where
    /// `non_exhaustive` cannot weaken the match, and everything else
    /// reads it rather than repeating it.
    pub const ALL: &'static [FailureCode] = &[
        FailureCode::ElementNotFound,
        FailureCode::NotVisible,
        FailureCode::NotEnabled,
        FailureCode::Ambiguous,
        FailureCode::Timeout,
        FailureCode::AssertionFailed,
        FailureCode::AppNotRunning,
        FailureCode::SimulatorNotBooted,
        FailureCode::TapMissed,
        FailureCode::CoordinateSpaceMismatch,
        FailureCode::DriverError,
        FailureCode::CaptureBackpressure,
    ];

    /// Whether this code is a verdict about the screen, as opposed to
    /// smix being unable to look at it.
    ///
    /// Two readers ask this and must get the same answer. A flow step
    /// marked `optional` turns a verdict into a skip and lets a driver
    /// failure fail the step; an end-to-end check judges a flow by its
    /// own rule only when the flow failed on a verdict, and names the
    /// driver's code otherwise. A runner that answered garbage once read,
    /// in one of those checks, as "the scroll stopped in the wrong place"
    /// — the red carried a verdict that was not its own.
    ///
    /// Exhaustive on purpose: a code added later does not compile until
    /// somebody has said which side it is on.
    pub fn judges_the_screen(self) -> bool {
        match self {
            FailureCode::ElementNotFound
            | FailureCode::NotVisible
            | FailureCode::NotEnabled
            | FailureCode::Ambiguous
            | FailureCode::Timeout
            | FailureCode::AssertionFailed
            | FailureCode::TapMissed
            | FailureCode::CoordinateSpaceMismatch => true,
            FailureCode::AppNotRunning
            | FailureCode::SimulatorNotBooted
            | FailureCode::DriverError
            | FailureCode::CaptureBackpressure => false,
        }
    }
}

#[cfg(test)]
mod what_a_code_is_about {
    use super::*;

    /// The eight codes that say something about the screen, and the four
    /// that say smix could not look. Named rather than counted: a code
    /// moved from one side to the other has to be moved here too.
    #[test]
    fn a_verdict_is_about_the_screen_and_a_driver_failure_is_not() {
        let about_the_screen = [
            FailureCode::ElementNotFound,
            FailureCode::NotVisible,
            FailureCode::NotEnabled,
            FailureCode::Ambiguous,
            FailureCode::Timeout,
            FailureCode::AssertionFailed,
            FailureCode::TapMissed,
            FailureCode::CoordinateSpaceMismatch,
        ];
        let could_not_look = [
            FailureCode::AppNotRunning,
            FailureCode::SimulatorNotBooted,
            FailureCode::DriverError,
            FailureCode::CaptureBackpressure,
        ];
        for c in about_the_screen {
            assert!(c.judges_the_screen(), "{c:?} is a verdict about the screen");
        }
        for c in could_not_look {
            assert!(
                !c.judges_the_screen(),
                "{c:?} says smix could not look, not what it saw"
            );
        }
        assert_eq!(
            about_the_screen.len() + could_not_look.len(),
            FailureCode::ALL.len(),
            "every code is on one side or the other"
        );
    }
}

#[cfg(test)]
mod vocabulary {
    use super::*;

    /// A new `FailureCode` must not compile until it has been thought
    /// about everywhere.
    ///
    /// This match is exhaustive on purpose and lives inside the crate on
    /// purpose: `#[non_exhaustive]` makes an outside `match` accept
    /// anything, so the guard that used to sit in
    /// `tests/it/sdk_failure_code_parity.rs` would have started passing for
    /// every future variant. Adding a code should break this line, then
    /// the wire-string arm below it, then the three SDK declarations the
    /// parity test reads, then the errors guide.
    #[test]
    fn the_vocabulary_is_pinned() {
        let every = FailureCode::ALL;
        for &code in every {
            match code {
                FailureCode::ElementNotFound
                | FailureCode::NotVisible
                | FailureCode::NotEnabled
                | FailureCode::Ambiguous
                | FailureCode::Timeout
                | FailureCode::AssertionFailed
                | FailureCode::AppNotRunning
                | FailureCode::SimulatorNotBooted
                | FailureCode::TapMissed
                | FailureCode::CoordinateSpaceMismatch
                | FailureCode::DriverError
                | FailureCode::CaptureBackpressure => {}
            }
            // Every code renders as a wire string, and a code whose
            // string nobody wrote would reach a consumer as whatever
            // the formatter defaults to.
            assert!(!format_code(code).is_empty(), "{code:?} has no wire string");
        }
        assert_eq!(
            every.len(),
            12,
            "counted off the list above, not remembered"
        );
    }
}