openlatch-client 0.6.1

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! The result card that closes a rail, and the `result=` line that closes a
//! plain (no-TTY) run.
//!
//! The card knows nothing about doctor reports: a caller maps its own verdict
//! onto [`Verdict`] and its facts onto [`Row`]s and [`Section`]s. Text may mark
//! a command or a URL with backticks (`` `openlatch doctor` ``); the backticks
//! are dropped and, where colour is on, the span is drawn cyan.
//!
//! ```text
//!   ╭──────────────────────────────────────────────────────────────────────╮
//!   │                                                                      │
//!   │ ✓  OpenLatch is live on this machine                                 │
//!   │                                                                      │
//!   │    Organization   SuperAdmin                                         │
//!   │    Agent          Cline                                              │
//!   │                   actions controlled · model calls not observed      │
//!   │                                                                      │
//!   │    Next           Keep using Cline as usual.                         │
//!   │                                                                      │
//!   ╰──────────────────────────────────────────────────────────────────────╯
//!   Check anytime openlatch status   ·   Full diagnostics openlatch doctor
//! ```

use super::term::{Caps, Mode};
use super::{fit_glyphs, paint, style, style_over, wrap};

/// Columns inside the card's border.
const INNER: usize = 70;
/// Indent of a row inside the card.
const INDENT: usize = 4;
/// Width of the label column.
const LABEL: usize = 15;
/// Room left for a row's value (one column of right margin).
const VALUE: usize = INNER - INDENT - LABEL - 1;

/// What the card announces. Decides glyph, colour and the `result=` token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
    /// Everything ran and nothing needs the user. Green ✓.
    Live,
    /// Running, but the user has one thing to do. Amber !.
    NeedsAttention,
    /// Nothing to connect on this machine yet. Amber !.
    NoAgent,
    /// A stage failed; the machine is not protected. Red ✗.
    NotLive,
}

impl Verdict {
    /// The `result=` token: `live`, `attention` or `not_live` — the same
    /// vocabulary as `init --json`'s `verdict` key. `NoAgent` is an
    /// `attention` whose reason [`result_line`] adds.
    pub fn token(self) -> &'static str {
        match self {
            Self::Live => "live",
            Self::NeedsAttention | Self::NoAgent => "attention",
            Self::NotLive => "not_live",
        }
    }

    fn glyph(self, caps: &Caps) -> &'static str {
        let g = caps.glyphs();
        match self {
            Self::Live => g.ok,
            Self::NeedsAttention | Self::NoAgent => g.warn,
            Self::NotLive => g.fail,
        }
    }

    fn paint(self, text: &str, on: bool) -> String {
        match self {
            Self::Live => paint::green(text, on),
            Self::NeedsAttention | Self::NoAgent => paint::amber(text, on),
            Self::NotLive => paint::red(text, on),
        }
    }
}

/// How an `openlatch update` run ended: its `result=` token, the card's tone
/// and headline, and the exit code, as the update playground has them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Update {
    /// The new version is installed and running. Green ✓, exit 0.
    Updated,
    /// Already on the latest release. Green ✓, exit 0.
    UpToDate,
    /// A newer release exists and nothing asked to apply it (no terminal to
    /// ask). Amber !, exit 7.
    Available,
    /// The user answered "Not now". Amber !, exit 7.
    Declined,
    /// The update server did not answer; nothing changed. Amber !, exit 7.
    CheckFailed,
    /// A stage failed; the old version is still running. Red ✗, exit 1.
    Failed,
    /// The new version did not start and the old one was restored. Red ✗,
    /// exit 1.
    RolledBack,
}

impl Update {
    /// The `result=` token: `updated`, `up_to_date`, `available`, `declined`,
    /// `check_failed`, `failed` or `rolled_back`.
    pub fn token(self) -> &'static str {
        match self {
            Self::Updated => "updated",
            Self::UpToDate => "up_to_date",
            Self::Available => "available",
            Self::Declined => "declined",
            Self::CheckFailed => "check_failed",
            Self::Failed => "failed",
            Self::RolledBack => "rolled_back",
        }
    }

    /// The card's glyph and colour.
    pub fn verdict(self) -> Verdict {
        match self {
            Self::Updated | Self::UpToDate => Verdict::Live,
            Self::Available | Self::Declined | Self::CheckFailed => Verdict::NeedsAttention,
            Self::Failed | Self::RolledBack => Verdict::NotLive,
        }
    }

    /// The health convention: 0 ok, 7 needs attention, 1 failed.
    pub fn exit_code(self) -> i32 {
        match self.verdict() {
            Verdict::Live => 0,
            Verdict::NeedsAttention | Verdict::NoAgent => crate::cli::report::EXIT_DEGRADED,
            Verdict::NotLive => 1,
        }
    }

    /// The card's headline, `from` the running version `to` the release:
    /// `OpenLatch 0.5.8 is running`. A failure's headline names what stopped
    /// it (`Update stopped: the download didn't verify`), so the caller
    /// finishes the generic one given here.
    pub fn title(self, from: &str, to: &str) -> String {
        match self {
            Self::Updated => format!("OpenLatch {to} is running"),
            Self::UpToDate => format!("OpenLatch {to} is up to date"),
            Self::Available => format!("{to} is available"),
            Self::Declined => format!("Not updated · still on {from}"),
            Self::CheckFailed => "Couldn't check for updates".to_string(),
            Self::Failed => "Update stopped".to_string(),
            Self::RolledBack => format!("{to} didn't start, so {from} is back"),
        }
    }
}

/// One labelled fact. An empty label continues the row above.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Row {
    pub label: String,
    pub value: String,
    /// Secondary information, drawn dim.
    pub dim: bool,
    /// A dim qualifier after the value, on the same line when it fits:
    /// `first sync in progress` + `· applies on arrival`.
    pub tail: String,
}

impl Row {
    /// A labelled row.
    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            value: value.into(),
            dim: false,
            tail: String::new(),
        }
    }

    /// A dim, unlabelled line under the row above (e.g. a coverage line).
    pub fn more(value: impl Into<String>) -> Self {
        Self {
            label: String::new(),
            value: value.into(),
            dim: true,
            tail: String::new(),
        }
    }

    /// This row with a dim qualifier after its value.
    pub fn with_tail(mut self, tail: impl Into<String>) -> Self {
        self.tail = tail.into();
        self
    }
}

/// A labelled block after a blank line: `Next`, `Try this`, `Need help`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Section {
    pub label: String,
    pub lines: Vec<String>,
}

impl Section {
    pub fn new(label: impl Into<String>, lines: Vec<String>) -> Self {
        Self {
            label: label.into(),
            lines,
        }
    }
}

/// The whole card.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Card {
    pub verdict: Verdict,
    pub title: String,
    pub rows: Vec<Row>,
    pub sections: Vec<Section>,
    /// Dim lines under the card: `openlatch status` · `openlatch doctor`, the
    /// log path, the PATH hint.
    pub footer: Vec<String>,
}

/// How a value is drawn.
#[derive(Clone, Copy)]
enum Ink {
    /// A row's fact: bright white.
    Fact,
    /// A secondary row: dim.
    Dim,
    /// A section's sentence: the terminal's own foreground.
    Plain,
}

/// One line inside the card, before any border is drawn.
enum Line {
    Blank,
    Title,
    /// label, value, how the value is drawn, bold label, dim tail
    Field(String, String, Ink, bool, String),
}

/// Draw `card` for `caps`: a box in `Live`/`Append` mode, the same lines without
/// a border in `Plain` mode. Every line fits in 80 columns.
pub fn render(card: &Card, caps: &Caps) -> Vec<String> {
    render_with_warnings(card, &[], caps)
}

/// [`render`], with amber warning lines heading the footer: something off
/// and its remedy, `! Automatic updates: off · turn on: `openlatch config set
/// update.auto_update true``. What comes before the first ` · ` is amber, the
/// rest dim with its commands in the accent colour.
pub fn render_with_warnings(card: &Card, warnings: &[String], caps: &Caps) -> Vec<String> {
    let on = caps.color;
    let mut body = vec![Line::Blank, Line::Title, Line::Blank];
    // Fitted before wrapping: an ASCII `->` or `...` is wider than its glyph.
    let fit = |text: &str| fit_glyphs(text, caps);
    for row in &card.rows {
        let ink = if row.dim { Ink::Dim } else { Ink::Fact };
        push_field(
            &mut body,
            &row.label,
            &fit(&row.value),
            ink,
            false,
            &fit(&row.tail),
        );
    }
    for section in &card.sections {
        body.push(Line::Blank);
        for (i, line) in section.lines.iter().enumerate() {
            let label = if i == 0 { section.label.as_str() } else { "" };
            push_field(&mut body, label, &fit(line), Ink::Plain, true, "");
        }
    }
    body.push(Line::Blank);

    let draw = |line: &Line| -> String {
        match line {
            Line::Blank => String::new(),
            Line::Title => format!(
                " {}  {}",
                paint::bold(&card.verdict.paint(card.verdict.glyph(caps), on), on),
                paint::bold(&paint::white(&card.title, on), on)
            ),
            Line::Field(label, value, ink, strong, tail) => {
                let label = format!("{label:<LABEL$}");
                let label = if *strong {
                    paint::bold(&paint::white(&label, on), on)
                } else {
                    paint::dim(&label, on)
                };
                let value = fit_glyphs(value, caps);
                let value = match ink {
                    Ink::Fact => style_over(&value, on, paint::white),
                    Ink::Dim => style_over(&value, on, paint::dim),
                    Ink::Plain => style(&value, on),
                };
                let tail = if tail.is_empty() {
                    String::new()
                } else {
                    paint::dim(&format!(" {}", fit_glyphs(tail, caps)), on)
                };
                format!("{}{label}{value}{tail}", " ".repeat(INDENT))
            }
        }
    };

    let mut out = Vec::new();
    if caps.mode == Mode::Plain {
        // Drop the padding lines a border needs and a log does not.
        let inner = &body[1..body.len() - 1];
        out.extend(
            inner
                .iter()
                .map(|l| format!("  {}", draw(l)).trim_end().to_string()),
        );
    } else {
        let g = caps.glyphs();
        let edge = |l: &str, r: &str| {
            let rule = format!("{l}{}{r}", g.horizontal.repeat(INNER));
            format!("  {}", card.verdict.paint(&rule, on))
        };
        let side = card.verdict.paint(g.vertical, on);
        out.push(edge(g.top_left, g.top_right));
        for line in &body {
            let text = draw(line);
            let pad = INNER.saturating_sub(console::measure_text_width(&text));
            out.push(format!("  {side}{text}{}{side}", " ".repeat(pad)));
        }
        out.push(edge(g.bottom_left, g.bottom_right));
    }
    if !card.footer.is_empty() || !warnings.is_empty() {
        out.push(String::new());
    }
    out.extend(warnings.iter().map(|w| warn_line(w, caps)));
    out.extend(card.footer.iter().map(|f| {
        format!("  {}", style_over(&fit_glyphs(f, caps), on, paint::dim))
            .trim_end()
            .to_string()
    }));
    out
}

/// `  ! Automatic updates: off · turn on: openlatch config set …`: the glyph
/// bold amber, the words before the first ` · ` amber, the rest dim.
fn warn_line(text: &str, caps: &Caps) -> String {
    let on = caps.color;
    let (head, rest) = match text.split_once(" · ") {
        Some((head, rest)) => (head, format!(" · {rest}")),
        None => (text, String::new()),
    };
    format!(
        "  {} {}{}",
        paint::bold(&paint::amber(caps.glyphs().warn, on), on),
        style_over(&fit_glyphs(head, caps), on, paint::amber),
        style_over(&fit_glyphs(&rest, caps), on, paint::dim)
    )
    .trim_end()
    .to_string()
}

fn push_field(body: &mut Vec<Line>, label: &str, value: &str, ink: Ink, strong: bool, tail: &str) {
    let parts = wrap(value, VALUE);
    let last = parts.len() - 1;
    // The tail rides on the value's last line when it fits, else on its own.
    let fits = tail.is_empty()
        || console::measure_text_width(&parts[last].replace('`', "")) + 1 + tail.chars().count()
            <= VALUE;
    for (i, part) in parts.into_iter().enumerate() {
        let label = if i == 0 { label } else { "" };
        let with_tail = if i == last && fits { tail } else { "" };
        body.push(Line::Field(
            label.to_string(),
            part,
            ink,
            strong,
            with_tail.to_string(),
        ));
    }
    if !fits {
        body.push(Line::Field(
            String::new(),
            String::new(),
            Ink::Dim,
            false,
            tail.to_string(),
        ));
    }
}

/// The last line of a plain (no-TTY) run, for scripts and MDM logs to grep:
/// `result=live org="Acme Corp" agents=cline exit=0`.
///
/// Values with spaces, quotes or nothing in them are quoted. `NoAgent` adds
/// `reason=no-agent` so it is told apart from any other `attention`.
pub fn result_line(verdict: Verdict, exit_code: i32, fields: &[(&str, &str)]) -> String {
    let mut all = Vec::with_capacity(fields.len() + 1);
    if verdict == Verdict::NoAgent {
        all.push(("reason", "no-agent"));
    }
    all.extend_from_slice(fields);
    result_line_token(verdict.token(), exit_code, &all)
}

/// [`result_line`] for a command with its own vocabulary: `token` is written
/// as is (`result=updated from=0.5.7 to=0.5.8 exit=0`, see [`Update::token`]).
pub fn result_line_token(token: &str, exit_code: i32, fields: &[(&str, &str)]) -> String {
    let mut line = format!("result={token}");
    for (key, value) in fields {
        line.push(' ');
        line.push_str(key);
        line.push('=');
        if value.is_empty() || value.contains(|c: char| c.is_whitespace() || c == '"') {
            line.push('"');
            line.push_str(&value.replace('\\', "\\\\").replace('"', "\\\""));
            line.push('"');
        } else {
            line.push_str(value);
        }
    }
    line.push_str(&format!(" exit={exit_code}"));
    line
}

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

    fn live_card() -> Card {
        Card {
            verdict: Verdict::Live,
            title: "OpenLatch is live on this machine".into(),
            rows: vec![
                Row::new("Organization", "SuperAdmin"),
                Row::new("Agent", "Cline"),
                Row::more("actions controlled · model calls not observed"),
                Row::new("Policies", "in sync"),
            ],
            sections: vec![Section::new(
                "Next",
                vec![
                    "Keep using Cline as usual.".into(),
                    "See what they do at `https://app.openlatch.ai`".into(),
                ],
            )],
            footer: vec![
                "Check anytime `openlatch status`   ·   Full diagnostics `openlatch doctor`".into(),
            ],
        }
    }

    fn caps(mode: Mode, color: bool) -> Caps {
        Caps::new(mode, color, false, 80)
    }

    #[test]
    fn test_boxed_card_fits_80_columns_and_is_square() {
        for color in [false, true] {
            let lines = render(&live_card(), &caps(Mode::Live, color));
            let widths: Vec<usize> = lines
                .iter()
                .map(|l| console::measure_text_width(l))
                .collect();
            assert!(widths.iter().all(|w| *w <= 80), "{lines:#?}");
            // Every bordered line is exactly as wide as the top border; the
            // blank line and the footer follow the bottom border.
            let boxed = &widths[..widths.len() - 2];
            assert!(boxed.iter().all(|w| *w == boxed[0]), "{widths:?}");
        }
    }

    #[test]
    fn test_boxed_card_content() {
        let lines = render(&live_card(), &caps(Mode::Live, false));
        assert!(lines[0].starts_with("  ╭─"));
        assert!(lines[2].starts_with("  │ ✓  OpenLatch is live on this machine"));
        assert!(lines
            .iter()
            .any(|l| l.contains("    Organization   SuperAdmin")));
        assert!(lines
            .iter()
            .any(|l| l.contains("                   actions controlled")));
        assert!(lines
            .iter()
            .any(|l| l.contains("Next           Keep using")));
        assert!(
            lines.iter().all(|l| !l.contains('`')),
            "backticks are markup, never printed"
        );
        assert!(lines.last().unwrap().contains("openlatch doctor"));
    }

    #[test]
    fn test_colour_marks_commands_cyan_and_border_in_verdict_colour() {
        let lines = render(&live_card(), &caps(Mode::Live, true));
        assert!(lines[0].contains("\x1b[92m"), "green border for Live");
        assert!(lines
            .iter()
            .any(|l| l.contains("\x1b[4;36mhttps://app.openlatch.ai")));
        let red = Card {
            verdict: Verdict::NotLive,
            ..live_card()
        };
        let lines = render(&red, &caps(Mode::Live, true));
        assert!(lines[0].contains("\x1b[91m"));
        assert!(lines[2].contains('✗'));
    }

    /// The playground's boxCard, span for span: glyph in the verdict colour and
    /// bold, title bold bright white, labels dim, facts bright white, the
    /// coverage line and a row's tail dim, section labels bold bright white,
    /// commands and links in the accent colour, a blank line, then the footer's
    /// dim words around its commands.
    #[test]
    fn test_card_spans_match_the_playground() {
        let mut card = live_card();
        card.rows[3] =
            Row::new("Policies", "first sync in progress").with_tail("· applies on arrival");
        let lines = render(&card, &caps(Mode::Live, true));
        let g = "\x1b[92m";
        let side = format!("{g}│\x1b[0m");
        let find = |needle: &str| {
            lines
                .iter()
                .find(|l| l.contains(needle))
                .unwrap_or_else(|| panic!("{needle:?} in {lines:#?}"))
                .clone()
        };
        assert!(find("OpenLatch is live").starts_with(&format!(
            "  {side} \x1b[1m{g}✓\x1b[0m\x1b[22m  \x1b[1m\x1b[97mOpenLatch is live on this machine\x1b[0m\x1b[22m"
        )));
        assert!(find("SuperAdmin").starts_with(&format!(
            "  {side}    \x1b[90mOrganization   \x1b[0m\x1b[97mSuperAdmin\x1b[0m"
        )));
        assert!(find("actions controlled")
            .contains("\x1b[90mactions controlled · model calls not observed\x1b[0m"));
        assert!(find("first sync")
            .contains("\x1b[97mfirst sync in progress\x1b[0m\x1b[90m · applies on arrival\x1b[0m"));
        assert!(find("Keep using")
            .contains("\x1b[1m\x1b[97mNext           \x1b[0m\x1b[22mKeep using Cline as usual."));
        assert!(find("See what")
            .contains("See what they do at \x1b[4;36mhttps://app.openlatch.ai\x1b[0m"));
        let n = lines.len();
        assert_eq!(
            lines[n - 2],
            "",
            "a blank line between the card and its footer"
        );
        assert_eq!(
            lines[n - 1],
            "  \x1b[90mCheck anytime \x1b[0m\x1b[36mopenlatch status\x1b[0m\x1b[90m   ·   Full diagnostics \x1b[0m\x1b[36mopenlatch doctor\x1b[0m"
        );
    }

    #[test]
    fn test_ascii_box_on_append_mode() {
        let lines = render(&live_card(), &caps(Mode::Append, true));
        assert!(lines.iter().all(|l| l.is_ascii()), "{lines:#?}");
        assert!(lines.iter().all(|l| !l.contains('\x1b')));
        assert!(lines[0].starts_with("  +---"));
        assert!(lines[2].starts_with("  | +  OpenLatch is live"));
    }

    #[test]
    fn test_plain_card_has_no_border_and_no_trailing_space() {
        let lines = render(&live_card(), &caps(Mode::Plain, true));
        assert_eq!(lines[0], "   +  OpenLatch is live on this machine");
        assert!(lines.iter().all(|l| l.is_ascii()), "{lines:#?}");
        assert!(lines.iter().all(|l| !l.ends_with(' ')));
        assert!(lines.iter().all(|l| !l.contains('|')));
        assert!(lines.iter().any(|l| l == "      Organization   SuperAdmin"));
    }

    /// A value is fitted before it is wrapped: `→` and `…` widen in ASCII,
    /// and a row sized to the Unicode width must still stay in the box.
    #[test]
    fn test_ascii_glyphs_widen_before_wrapping() {
        let mut card = live_card();
        let value = format!("{} →→→…", "x".repeat(VALUE - 5));
        card.rows = vec![Row::new("Updated", value)];
        let lines = render(&card, &caps(Mode::Append, false));
        let widths: Vec<usize> = lines
            .iter()
            .map(|l| console::measure_text_width(l))
            .collect();
        let boxed = &widths[..widths.len() - 2];
        assert!(boxed.iter().all(|w| *w == boxed[0]), "{lines:#?}");
        assert!(lines.iter().any(|l| l.contains("->->->...")), "{lines:#?}");
        assert!(lines.iter().all(|l| l.is_ascii()));
    }

    #[test]
    fn test_long_values_wrap_inside_the_card() {
        let mut card = live_card();
        card.sections = vec![Section::new(
            "Try this",
            vec!["Run `openlatch init` again. If it fails twice, check that antivirus allows openlatch.exe to start and listen on loopback.".into()],
        )];
        let lines = render(&card, &caps(Mode::Live, false));
        assert!(lines.iter().all(|l| console::measure_text_width(l) <= 80));
        let body: Vec<_> = lines.iter().filter(|l| l.contains("antivirus")).collect();
        assert_eq!(body.len(), 1, "{lines:#?}");
        assert!(lines
            .iter()
            .any(|l| l.contains("Try this       Run openlatch init again.")));
    }

    /// Each update outcome: its token, tone, exit code and headline, as the
    /// playground has them, and the card glyph its tone draws.
    #[test]
    fn test_update_tokens() {
        let cases = [
            (
                Update::Updated,
                "updated",
                Verdict::Live,
                0,
                "OpenLatch 0.5.8 is running",
                "✓",
            ),
            (
                Update::UpToDate,
                "up_to_date",
                Verdict::Live,
                0,
                "OpenLatch 0.5.8 is up to date",
                "✓",
            ),
            (
                Update::Available,
                "available",
                Verdict::NeedsAttention,
                7,
                "0.5.8 is available",
                "!",
            ),
            (
                Update::Declined,
                "declined",
                Verdict::NeedsAttention,
                7,
                "Not updated · still on 0.5.7",
                "!",
            ),
            (
                Update::CheckFailed,
                "check_failed",
                Verdict::NeedsAttention,
                7,
                "Couldn't check for updates",
                "!",
            ),
            (
                Update::Failed,
                "failed",
                Verdict::NotLive,
                1,
                "Update stopped",
                "✗",
            ),
            (
                Update::RolledBack,
                "rolled_back",
                Verdict::NotLive,
                1,
                "0.5.8 didn't start, so 0.5.7 is back",
                "✗",
            ),
        ];
        for (update, token, verdict, exit, title, glyph) in cases {
            assert_eq!(update.token(), token);
            assert_eq!(update.verdict(), verdict);
            assert_eq!(update.exit_code(), exit);
            assert_eq!(update.title("0.5.7", "0.5.8"), title);
            let card = Card {
                verdict: update.verdict(),
                title: update.title("0.5.7", "0.5.8"),
                rows: vec![],
                sections: vec![],
                footer: vec![],
            };
            let lines = render(&card, &caps(Mode::Live, false));
            assert!(
                lines[2].starts_with(&format!("  │ {glyph}  {title}")),
                "{lines:#?}"
            );
            assert_eq!(
                result_line_token(update.token(), update.exit_code(), &[("to", "0.5.8")]),
                format!("result={token} to=0.5.8 exit={exit}")
            );
        }
    }

    /// The warning heads the footer: glyph bold amber, the words before the
    /// first ` · ` amber, the rest dim, the command in the accent colour.
    #[test]
    fn test_warning_footer_spans() {
        let warnings = vec![
            "Automatic updates: off · turn on: `openlatch config set update.auto_update true`"
                .to_string(),
        ];
        let lines = render_with_warnings(&live_card(), &warnings, &caps(Mode::Live, true));
        let n = lines.len();
        assert_eq!(lines[n - 3], "");
        assert_eq!(
            lines[n - 2],
            "  \x1b[1m\x1b[33m!\x1b[0m\x1b[22m \x1b[33mAutomatic updates: off\x1b[0m\
             \x1b[90m · turn on: \x1b[0m\x1b[36mopenlatch config set update.auto_update true\x1b[0m"
        );
        assert!(
            lines[n - 1].contains("openlatch doctor"),
            "the dim footer follows"
        );

        let hint =
            vec!["The background service isn't running · start it: `openlatch start`".to_string()];
        let card = Card {
            footer: vec![],
            ..live_card()
        };
        let lines = render_with_warnings(&card, &hint, &caps(Mode::Plain, false));
        let n = lines.len();
        assert_eq!(lines[n - 2], "");
        assert_eq!(
            lines[n - 1],
            "  ! The background service isn't running - start it: openlatch start"
        );
        let live = caps(Mode::Live, false);
        assert_eq!(
            render_with_warnings(&card, &[], &live),
            render(&card, &live)
        );
    }

    #[test]
    fn test_result_line() {
        assert_eq!(
            result_line(
                Verdict::Live,
                0,
                &[("org", "Acme Corp"), ("agents", "cline")]
            ),
            r#"result=live org="Acme Corp" agents=cline exit=0"#
        );
        assert_eq!(
            result_line(Verdict::NoAgent, 3, &[]),
            "result=attention reason=no-agent exit=3"
        );
        assert_eq!(
            result_line(
                Verdict::NotLive,
                1,
                &[("code", "OL-1502"), ("log", r#"C:\a "b""#)]
            ),
            r#"result=not_live code=OL-1502 log="C:\\a \"b\"" exit=1"#
        );
        assert_eq!(
            result_line(Verdict::NeedsAttention, 7, &[("org", "")]),
            r#"result=attention org="" exit=7"#
        );
    }
}