seer-core 0.52.3

Core library for Seer domain name utilities
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use super::*;
use crate::output::diff_table::{build_diff_sections, DiffSection, EMPTY_PLACEHOLDER};

impl HumanFormatter {
    pub(super) fn format_diff(&self, diff: &crate::diff::DomainDiff) -> String {
        let mut output = Vec::new();

        // The column headers are aligned cells too, so one line each.
        let domain_a = sanitize_line(&diff.domain_a);
        let domain_b = sanitize_line(&diff.domain_b);
        output.push(self.header(&format!("Diff: {domain_a} vs {domain_b}")));

        let sections = build_diff_sections(diff);
        let col_width = compute_column_width(&sections, &domain_a, &domain_b);

        // Label gutter width: max of all field labels (not section titles).
        let label_width = sections
            .iter()
            .flat_map(|s| s.rows.iter().map(|r| r.label.chars().count()))
            .max()
            .unwrap_or(0);

        // Indents and gutters
        let label_indent = "    "; // 4 spaces inside section
        let section_indent = "  "; // 2 spaces before section title
        let marker_gutter_width = 2; // "= " or "≠ "
                                     // Between label cell and marker: 2 spaces (inter-column gap).
                                     // Marker cell: "= " or "≠ " = 2 chars.
                                     // Total left pad before value column A = label_indent + label_width + 2 + 2.
        let header_left_pad = label_indent.chars().count() + label_width + 2 + marker_gutter_width;

        // Column header block. Data cells wrap to `col_width` (capped at
        // DIFF_COLUMN_CAP), so the header domain names must be elided to the
        // same width or a domain longer than the cap drifts the header out of
        // alignment with the body (and its rule). Elide (single-line) rather
        // than wrap to keep the header one row tall.
        let header_a = elide_to(&domain_a, col_width);
        let header_b = elide_to(&domain_b, col_width);
        let header_line = format!(
            "{}{}   {}",
            " ".repeat(header_left_pad),
            self.label(&format!("{header_a:<col_width$}")),
            self.label(&header_b)
        );
        // Rules match the rendered (elided) header cell widths, never the raw
        // domain length.
        let rule_a: String = "─".repeat(header_a.chars().count());
        let rule_b: String = "─".repeat(header_b.chars().count());
        let rule_line = format!(
            "{}{}   {}",
            " ".repeat(header_left_pad),
            self.label(&format!("{rule_a:<col_width$}")),
            self.label(&rule_b)
        );
        output.push(String::new());
        output.push(header_line);
        output.push(rule_line);

        for section in &sections {
            output.push(String::new());
            output.push(format!("{}{}", section_indent, self.label(section.title)));

            for row in &section.rows {
                // Wrap each value column independently.
                let wrap = |values: &[String]| -> Vec<String> {
                    values
                        .iter()
                        .flat_map(|v| wrap_cell(v, col_width))
                        .collect()
                };
                let mut a_lines = wrap(&row.a_values);
                let mut b_lines = wrap(&row.b_values);

                // Pad the shorter list with blank lines so rows align.
                let rows_needed = a_lines.len().max(b_lines.len()).max(1);
                a_lines.resize(rows_needed, String::new());
                b_lines.resize(rows_needed, String::new());

                let marker_glyph = if row.matches { "=" } else { "≠" };
                let color = |s: &str| -> String {
                    if row.matches {
                        self.success(s)
                    } else {
                        self.error(s)
                    }
                };

                for (i, (a, b)) in a_lines.iter().zip(b_lines.iter()).enumerate() {
                    let label = if i == 0 { row.label } else { "" };
                    let label_cell = format!("{label_indent}{label:<label_width$}");
                    let marker_cell = if i == 0 {
                        format!("{} ", color(marker_glyph))
                    } else {
                        "  ".to_string()
                    };
                    let color_value = |s: &str, raw: &str| -> String {
                        if raw.trim() == EMPTY_PLACEHOLDER {
                            self.dim(s)
                        } else {
                            color(s)
                        }
                    };
                    let a_cell = color_value(&format!("{a:<col_width$}"), a);
                    let b_cell = color_value(b, b);
                    output.push(format!(
                        "{}  {}{}   {}",
                        self.label(&label_cell),
                        marker_cell,
                        a_cell,
                        b_cell
                    ));
                }
            }
        }

        // Failed checks: their rows above are empty, not real answers.
        if !diff.errors.is_empty() {
            output.push(String::new());
            for error in &diff.errors {
                output.push(format!("  {} {}", self.warning("!"), sanitize_line(error)));
            }
        }

        output.join("\n")
    }
}

/// Wraps remote `text` into lines no wider than `max_width` display chars.
/// Breaks at the last whitespace within the window when possible; otherwise
/// hard-breaks at the cap. Widths are measured in `chars().count()`, which is
/// correct for ASCII and a reasonable fallback for other inputs. The text
/// goes through [`sanitize_line`] first, so every returned line is a single
/// physical row: a raw newline would break the row (the pad math counts it
/// as one column) and let a remote party forge extra, aligned rows.
fn wrap_cell(text: &str, max_width: usize) -> Vec<String> {
    let width = max_width.max(1);
    let text = sanitize_line(text);
    let chars: Vec<char> = text.chars().collect();
    if chars.len() <= width {
        return vec![text];
    }

    let mut out = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        let remaining = chars.len() - i;
        if remaining <= width {
            out.push(chars[i..].iter().collect());
            break;
        }
        // Search for last whitespace in chars[i .. i+width]
        let window_end = i + width;
        let break_at = (i..window_end).rev().find(|&k| chars[k].is_whitespace());
        match break_at {
            Some(k) if k > i => {
                out.push(chars[i..k].iter().collect());
                i = k + 1; // skip the whitespace itself
            }
            _ => {
                // No whitespace in window (or whitespace at index i): hard break.
                out.push(chars[i..window_end].iter().collect());
                i = window_end;
            }
        }
    }

    out
}

/// Hard cap on a single value column (applies before wrapping).
const DIFF_COLUMN_CAP: usize = 40;

/// Computes the shared width for both value columns: the widest item across
/// every row of every section plus the two domain-header lengths, capped at
/// `DIFF_COLUMN_CAP`.
fn compute_column_width(sections: &[DiffSection], domain_a: &str, domain_b: &str) -> usize {
    let mut widest = domain_a.chars().count().max(domain_b.chars().count());
    for section in sections {
        for row in &section.rows {
            for v in row.a_values.iter().chain(row.b_values.iter()) {
                widest = widest.max(v.chars().count());
            }
        }
    }
    widest.clamp(1, DIFF_COLUMN_CAP)
}

/// Elides `text` to at most `width` display chars, appending a single-char
/// ellipsis (`…`) when truncation occurs so the result is exactly `width` chars.
/// Char-boundary-safe (operates on `chars()`, never byte indices). A `width` of
/// 0 yields an empty string; a `width` of 1 yields just the ellipsis when
/// truncating.
fn elide_to(text: &str, width: usize) -> String {
    let chars: Vec<char> = text.chars().collect();
    if chars.len() <= width {
        return text.to_string();
    }
    if width == 0 {
        return String::new();
    }
    // Keep width-1 chars and add the ellipsis to land on exactly `width`.
    let keep = width - 1;
    let mut out: String = chars[..keep].iter().collect();
    out.push('…');
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::{DnsDiff, DomainDiff, RegistrationDiff, SslDiff};
    use crate::output::diff_table::tests::make_sample_diff;
    use crate::output::diff_table::DiffRow;

    #[test]
    fn wrap_cell_short_returns_single_line() {
        assert_eq!(wrap_cell("hello", 10), vec!["hello".to_string()]);
    }

    #[test]
    fn wrap_cell_wraps_at_word_boundary() {
        let out = wrap_cell("the quick brown fox", 10);
        assert_eq!(out, vec!["the quick".to_string(), "brown fox".to_string()]);
    }

    #[test]
    fn wrap_cell_hard_breaks_when_no_whitespace() {
        // A long nameserver with no break points must hard-break at the cap.
        let out = wrap_cell("a.very.long.nameserver.example", 10);
        assert_eq!(
            out,
            vec![
                "a.very.lon".to_string(),
                "g.nameserv".to_string(),
                "er.example".to_string(),
            ]
        );
    }

    #[test]
    fn wrap_cell_exact_width_no_wrap() {
        assert_eq!(wrap_cell("1234567890", 10), vec!["1234567890".to_string()]);
    }

    #[test]
    fn wrap_cell_empty_input_returns_one_empty_line() {
        assert_eq!(wrap_cell("", 10), vec!["".to_string()]);
    }

    #[test]
    fn wrap_cell_zero_width_treated_as_one() {
        // Defensive: never loop forever on width 0. Caller must not pass 0, but
        // we clamp to 1 to be safe.
        let out = wrap_cell("abc", 0);
        assert_eq!(out, vec!["a".to_string(), "b".to_string(), "c".to_string()]);
    }

    #[test]
    fn wrap_cell_flattens_newline_cr_tab() {
        // Inside an aligned cell a newline or tab must not survive, or a
        // value breaks its row / forges new ones (a bare CR is dropped).
        assert_eq!(wrap_cell("a\nb\tc\rd", 40), vec!["a b cd".to_string()]);
        for line in wrap_cell("x\ny\nz", 3) {
            assert!(!line.contains(['\n', '\r', '\t']), "{line:?}");
        }
    }

    #[test]
    fn format_diff_cell_newline_cannot_forge_rows() {
        // A remote registrar value carrying a newline plus a fake, aligned
        // row must stay on its own row inside the value column.
        let mut diff = make_sample_diff();
        diff.registration.registrar = (
            Some("IANA\n    Organization  =  Forged".to_string()),
            Some("MarkMonitor".to_string()),
        );
        let out = diff_formatter().format_diff(&diff);
        let org_rows = out
            .lines()
            .filter(|l| l.trim_start().starts_with("Organization"))
            .count();
        assert_eq!(org_rows, 1, "forged row appeared:\n{out}");
        assert!(!out.contains('\t'), "tab leaked:\n{out}");
    }

    #[test]
    fn compute_column_width_uses_widest_value_across_sections() {
        let sections = vec![DiffSection {
            title: "Registration",
            rows: vec![
                DiffRow {
                    label: "Registrar",
                    a_values: vec!["IANA".to_string()],
                    b_values: vec!["MarkMonitor".to_string()],
                    matches: false,
                    list: false,
                },
                DiffRow {
                    label: "Organization",
                    a_values: vec!["—".to_string()],
                    b_values: vec!["Google LLC".to_string()],
                    matches: false,
                    list: false,
                },
            ],
        }];
        // Widest item is "MarkMonitor" (11).
        assert_eq!(compute_column_width(&sections, "a.com", "b.com"), 11);
    }

    #[test]
    fn compute_column_width_respects_domain_width() {
        let sections = vec![DiffSection {
            title: "Registration",
            rows: vec![DiffRow {
                label: "Registrar",
                a_values: vec!["x".to_string()],
                b_values: vec!["y".to_string()],
                matches: false,
                list: false,
            }],
        }];
        // Domain "very-long-domain.example" is wider than any value.
        let w = compute_column_width(&sections, "very-long-domain.example", "b.com");
        assert_eq!(w, "very-long-domain.example".chars().count());
    }

    #[test]
    fn compute_column_width_caps_at_40() {
        let long_value = "x".repeat(100);
        let sections = vec![DiffSection {
            title: "Registration",
            rows: vec![DiffRow {
                label: "Registrar",
                a_values: vec![long_value],
                b_values: vec!["y".to_string()],
                matches: false,
                list: false,
            }],
        }];
        assert_eq!(compute_column_width(&sections, "a.com", "b.com"), 40);
    }

    #[test]
    fn compute_column_width_minimum_sensible_default() {
        // Even with tiny inputs, width should not be zero.
        let sections = vec![DiffSection {
            title: "Registration",
            rows: vec![DiffRow {
                label: "X",
                a_values: vec!["a".to_string()],
                b_values: vec!["b".to_string()],
                matches: true,
                list: false,
            }],
        }];
        let w = compute_column_width(&sections, "a", "b");
        assert!(w >= 1);
    }

    fn diff_formatter() -> HumanFormatter {
        HumanFormatter::new().without_colors()
    }

    #[test]
    fn format_diff_shows_column_headers_with_domain_names() {
        let f = diff_formatter();
        let out = f.format_diff(&make_sample_diff());
        assert!(
            out.contains("example.com"),
            "missing domain_a in output:\n{}",
            out
        );
        assert!(
            out.contains("google.com"),
            "missing domain_b in output:\n{}",
            out
        );
        // A row indicating the header underline (Unicode box-drawing dash).
        assert!(out.contains("──"), "missing header underline:\n{}", out);
    }

    #[test]
    fn format_diff_marks_differing_rows_with_neq() {
        let f = diff_formatter();
        let out = f.format_diff(&make_sample_diff());
        // Registrar differs: IANA vs MarkMonitor.
        let registrar_line = out
            .lines()
            .find(|l| l.contains("Registrar"))
            .expect("registrar line missing");
        assert!(
            registrar_line.contains("≠"),
            "registrar row should be marked differ: {}",
            registrar_line
        );
    }

    #[test]
    fn format_diff_marks_matching_rows_with_eq() {
        let f = diff_formatter();
        let out = f.format_diff(&make_sample_diff());
        // Resolves matches (both true).
        let resolves_line = out
            .lines()
            .find(|l| l.contains("Resolves"))
            .expect("resolves line missing");
        assert!(
            resolves_line.contains('='),
            "resolves row should be marked match: {}",
            resolves_line
        );
        assert!(!resolves_line.contains('≠'));
    }

    #[test]
    fn format_diff_nameservers_reversed_order_is_match() {
        // make_sample_diff has reversed nameservers.
        let f = diff_formatter();
        let out = f.format_diff(&make_sample_diff());
        let ns_line = out
            .lines()
            .find(|l| l.contains("Nameservers"))
            .expect("nameservers line missing");
        assert!(
            ns_line.contains('=') && !ns_line.contains('≠'),
            "nameservers row should match (set equality): {}",
            ns_line
        );
    }

    #[test]
    fn format_diff_organization_none_renders_em_dash() {
        let f = diff_formatter();
        let out = f.format_diff(&make_sample_diff());
        let org_line = out
            .lines()
            .find(|l| l.contains("Organization"))
            .expect("organization line missing");
        assert!(org_line.contains("—"), "expected em dash: {}", org_line);
    }

    #[test]
    fn format_diff_multi_value_a_records_one_per_line() {
        let mut diff = make_sample_diff();
        diff.dns.a_records = (
            vec!["1.1.1.1".to_string(), "2.2.2.2".to_string()],
            vec!["3.3.3.3".to_string(), "4.4.4.4".to_string()],
        );
        let f = diff_formatter();
        let out = f.format_diff(&diff);
        assert!(out.contains("1.1.1.1"), "missing 1.1.1.1:\n{}", out);
        assert!(out.contains("2.2.2.2"), "missing 2.2.2.2:\n{}", out);
        assert!(out.contains("3.3.3.3"), "missing 3.3.3.3:\n{}", out);
        assert!(out.contains("4.4.4.4"), "missing 4.4.4.4:\n{}", out);
        // The label only appears on the first row of the field.
        let a_records_label_count = out.matches("A Records").count();
        assert_eq!(
            a_records_label_count, 1,
            "A Records label should appear exactly once:\n{}",
            out
        );
    }

    #[test]
    fn format_diff_wraps_long_scalar_values() {
        let mut diff = make_sample_diff();
        let long = "a".repeat(60);
        diff.ssl.issuer = (Some(long.clone()), Some("short".to_string()));
        let f = diff_formatter();
        let out = f.format_diff(&diff);
        // The 60-char value should not appear on any single line in full.
        for line in out.lines() {
            assert!(
                !line.contains(&long),
                "unwrapped 60-char value on one line: {}",
                line
            );
        }
        // But the characters as a whole should still be present.
        let chars_present = out.matches('a').count();
        assert!(
            chars_present >= 60,
            "wrapped value should preserve all chars, got {}",
            chars_present
        );
    }

    #[test]
    fn format_diff_plain_mode_contains_marker_glyphs() {
        let out = diff_formatter().format_diff(&make_sample_diff());
        assert!(out.contains('='), "plain mode missing =");
        assert!(out.contains('≠'), "plain mode missing ≠");
        assert!(out.contains('─'), "plain mode missing header rule ─");
    }

    #[test]
    fn format_diff_all_matching_has_no_neq() {
        let diff = DomainDiff {
            domain_a: "a.com".to_string(),
            domain_b: "a.com".to_string(),
            registration: RegistrationDiff {
                registrar: (Some("X".to_string()), Some("X".to_string())),
                organization: (Some("Org".to_string()), Some("Org".to_string())),
                created: (Some("2020".to_string()), Some("2020".to_string())),
                expires: (Some("2030".to_string()), Some("2030".to_string())),
            },
            dns: DnsDiff {
                a_records: (vec!["1.1.1.1".to_string()], vec!["1.1.1.1".to_string()]),
                nameservers: (vec!["ns".to_string()], vec!["ns".to_string()]),
                resolves: (Some(true), Some(true)),
            },
            ssl: SslDiff {
                issuer: (Some("I".to_string()), Some("I".to_string())),
                valid_until: (Some("2030".to_string()), Some("2030".to_string())),
                days_remaining: (Some(10), Some(10)),
                is_valid: (Some(true), Some(true)),
            },
            errors: Vec::new(),
        };
        let out = diff_formatter().format_diff(&diff);
        assert!(
            !out.contains('≠'),
            "all-match diff should have no ≠:\n{}",
            out
        );
    }

    #[test]
    fn format_diff_all_differing_has_no_eq() {
        let diff = DomainDiff {
            domain_a: "a.com".to_string(),
            domain_b: "b.com".to_string(),
            registration: RegistrationDiff {
                registrar: (Some("X".to_string()), Some("Y".to_string())),
                organization: (Some("OrgX".to_string()), Some("OrgY".to_string())),
                created: (Some("2020".to_string()), Some("2021".to_string())),
                expires: (Some("2030".to_string()), Some("2031".to_string())),
            },
            dns: DnsDiff {
                a_records: (vec!["1.1.1.1".to_string()], vec!["2.2.2.2".to_string()]),
                nameservers: (vec!["nsa".to_string()], vec!["nsb".to_string()]),
                resolves: (Some(true), Some(false)),
            },
            ssl: SslDiff {
                issuer: (Some("IA".to_string()), Some("IB".to_string())),
                valid_until: (Some("2030".to_string()), Some("2031".to_string())),
                days_remaining: (Some(10), Some(20)),
                is_valid: (Some(true), Some(false)),
            },
            errors: Vec::new(),
        };
        let out = diff_formatter().format_diff(&diff);
        // Every field differs. Match marker must not appear on any row.
        // We exclude the rule-line `─` and any spaces; only search within
        // lines that contain a field label (start with four spaces).
        for line in out.lines() {
            if line.starts_with("    ") && line.len() > 10 {
                assert!(
                    !line.contains('='),
                    "all-differing diff should have no = on field rows: {}",
                    line
                );
            }
        }
    }

    #[test]
    fn format_diff_uneven_list_lengths_pad_shorter_side() {
        let mut diff = make_sample_diff();
        diff.dns.nameservers = (
            vec!["ns1".to_string(), "ns2".to_string(), "ns3".to_string()],
            vec!["only".to_string()],
        );
        let out = diff_formatter().format_diff(&diff);
        // All three left-side nameservers render.
        assert!(out.contains("ns1"), "ns1 missing:\n{}", out);
        assert!(out.contains("ns2"), "ns2 missing:\n{}", out);
        assert!(out.contains("ns3"), "ns3 missing:\n{}", out);
        // Right side only has one value, "only".
        assert!(out.contains("only"), "right-side 'only' missing:\n{}", out);
        // The "only" string must appear exactly once — it should not be
        // mistakenly duplicated onto padding rows.
        assert_eq!(
            out.matches("only").count(),
            1,
            "right-side value must appear exactly once:\n{}",
            out
        );
    }

    #[test]
    fn elide_to_truncates_with_ellipsis_and_respects_width() {
        // Short text is returned unchanged.
        assert_eq!(elide_to("short", 40), "short");
        assert_eq!(elide_to("exactlyten", 10), "exactlyten");
        // Over-width text is elided to exactly `width` chars including the
        // ellipsis.
        let long = "a".repeat(50);
        let out = elide_to(&long, 40);
        assert_eq!(out.chars().count(), 40, "elided width must equal the cap");
        assert!(out.ends_with('…'), "elision marker expected: {out}");
    }

    #[test]
    fn format_diff_header_aligns_when_domain_exceeds_column_cap() {
        // A domain longer than DIFF_COLUMN_CAP must not drift the header out of
        // alignment with the body: the A-column header cell and its rule are
        // both bounded to col_width (== DIFF_COLUMN_CAP here), matching the
        // wrapped data cells.
        let mut diff = make_sample_diff();
        let long_domain = format!("{}.example.com", "x".repeat(50)); // > 40 chars
        diff.domain_a = long_domain.clone();

        let f = diff_formatter();
        let out = f.format_diff(&diff);

        // The full, untruncated domain must never appear on a header/body line
        // (it would blow past the column). The title line is exempt — it shows
        // both domains in full intentionally.
        for line in out.lines() {
            if line.starts_with("Diff:") {
                continue;
            }
            assert!(
                !line.contains(&long_domain),
                "untruncated long domain leaked onto an aligned line: {line}"
            );
        }

        // The A-column rule under the header must be exactly col_width dashes
        // (40), proving the header column matches the capped body column rather
        // than stretching to the raw domain length.
        let cap = DIFF_COLUMN_CAP;
        let has_capped_rule = out
            .lines()
            .any(|l| l.contains(&"─".repeat(cap)) && !l.contains(&"─".repeat(cap + 1)));
        assert!(
            has_capped_rule,
            "expected an A-column rule capped at {cap} dashes:\n{out}"
        );
    }

    #[test]
    fn format_diff_em_dash_is_dim_not_row_color() {
        // Colored formatter — we need to see the ANSI escape codes.
        // Force color output even in non-TTY test environments.
        colored::control::set_override(true);
        let f = HumanFormatter::new();
        let out = f.format_diff(&make_sample_diff());
        colored::control::unset_override();

        // In make_sample_diff, Organization is (None, Some("Google LLC")) →
        // differ row. The row-level red color for differ rows is the bright-red
        // ANSI code `\x1b[91m`. The dim em-dash cell should NOT appear inside
        // that code.
        //
        // We look for the Organization line and assert that the em-dash in it
        // is NOT wrapped in bright-red — i.e. the substring "\x1b[91m—" should
        // not appear. The em-dash should instead appear wrapped in the dim
        // (bright-black, `\x1b[90m`) code.
        let org_line = out
            .lines()
            .find(|l| l.contains("Organization"))
            .expect("organization line missing");
        assert!(
            !org_line.contains("\x1b[91m—"),
            "em-dash should not be red on a differ row: {:?}",
            org_line
        );
        assert!(
            org_line.contains("\x1b[90m"),
            "em-dash should be dim (bright-black ANSI): {:?}",
            org_line
        );
    }
}