dirge-agent 0.11.3

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
//! Shared box / chamber rendering for tool chambers, permission
//! alerts, panel sections, and any future framed UI block.
//!
//! Three glyph sets in the wild before this module:
//!   - Tool chambers: `╭─ NAME ─ "value" ─╮` … `│ content │` …
//!     `╰─────╯`. Built incrementally — TOP at ToolCall, BODY rows
//!     as ToolResult streams, BOTTOM at chamber close. Each row
//!     produced by a separate function call (`chamber_row`,
//!     `chamber_row_with_bg`, `chamber_bottom`).
//!   - Permission alert: `╭─ ⚠ ALERT · PERMISSION ──╮` … `│ row │`
//!     … `├──┤` … `│ row │` … `╰──╯`. Built all at once via a
//!     local `row` closure in the alert handler.
//!   - Panel sections: `╭─ HEADER ────╮` … `│ item │` …
//!     `╰────╯`. Built all at once via a `push_section` closure in
//!     `build_panel_lines`.
//!
//! The three implementations re-derived chamber math (frame_w,
//! inner, padding, truncation) separately, used inconsistent
//! width-counting (chamber_row was display-width-aware while
//! chamber_row_with_bg was char-count-based), and treated tab
//! expansion / ANSI escapes differently.
//!
//! This module unifies the row-painting primitives. Callers that
//! build a box all-at-once use `BoxBuilder`; callers that build
//! incrementally (tool chambers across multiple events) use the
//! raw `row`, `top`, `bottom`, `divider` helpers.
//!
//! Not all helpers are wired into production callers yet —
//! individual `#[allow(dead_code)]` annotations mark the
//! deliberately-exported-but-not-yet-integrated surface.

use compact_str::CompactString;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use super::wrap;

/// Visual style for a framed box. Currently only one shape ships
/// (rounded corners), but the enum gives a hook for future styles
/// (double-line, ASCII-fallback for legacy terminals).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoxStyle {
    /// `╭─╮ │ │ ╰─╯` — rounded corners + light single-line
    /// borders. Used for tool chambers and inline alerts.
    Rounded,
    /// `╔═╗ ║ ║ ╚═╝` — double-line borders. Used for the
    /// outer UI panel frames (left AGENT STATUS, right
    /// SYSTEM & PROJECT DATA, bottom ALERT). Matches the
    /// mockup's framing.
    #[allow(dead_code)]
    Double,
}

impl BoxStyle {
    #[allow(dead_code)]
    pub fn top_left(self) -> char {
        match self {
            BoxStyle::Rounded => '',
            BoxStyle::Double => '',
        }
    }
    pub fn top_right(self) -> char {
        match self {
            BoxStyle::Rounded => '',
            BoxStyle::Double => '',
        }
    }
    pub fn bottom_left(self) -> char {
        match self {
            BoxStyle::Rounded => '',
            BoxStyle::Double => '',
        }
    }
    pub fn bottom_right(self) -> char {
        match self {
            BoxStyle::Rounded => '',
            BoxStyle::Double => '',
        }
    }
    pub fn horizontal(self) -> char {
        match self {
            BoxStyle::Rounded => '',
            BoxStyle::Double => '',
        }
    }
    pub fn vertical(self) -> char {
        match self {
            BoxStyle::Rounded => '',
            BoxStyle::Double => '',
        }
    }
    /// Left + right T-junctions used by divider rows inside a box.
    /// Double-style fallbacks to single-line tees because the
    /// double-tee glyphs (╠ ╣) read as heavier than the rest of
    /// the panel.
    pub fn tee_left(self) -> char {
        match self {
            BoxStyle::Rounded => '',
            BoxStyle::Double => '',
        }
    }
    pub fn tee_right(self) -> char {
        match self {
            BoxStyle::Rounded => '',
            BoxStyle::Double => '',
        }
    }
}

/// Build a `╭─ <title> ─<dashes>─╮` top border. `title` renders
/// flush against the left corner with one cell of dash padding on
/// each side; remaining width fills with horizontal dashes.
/// Width math is display-aware so wide title glyphs don't push the
/// right corner off.
#[allow(dead_code)]
pub fn top(style: BoxStyle, title: &str, total_w: usize) -> String {
    // Review #10: empty title would otherwise render as
    // `╭─  ─{fill}─╮` (two spaces with no glyph between). Match
    // the bottom-border shape (`╭{horizontals}╮`) instead.
    if title.is_empty() {
        let inner = total_w.saturating_sub(2);
        return format!(
            "{}{}{}",
            style.top_left(),
            style.horizontal().to_string().repeat(inner),
            style.top_right(),
        );
    }
    let hch = style.horizontal();
    let hstr = hch.to_string();
    // ui-redesign: double-style frames put the title centered in
    // the top border surrounded by `[...]` brackets — matches the
    // mockup look. Rounded keeps the legacy `─ TITLE ─` shape so
    // tool chambers / alert frames don't suddenly look different.
    match style {
        BoxStyle::Double => {
            // Layout: `╔═══[TITLE]═══╗` with title centered.
            // Overhead = 2 corners + 2 brackets = 4 cells.
            let bracketed = format!("[{title}]");
            let bracketed_w = UnicodeWidthStr::width(bracketed.as_str());
            let fill = total_w.saturating_sub(2).saturating_sub(bracketed_w);
            let left = fill / 2;
            let right = fill - left;
            format!(
                "{}{}{}{}{}",
                style.top_left(),
                hstr.repeat(left),
                bracketed,
                hstr.repeat(right),
                style.top_right(),
            )
        }
        BoxStyle::Rounded => {
            // Legacy: `╭─ TITLE ─────╮` — left-anchored, single-
            // line shape. Tool chambers + inline alerts use this.
            // Layout: corner + hch + ' ' + title + ' ' + hch + fill
            //         + hch + corner = 7 fixed + title + fill cells.
            let title_w = UnicodeWidthStr::width(title);
            const OVERHEAD: usize = 7;
            let fill = total_w.saturating_sub(OVERHEAD).saturating_sub(title_w);
            format!(
                "{}{} {} {}{}{}{}",
                style.top_left(),
                hstr,
                title,
                hstr,
                hstr.repeat(fill),
                hstr,
                style.top_right(),
            )
        }
    }
}

/// Build a `╰─────╯` bottom border sized to `total_w`.
pub fn bottom(style: BoxStyle, total_w: usize) -> String {
    let inner = total_w.saturating_sub(2); // corners
    format!(
        "{}{}{}",
        style.bottom_left(),
        style.horizontal().to_string().repeat(inner),
        style.bottom_right(),
    )
}

/// Build a `├─────┤` divider row sized to `total_w`. Used inside
/// boxes that have multiple sections (e.g. the permission alert
/// separates the question and action rows with a divider).
#[allow(dead_code)]
pub fn divider(style: BoxStyle, total_w: usize) -> String {
    let inner = total_w.saturating_sub(2);
    format!(
        "{}{}{}",
        style.tee_left(),
        style.horizontal().to_string().repeat(inner),
        style.tee_right(),
    )
}

/// Build a `│ content {pad} │` content row sized so the right
/// border lands at column `total_w`. `total_w` is the EXTERNAL
/// width (border-to-border). Content width is `total_w - 4` —
/// two cells for each border + space.
///
/// Long content is truncated with `…`. Tabs are expanded to
/// `tab_stop` spaces beforehand so chamber rows stay aligned
/// regardless of where the tab fell. Width is display-aware so
/// wide glyphs don't drift the right border.
///
/// Callers that need their content soft-wrapped across multiple
/// rows should use `wrap::soft_wrap` themselves to chunk the input
/// and call `row` once per chunk.
pub fn row(style: BoxStyle, content: &str, total_w: usize) -> String {
    let inner = total_w.saturating_sub(4);
    let expanded = expand_tabs(content, 4);
    let total_visible = UnicodeWidthStr::width(expanded.as_str());

    let (trimmed, trimmed_w): (String, usize) = if total_visible <= inner {
        (expanded.clone(), total_visible)
    } else if inner == 0 {
        (String::new(), 0)
    } else {
        // Reserve 1 cell for `…`; pull chars from the start until
        // we'd overflow the remaining budget.
        let budget = inner.saturating_sub(1);
        let mut out = String::with_capacity(expanded.len());
        let mut used = 0;
        for ch in expanded.chars() {
            let w = ch.width().unwrap_or(0);
            if used + w > budget {
                break;
            }
            out.push(ch);
            used += w;
        }
        out.push('');
        (out, used + 1)
    };
    let pad = inner.saturating_sub(trimmed_w);
    format!(
        "{} {}{} {}",
        style.vertical(),
        trimmed,
        " ".repeat(pad),
        style.vertical(),
    )
}

/// Same as `row` but wraps content with a 256-color background
/// inside the borders. Used by diff `+`/`-` rows where the BG
/// signals add/remove. Border glyphs sit OUTSIDE the bg span so
/// they keep the chamber color.
pub fn row_with_bg(style: BoxStyle, content: &str, total_w: usize, bg_idx: u8) -> String {
    // Review #3: refactor previously left `row_with_bg` on
    // char-count math while `row` was switched to display-width.
    // For CJK / emoji content in a diff (`+ 中文测试`), the right
    // border drifted by N cells per wide glyph. Mirror `row`'s
    // exact display-width budget so diff rows align with the
    // plain rows in the same chamber.
    let inner = total_w.saturating_sub(4);
    let expanded = expand_tabs(content, 4);
    let total_visible = UnicodeWidthStr::width(expanded.as_str());

    let (trimmed, trimmed_w): (String, usize) = if total_visible <= inner {
        (expanded.clone(), total_visible)
    } else if inner == 0 {
        (String::new(), 0)
    } else {
        let budget = inner.saturating_sub(1);
        let mut out = String::with_capacity(expanded.len());
        let mut used = 0;
        for ch in expanded.chars() {
            let w = ch.width().unwrap_or(0);
            if used + w > budget {
                break;
            }
            out.push(ch);
            used += w;
        }
        out.push('');
        (out, used + 1)
    };
    let pad = inner.saturating_sub(trimmed_w);
    // dirge-ufkp: honour `--no-color`. These diff +/- background escapes
    // are baked straight into the line (write_line stores it verbatim),
    // so they bypass the `theme::*()` accessors the no-color chokepoint
    // collapses. Gate them on the same flag so a no-color terminal sees a
    // plain padded row instead of green/red blocks.
    let (bg_open, bg_close) = diff_bg_escapes(bg_idx, crate::ui::theme::no_color());
    format!(
        "{} {}{}{}{} {}",
        style.vertical(),
        bg_open,
        trimmed,
        " ".repeat(pad),
        bg_close,
        style.vertical(),
    )
}

/// The `(open, close)` SGR background escapes for a diff `+`/`-` row, or
/// empty strings under `--no-color`. Pure (takes the flag as a param) so
/// it's testable without the set-once `NO_COLOR` global. dirge-ufkp.
fn diff_bg_escapes(bg_idx: u8, no_color: bool) -> (String, String) {
    if no_color {
        (String::new(), String::new())
    } else {
        (format!("\x1b[48;5;{bg_idx}m"), String::from("\x1b[49m"))
    }
}

/// Expand `\t` to spaces honouring a fixed tab stop. Walks the
/// string tracking column position so a tab N cells before the
/// next stop expands to exactly `stop - (col % stop)` spaces.
/// Display-width-aware: a wide glyph advances col by 2.
///
/// Precondition: input should be free of CONTROL characters
/// (ESC, CR, etc.) — controls have display width 0, so they
/// don't advance the column counter, and a tab placed after a
/// control byte will mis-align relative to the visible cursor
/// position. Callers should pass output through
/// `ansi::strip_controls` first.
pub fn expand_tabs(s: &str, tab_stop: usize) -> String {
    if !s.contains('\t') {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len() + 8);
    let mut col = 0usize;
    for ch in s.chars() {
        if ch == '\t' {
            let pad = tab_stop - (col % tab_stop);
            for _ in 0..pad {
                out.push(' ');
            }
            col += pad;
        } else {
            out.push(ch);
            col += ch.width().unwrap_or(0);
        }
    }
    out
}

// === Builder ===
//
// Convenience for callers that build a complete box in one go
// (alerts, panel sections, notifications). Construct, push rows
// (optionally with dividers), finalize to a Vec<String> the
// caller paints in order.

#[allow(dead_code)]
pub struct BoxBuilder {
    style: BoxStyle,
    width: usize,
    title: String,
    rows: Vec<RowKind>,
}

#[allow(dead_code)]
enum RowKind {
    Text(CompactString),
    Divider,
}

impl BoxBuilder {
    /// Start a new box. `width` is the external width
    /// (border-to-border). `title` renders in the top border.
    #[allow(dead_code)]
    pub fn new(style: BoxStyle, title: impl Into<String>, width: usize) -> Self {
        Self {
            style,
            width: width.max(8),
            title: title.into(),
            rows: Vec::new(),
        }
    }

    /// Push a content row. Behavior:
    /// - Empty input emits a single blank row (vertical padding).
    /// - Embedded `\n` splits into multiple logical rows (review
    ///   #12 — otherwise a multi-line input went through `row()`
    ///   as one chunk with a literal `\n`, which `write_line` then
    ///   split and broke the chamber border).
    /// - Each logical row that exceeds inner width soft-wraps via
    ///   `wrap::soft_wrap` with no continuation indent. Callers
    ///   needing label-aligned wrapped tails should use
    ///   `row_labelled` instead (review #13).
    #[allow(dead_code)]
    pub fn row(mut self, content: impl AsRef<str>) -> Self {
        let inner = self.width.saturating_sub(4);
        let s = content.as_ref();
        if s.is_empty() {
            self.rows.push(RowKind::Text(CompactString::new("")));
            return self;
        }
        for logical in s.split('\n') {
            if logical.is_empty() {
                self.rows.push(RowKind::Text(CompactString::new("")));
                continue;
            }
            for chunk in wrap::soft_wrap(logical, inner, "") {
                self.rows.push(RowKind::Text(CompactString::from(chunk)));
            }
        }
        self
    }

    /// Push a `<label><sep><value>` row where wrapped tails of
    /// long values indent under the value column rather than
    /// hugging the left border. Mirrors the alert chamber's
    /// `labelled_rows` shape so a future alert refactor can use
    /// `BoxBuilder` directly. The continuation indent's width is
    /// the display-width of `label + sep`.
    #[allow(dead_code)]
    pub fn row_labelled(mut self, label: &str, sep: &str, value: &str) -> Self {
        let inner = self.width.saturating_sub(4);
        let prefix = format!("{label}{sep}");
        let prefix_w = UnicodeWidthStr::width(prefix.as_str());
        let cont_indent: String = " ".repeat(prefix_w);
        let combined = format!("{prefix}{value}");
        for chunk in wrap::soft_wrap(&combined, inner, &cont_indent) {
            self.rows.push(RowKind::Text(CompactString::from(chunk)));
        }
        self
    }

    /// Push a horizontal divider (`├──┤`) between rows.
    #[allow(dead_code)]
    pub fn divider(mut self) -> Self {
        self.rows.push(RowKind::Divider);
        self
    }

    /// Finalise to a Vec<String> ready to paint top-to-bottom.
    #[allow(dead_code)]
    pub fn build(self) -> Vec<String> {
        let mut out: Vec<String> = Vec::with_capacity(self.rows.len() + 2);
        out.push(top(self.style, &self.title, self.width));
        for rk in self.rows {
            match rk {
                RowKind::Text(s) => out.push(row(self.style, &s, self.width)),
                RowKind::Divider => out.push(divider(self.style, self.width)),
            }
        }
        out.push(bottom(self.style, self.width));
        out
    }
}

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

    /// dirge-ufkp: diff backgrounds are emitted normally, but suppressed
    /// entirely under `--no-color` (no stray `48;5;` / `49` escapes).
    #[test]
    fn diff_bg_escapes_respect_no_color() {
        let (open, close) = diff_bg_escapes(22, false);
        assert_eq!(open, "\x1b[48;5;22m");
        assert_eq!(close, "\x1b[49m");

        let (open, close) = diff_bg_escapes(22, true);
        assert!(open.is_empty(), "no-color must drop the bg-open escape");
        assert!(close.is_empty(), "no-color must drop the bg-close escape");

        // And the row built under no-color carries no SGR escapes at all.
        let row_no_color = {
            // Build the row body the way row_with_bg does, but with the
            // no-color escapes — assert no ESC bytes leak through.
            let (o, c) = diff_bg_escapes(52, true);
            format!("{o}+ added{c}")
        };
        assert!(
            !row_no_color.contains('\x1b'),
            "no escapes under no-color: {row_no_color:?}"
        );
    }

    /// Top, bottom, and divider all hit the requested external width.
    #[test]
    fn frame_helpers_match_total_width() {
        for w in [12, 60, 120usize] {
            let t = top(BoxStyle::Rounded, "TEST", w);
            let b = bottom(BoxStyle::Rounded, w);
            let d = divider(BoxStyle::Rounded, w);
            assert_eq!(UnicodeWidthStr::width(t.as_str()), w, "top width@{w}");
            assert_eq!(UnicodeWidthStr::width(b.as_str()), w, "bottom width@{w}");
            assert_eq!(UnicodeWidthStr::width(d.as_str()), w, "divider width@{w}");
        }
    }

    /// Content rows match total_w independent of input content
    /// (short, exact, overflowing).
    #[test]
    fn row_width_invariant() {
        let w = 30;
        for input in &["short", "exactlyfittingrow", &"x".repeat(100)] {
            let r = row(BoxStyle::Rounded, input, w);
            assert_eq!(UnicodeWidthStr::width(r.as_str()), w, "row({input:?})@{w}");
        }
    }

    /// Tabs expand BEFORE width measurement so the right border
    /// doesn't drift.
    #[test]
    fn row_handles_tabs() {
        let w = 40;
        let r = row(BoxStyle::Rounded, "a\tb", w);
        assert_eq!(UnicodeWidthStr::width(r.as_str()), w);
        assert!(!r.contains('\t'));
    }

    /// CJK glyphs count as width-2.
    #[test]
    fn row_handles_cjk() {
        let w = 30;
        let r = row(BoxStyle::Rounded, "中文测试", w);
        assert_eq!(UnicodeWidthStr::width(r.as_str()), w);
    }

    /// Builder produces a sequence: top, then rows in order, then
    /// bottom. Every output line hits the requested width.
    #[test]
    fn builder_produces_well_formed_box() {
        let out = BoxBuilder::new(BoxStyle::Rounded, "TITLE", 40)
            .row("first line")
            .row("second line")
            .divider()
            .row("after divider")
            .build();
        assert!(out.len() >= 5);
        // First is top border, last is bottom border.
        assert!(out[0].starts_with(''));
        assert!(out.last().unwrap().starts_with(''));
        // All rows the same external width.
        for line in &out {
            assert_eq!(UnicodeWidthStr::width(line.as_str()), 40);
        }
    }

    /// A row longer than the inner width wraps across multiple
    /// rows rather than truncating with `…`.
    #[test]
    fn builder_soft_wraps_long_rows() {
        let long = "the quick brown fox jumps over the lazy dog repeatedly";
        let out = BoxBuilder::new(BoxStyle::Rounded, "T", 30)
            .row(long)
            .build();
        // Top + N wrapped rows + bottom; N ≥ 2 for this length.
        let content_rows = out.len() - 2;
        assert!(content_rows >= 2, "expected wrap, got {content_rows} rows");
        // None of the rows truncated with `…`.
        for line in &out[1..out.len() - 1] {
            assert!(!line.contains(''), "row truncated unexpectedly: {line}");
        }
    }

    /// `expand_tabs` honours mixed content + tab stop alignment.
    #[test]
    fn expand_tabs_aligned_to_stop() {
        assert_eq!(expand_tabs("a\tb", 4), "a   b");
        assert_eq!(expand_tabs("ab\tc", 4), "ab  c");
        assert_eq!(expand_tabs("abc\td", 4), "abc d");
        assert_eq!(expand_tabs("abcd\te", 4), "abcd    e");
    }

    /// Review #3: `row_with_bg` must be display-width-aware so a
    /// diff row containing CJK / emoji doesn't drift the right
    /// border relative to plain `row`s in the same chamber.
    #[test]
    fn row_with_bg_width_invariant() {
        let w = 30;
        for input in &["+ added", "- 中文测试", "+\tindented", "- 🚀"] {
            let r = row_with_bg(BoxStyle::Rounded, input, w, 22);
            // visible width = SGR-skipping width
            let visible = super::super::wrap::visible_width(&r);
            assert_eq!(visible, w, "row_with_bg({input:?})@{w}");
        }
    }

    /// Review #10: empty title produces a borderless top
    /// `╭{horizontals}╮`, matching the bottom-border shape.
    #[test]
    fn top_empty_title_omits_title_slot() {
        let w = 20;
        let t = top(BoxStyle::Rounded, "", w);
        assert_eq!(UnicodeWidthStr::width(t.as_str()), w);
        assert!(t.starts_with(''));
        assert!(t.ends_with(''));
        // No literal spaces inside — pure dash run.
        assert!(!t.contains(' '));
    }

    /// Review #12: `BoxBuilder::row` with embedded `\n` produces
    /// multiple framed rows instead of a single row containing
    /// a literal `\n` that breaks the chamber border downstream.
    #[test]
    fn builder_splits_embedded_newlines() {
        let out = BoxBuilder::new(BoxStyle::Rounded, "T", 30)
            .row("first\nsecond\nthird")
            .build();
        // Top + 3 content rows + bottom = 5 lines minimum.
        assert!(out.len() >= 5, "got {} rows", out.len());
        // No row carries a `\n`.
        for line in &out {
            assert!(!line.contains('\n'), "row leaked newline: {line:?}");
        }
        // The 3 content rows contain the expected text.
        let body: Vec<&String> = out[1..out.len() - 1].iter().collect();
        assert!(body.iter().any(|l| l.contains("first")));
        assert!(body.iter().any(|l| l.contains("second")));
        assert!(body.iter().any(|l| l.contains("third")));
    }

    /// Review #13: `BoxBuilder::row_labelled` indents continuation
    /// rows under the value column rather than flush-left.
    #[test]
    fn builder_row_labelled_indents_continuation() {
        let out = BoxBuilder::new(BoxStyle::Rounded, "T", 40)
            .row_labelled("args", ": ", &"x".repeat(80))
            .build();
        // First content row starts with `args: `; later rows
        // start with 6 spaces (`args: ` width).
        let body: Vec<&String> = out[1..out.len() - 1].iter().collect();
        assert!(body.len() >= 2);
        assert!(body[0].contains("args: "), "first row: {:?}", body[0]);
        // Continuation rows after the first should contain a
        // run of 6 spaces immediately after the left border.
        for cont in &body[1..] {
            // Skip the leading `│ ` (border + space), look for
            // 6 spaces indent.
            let after_border = cont.split_once("").map(|(_, r)| r).unwrap_or(cont);
            assert!(
                after_border.starts_with("      "),
                "continuation row missing indent: {cont:?}",
            );
        }
    }
}