limitless-cli 1.0.0

A beginner-friendly environment diagnostic tool
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
//! Interactive orbital dashboard (`limit orbit`) rendering.
//!
//! [`render_dashboard`] draws the full environment pre-flight as a single
//! Unicode box: a version banner, one status line per diagnostic, a live
//! health bar, a status badge, a beginner-friendly mentor note and a numbered
//! list of auto-fixes.
//!
//! The full width is capped at [`DASHBOARD_WIDTH`] so the dashboard fits an
//! 80-column terminal.
//!
//! ```
//! use limitless_cli::models::{EnvironmentState, HealthScore};
//! use limitless_cli::modules::tui::{render_dashboard, render_dashboard_plain,
//!                                   DASHBOARD_WIDTH};
//!
//! let state = EnvironmentState::default();
//! let dashboard = render_dashboard(&state);
//! assert!(dashboard.contains(concat!("LIMITLESS v", env!("CARGO_PKG_VERSION"))));
//!
//! let plain = render_dashboard_plain(&state);
//! for line in plain.lines() {
//!     assert!(line.chars().count() <= DASHBOARD_WIDTH);
//! }
//! # let _ = HealthScore::default();
//! ```

use colored::{ColoredString, Colorize};

use crate::models::{CheckStatus, DiagnosticResult, EnvironmentState, HealthScore, HealthStatus};

/// Total width of the dashboard frame. Kept ≤ 80 so it fits any terminal.
///
/// ```
/// use limitless_cli::modules::tui::DASHBOARD_WIDTH;
/// assert!(DASHBOARD_WIDTH <= 80);
/// ```
pub const DASHBOARD_WIDTH: usize = 76;

/// Inner content width between the two vertical frame bars.
const INNER_WIDTH: usize = DASHBOARD_WIDTH - 4;

/// Number of cells in the health bar.
pub const HEALTH_BAR_CELLS: usize = 20;

/// Version banner printed on the first row.
/// The title banner shown at the top of every dashboard.
///
/// The version always matches the crate version in `Cargo.toml`.
pub const VERSION_BANNER: &str = concat!(
    "🚀 LIMITLESS v",
    env!("CARGO_PKG_VERSION"),
    " — SYSTEM ENVIRONMENT PRE-FLIGHT"
);

/// Renders the full diagnostic dashboard for `limit orbit`.
///
/// Colors each status icon, the health bar and the status badge using a muted
/// ANSI palette; the returned string is therefore intended for a terminal.
pub fn render_dashboard(state: &EnvironmentState) -> String {
    render_dashboard_inner(state, true)
}

/// Same layout as [`render_dashboard`] but with all ANSI sequences stripped.
///
/// Useful for logging verbatim or for exact-output tests.
pub fn render_dashboard_plain(state: &EnvironmentState) -> String {
    render_dashboard_inner(state, false)
}

/// Per-segment styling used while assembling a row.
///
/// Plain rows are used for body text; the remaining variants map 1:1 to
/// `colored` styles so the same layout works with colors enabled or off.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RowStyle {
    Plain,
    Green,
    Red,
    Yellow,
    Cyan,
    Dimmed,
    CyanBold,
    BoldGreen,
    BoldYellow,
    Status(HealthStatus),
}

/// Applies a [`RowStyle`] to `s` via the `colored` crate.
fn apply_style(s: &str, style: RowStyle) -> ColoredString {
    match style {
        RowStyle::Plain => s.normal(),
        RowStyle::Green => s.green(),
        RowStyle::Red => s.red(),
        RowStyle::Yellow => s.yellow(),
        RowStyle::Cyan => s.cyan(),
        RowStyle::Dimmed => s.dimmed(),
        RowStyle::CyanBold => s.cyan().bold(),
        RowStyle::BoldGreen => s.green().bold(),
        RowStyle::BoldYellow => s.yellow().bold(),
        RowStyle::Status(HealthStatus::Healthy) => s.green().bold(),
        RowStyle::Status(HealthStatus::Caution) => s.yellow().bold(),
        RowStyle::Status(HealthStatus::Critical) => s.red().bold(),
    }
}

/// Uses the live `diagnostics` to recompute health when present, falling back
/// to the stored score (e.g. for a freshly-built empty state).
fn effective_health(state: &EnvironmentState) -> HealthScore {
    if state.diagnostics.is_empty() {
        state.health_score
    } else {
        HealthScore::from_results(&state.diagnostics)
    }
}

/// Uppercase status badge text, e.g. `"CAUTION"`.
fn status_label(status: HealthStatus) -> &'static str {
    match status {
        HealthStatus::Healthy => "HEALTHY",
        HealthStatus::Caution => "CAUTION",
        HealthStatus::Critical => "CRITICAL",
    }
}

/// Splits a percentage into (filled, empty) health-bar block strings.
fn health_bar_parts(percentage: u32) -> (String, String) {
    let filled = ((percentage as f64 * HEALTH_BAR_CELLS as f64) / 100.0).round() as usize;
    let filled = filled.min(HEALTH_BAR_CELLS);
    ("█".repeat(filled), "░".repeat(HEALTH_BAR_CELLS - filled))
}

/// A top (`┌…┐`) or bottom (`└…┘`) frame line.
fn border_line(top: bool) -> String {
    let (left, right) = if top { ('┌', '┐') } else { ('└', '┘') };
    format!("{left}{}{right}", "─".repeat(DASHBOARD_WIDTH - 2))
}

/// A single `│ content-padded │` row assembled from styled segments.
///
/// Padding is computed against the *plain* text length so ANSI escape codes
/// never disturb the frame alignment.
fn styled_row(segments: &[(String, RowStyle)], colored: bool) -> String {
    let plain: Vec<&str> = segments.iter().map(|(s, _)| s.as_str()).collect();
    let plain_len: usize = plain.iter().map(|s| s.chars().count()).sum();
    let pad = INNER_WIDTH.saturating_sub(plain_len);

    let mut line = String::from("│ ");
    for (text, style) in segments {
        if colored {
            line.push_str(&apply_style(text, *style).to_string());
        } else {
            line.push_str(text);
        }
    }
    line.push_str(&" ".repeat(pad));
    line.push_str(" │");
    line
}

/// Word-wraps `text` so every line is at most `width` characters long.
///
/// Words longer than `width` are hard-split across lines; runs of spaces are
/// collapsed into a single gap.
fn wrap(text: &str, width: usize) -> Vec<String> {
    if text.is_empty() || width == 0 {
        return vec![String::new()];
    }

    let mut lines = Vec::new();
    let mut current = String::new();

    for word in text.split(' ') {
        let word_len = word.chars().count();
        if word_len == 0 {
            continue;
        }
        if word_len > width {
            if !current.is_empty() {
                lines.push(std::mem::take(&mut current));
            }
            let mut chunk = String::new();
            for ch in word.chars() {
                if chunk.chars().count() == width {
                    lines.push(std::mem::take(&mut chunk));
                }
                chunk.push(ch);
            }
            current = chunk;
        } else if current.is_empty() {
            current.push_str(word);
        } else if current.chars().count() + 1 + word_len <= width {
            current.push(' ');
            current.push_str(word);
        } else {
            lines.push(std::mem::take(&mut current));
            current.push_str(word);
        }
    }

    if !current.is_empty() {
        lines.push(current);
    }
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines
}

/// Wraps `text` for the 4-space indented body area of the dashboard.
fn wrap_indented(text: &str) -> Vec<String> {
    let width = INNER_WIDTH - 4;
    wrap(text, width)
        .into_iter()
        .map(|line| format!("{}{line}", " ".repeat(4)))
        .collect()
}

/// Renders the status rows for one diagnostic: a colored icon, the check name
/// and a wrapped description, with continuations indented.
fn diagnostic_rows(result: &DiagnosticResult, colored: bool) -> Vec<String> {
    let (icon, style) = match result.status {
        CheckStatus::Pass => ("✓", RowStyle::Green),
        CheckStatus::Warn => ("⚠", RowStyle::Yellow),
        CheckStatus::Fail => ("✖", RowStyle::Red),
    };

    let body = format!("{}: {}", result.check_name, result.message);
    let body_width = INNER_WIDTH - 4;
    let wrapped = wrap(&body, body_width);

    let mut rows = Vec::new();
    for (index, line) in wrapped.iter().enumerate() {
        if index == 0 {
            let icon_token = format!("[{icon}] ");
            rows.push(styled_row(
                &[(icon_token, style), (line.clone(), RowStyle::Plain)],
                colored,
            ));
        } else {
            rows.push(styled_row(
                &[(format!("    {line}"), RowStyle::Plain)],
                colored,
            ));
        }
    }
    rows
}

/// Renders one numbered fix line: `    1. <action> (Y/n) [y]`.
///
/// The `(Y/n) [y]` prompt marker is never split across wrapped lines: it is
/// appended to the last wrapped line, or moved to its own trailing line when
/// it would overflow the frame.
fn fix_row(number: usize, action: &str, colored: bool) -> Vec<String> {
    const PROMPT: &str = " (Y/n) [y]";
    let body_width = INNER_WIDTH - 4;
    let mut lines = wrap(&format!("{number}. {action}"), body_width);
    let last = lines.last_mut().expect("wrap always emits one line");
    if last.chars().count() + PROMPT.chars().count() <= body_width {
        last.push_str(PROMPT);
    } else {
        lines.push(PROMPT.to_string());
    }
    lines
        .into_iter()
        .map(|line| styled_row(&[(format!("    {line}"), RowStyle::Plain)], colored))
        .collect()
}

fn render_dashboard_inner(state: &EnvironmentState, colored: bool) -> String {
    let health = effective_health(state);
    let mentors = crate::modules::diagnostics::mentor_messages(&state.diagnostics);
    let has_fixes = !mentors.is_empty();
    let (bar_fill, bar_empty) = health_bar_parts(health.percentage);

    let mut out = String::new();

    out.push_str(&border_line(true));
    out.push('\n');
    out.push_str(&styled_row(
        &[(VERSION_BANNER.to_string(), RowStyle::CyanBold)],
        colored,
    ));
    out.push('\n');
    out.push_str(&styled_row(
        &[("─".repeat(INNER_WIDTH), RowStyle::Dimmed)],
        colored,
    ));
    out.push('\n');

    if !state.diagnostics.is_empty() {
        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
        out.push('\n');
        for result in &state.diagnostics {
            for row in diagnostic_rows(result, colored) {
                out.push_str(&row);
                out.push('\n');
            }
        }
        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
        out.push('\n');
    } else {
        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
        out.push('\n');
        out.push_str(&styled_row(
            &[("No checks recorded yet.".to_string(), RowStyle::Dimmed)],
            colored,
        ));
        out.push('\n');
    }

    out.push_str(&styled_row(
        &[
            ("Health Score: ".to_string(), RowStyle::Plain),
            (format!("{}% ", health.percentage), RowStyle::Plain),
            ("[".to_string(), RowStyle::Plain),
            (bar_fill, RowStyle::Green),
            (bar_empty, RowStyle::Dimmed),
            ("]".to_string(), RowStyle::Plain),
        ],
        colored,
    ));
    out.push('\n');
    out.push_str(&styled_row(
        &[
            ("Status: ".to_string(), RowStyle::Plain),
            (
                status_label(health.overall_status).to_string(),
                RowStyle::Status(health.overall_status),
            ),
        ],
        colored,
    ));
    out.push('\n');

    if let Some(mentor) = mentors.first() {
        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
        out.push('\n');
        out.push_str(&styled_row(
            &[("💡 MENTOR NOTE:".to_string(), RowStyle::Cyan)],
            colored,
        ));
        out.push('\n');
        for line in wrap_indented(&mentor.plain_english) {
            out.push_str(&styled_row(&[(line, RowStyle::Plain)], colored));
            out.push('\n');
        }
    }

    if has_fixes {
        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
        out.push('\n');
        out.push_str(&styled_row(
            &[("✅ RECOMMENDED FIXES:".to_string(), RowStyle::BoldGreen)],
            colored,
        ));
        out.push('\n');
        for (index, mentor) in mentors.iter().enumerate() {
            for row in fix_row(index + 1, &mentor.suggested_action, colored) {
                out.push_str(&row);
                out.push('\n');
            }
        }
        out.push_str(&styled_row(&[(String::new(), RowStyle::Plain)], colored));
        out.push('\n');
        out.push_str(&styled_row(
            &[(
                "> Executing auto-fixes... ✨".to_string(),
                RowStyle::BoldYellow,
            )],
            colored,
        ));
        out.push('\n');
    }

    out.push_str(&border_line(false));
    out.push('\n');
    out
}

/// Runs `limit orbit`: builds a fresh snapshot and renders the dashboard.
pub async fn run_orbit() {
    let state = crate::modules::diagnostics::build_snapshot(".");
    print!("{}", render_dashboard(&state));
    if state.ready_for_dev() {
        println!(
            "{}",
            "  Dashboard complete — environment is ready to develop."
                .green()
                .bold()
        );
    } else {
        println!(
            "{}",
            "  Dashboard complete — review the notes above before continuing."
                .yellow()
                .bold()
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{HealthScore, ProjectStack};

    fn state_from(diagnostics: Vec<DiagnosticResult>) -> EnvironmentState {
        EnvironmentState {
            detected_stack: ProjectStack::Node {
                version: "18.12.0".into(),
                package_manager: "npm".into(),
            },
            runtime_version: Some("v18.12.0".into()),
            env_file_exists: false,
            env_example_exists: true,
            dependencies_healthy: true,
            blocked_ports: vec![(3000, 9921)],
            diagnostics: diagnostics.clone(),
            health_score: HealthScore::from_results(&diagnostics),
        }
    }

    fn demo_diagnostics() -> Vec<DiagnosticResult> {
        vec![
            DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node v18.12.0 found"),
            DiagnosticResult::new("Env Audit", CheckStatus::Fail, ".env file missing"),
            DiagnosticResult::new(
                "Port Scan",
                CheckStatus::Fail,
                "Port 3000 occupied by PID 9921",
            ),
            DiagnosticResult::new("Dependencies", CheckStatus::Pass, "node_modules present"),
        ]
    }

    #[test]
    fn dashboard_render_renders_all_status_icons() {
        let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
        assert_eq!(dashboard.matches("[✓]").count(), 2);
        assert_eq!(dashboard.matches("[✖]").count(), 2);
        assert!(!dashboard.contains("[⚠]"));
        assert!(dashboard.contains("Runtime Check: Node v18.12.0 found"));
        assert!(dashboard.contains("Env Audit: .env file missing"));
    }

    #[test]
    fn warn_check_uses_amber_icon() {
        let diagnostics = vec![
            DiagnosticResult::new("Runtime Check", CheckStatus::Warn, "Node is outdated"),
            DiagnosticResult::new("Port Scan", CheckStatus::Fail, "Port 5432 busy"),
        ];
        let dashboard = render_dashboard_plain(&state_from(diagnostics));
        assert_eq!(dashboard.matches("[⚠]").count(), 1);
        assert_eq!(dashboard.matches("[✖]").count(), 1);
    }

    #[test]
    fn header_shows_version_banner_and_borders() {
        let dashboard = render_dashboard_plain(&EnvironmentState::default());
        assert!(dashboard.starts_with("┌"));
        assert!(dashboard.ends_with("┘\n"));
        assert!(dashboard.contains(VERSION_BANNER));
    }

    #[test]
    fn every_line_is_exactly_dashboard_width() {
        for diagnostics in [
            demo_diagnostics(),
            vec![DiagnosticResult::new(
                "A",
                CheckStatus::Fail,
                "long message ".repeat(30),
            )],
            vec![],
        ] {
            let dashboard = render_dashboard_plain(&state_from(diagnostics));
            for line in dashboard.lines() {
                let observed = line.chars().count();
                assert!(
                    observed <= DASHBOARD_WIDTH,
                    "line too wide ({observed} > {DASHBOARD_WIDTH}): {line:?}"
                );
            }
        }
    }

    #[test]
    fn health_bar_is_accurate_for_percentages() {
        let cases = [
            (0, 0, 20),
            (25, 5, 15),
            (50, 10, 10),
            (75, 15, 5),
            (100, 20, 0),
        ];
        for (pct, filled, empty) in cases {
            assert_eq!(health_bar_parts(pct).0, "█".repeat(filled));
            assert_eq!(health_bar_parts(pct).1, "░".repeat(empty));
        }

        let diagnostics = vec![
            DiagnosticResult::new("1", CheckStatus::Pass, "ok"),
            DiagnosticResult::new("2", CheckStatus::Fail, "bad"),
        ];
        let dashboard = render_dashboard_plain(&state_from(diagnostics));
        assert!(dashboard.contains("Health Score: 50% [██████████░░░░░░░░░░]"));
    }

    #[test]
    fn status_badge_matches_health() {
        let pass = DiagnosticResult::new("A", CheckStatus::Pass, "ok");
        let fail = DiagnosticResult::new("B", CheckStatus::Fail, "bad");

        let caution =
            render_dashboard_plain(&state_from(vec![pass.clone(), pass.clone(), fail.clone()]));
        assert!(caution.contains("Status: CAUTION"));

        let healthy = render_dashboard_plain(&state_from(vec![pass.clone(), pass.clone()]));
        assert!(healthy.contains("Status: HEALTHY"));

        let critical = render_dashboard_plain(&state_from(vec![fail.clone(), fail.clone()]));
        assert!(critical.contains("Status: CRITICAL"));
    }

    #[test]
    fn mentor_note_section_appears_for_failing_checks() {
        let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
        assert!(dashboard.contains("💡 MENTOR NOTE:"));
    }

    #[test]
    fn recommended_fixes_are_numbered_with_prompt() {
        let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
        assert!(dashboard.contains("✅ RECOMMENDED FIXES:"));
        assert!(dashboard.contains(" (Y/n) [y]"));
        let fix_lines: Vec<&str> = dashboard
            .lines()
            .filter(|l| l.contains("(Y/n) [y]"))
            .collect();
        assert_eq!(fix_lines.len(), 2, "one fix per failing check");
        assert!(dashboard.contains("> Executing auto-fixes... ✨"));
    }

    #[test]
    fn all_pass_dashboard_skips_mentor_and_fixes() {
        let diagnostics = vec![
            DiagnosticResult::new("Runtime Check", CheckStatus::Pass, "Node v22.9.0 found"),
            DiagnosticResult::new("Dependencies", CheckStatus::Pass, "node_modules present"),
        ];
        let dashboard = render_dashboard_plain(&state_from(diagnostics));
        assert!(!dashboard.contains("💡 MENTOR NOTE:"));
        assert!(!dashboard.contains("RECOMMENDED FIXES:"));
        assert!(!dashboard.contains("(Y/n) [y]"));
        assert!(!dashboard.contains("Executing auto-fixes"));
        assert!(dashboard.contains("Status: HEALTHY"));
        assert!(dashboard.contains("Health Score: 100% ["));
    }

    #[test]
    fn dashboard_uses_terminal_colors() {
        colored::control::set_override(true);
        let dashboard = render_dashboard(&state_from(demo_diagnostics()));
        assert!(dashboard.contains("\x1b["));
        assert!(dashboard.contains("\x1b[0m"));
        colored::control::unset_override();
    }

    #[test]
    fn wrap_helper_respects_width() {
        assert_eq!(
            wrap("one two three four", 8),
            vec![
                "one two".to_string(),
                "three".to_string(),
                "four".to_string()
            ]
        );
        assert_eq!(
            wrap("abcdefghijk", 4),
            vec!["abcd".to_string(), "efgh".to_string(), "ijk".to_string()]
        );
        assert_eq!(wrap("", 10), vec![String::new()]);
    }

    #[test]
    fn long_diagnostics_wrap_with_indentation() {
        let diagnostics = vec![DiagnosticResult::new(
            "Tools Check",
            CheckStatus::Warn,
            "very long tool check output that should definitely be wrapped across multiple rows without overflowing the frame".to_string(),
        )];
        let dashboard = render_dashboard_plain(&state_from(diagnostics));
        assert_eq!(dashboard.matches("[⚠]").count(), 1);
        for line in dashboard.lines() {
            assert_eq!(line.chars().count(), DASHBOARD_WIDTH);
        }
    }

    #[test]
    fn empty_diagnostics_show_placeholder() {
        let dashboard = render_dashboard_plain(&EnvironmentState::default());
        assert!(dashboard.contains("No checks recorded yet."));
        assert!(!dashboard.contains("RECOMMENDED FIXES:"));
    }

    // --- Named coverage tests ----------------------------------------------

    #[test]
    fn test_dashboard_rendering() {
        let dashboard = render_dashboard_plain(&state_from(demo_diagnostics()));
        assert!(dashboard.contains(VERSION_BANNER));
        assert!(dashboard.contains("Runtime Check: Node v18.12.0 found"));
        assert!(dashboard.contains("Env Audit: .env file missing"));
        assert!(dashboard.contains("Health Score: 50% ["));
        assert!(dashboard.contains("Status: CRITICAL"));
        assert!(dashboard.contains("💡 MENTOR NOTE:"));
    }

    #[test]
    fn test_color_codes_valid() {
        colored::control::set_override(true);
        let colored = render_dashboard(&state_from(demo_diagnostics()));
        assert!(colored.contains("\x1b["), "colored dashboard needs ANSI");
        assert!(colored.contains("\x1b[0m"), "colored dashboard must reset");
        assert!(!colored.contains("\x1b[0m\x1b[0m"), "no double resets");

        colored::control::set_override(false);
        let plain = render_dashboard_plain(&state_from(demo_diagnostics()));
        assert!(
            !plain.contains("\x1b["),
            "plain dashboard must not contain ANSI escapes"
        );
        colored::control::unset_override();
    }

    #[test]
    fn test_box_drawing_characters() {
        let dashboard = render_dashboard_plain(&EnvironmentState::default());
        assert!(dashboard.contains('┌'), "top-left corner missing");
        assert!(dashboard.contains('┐'), "top-right corner missing");
        assert!(dashboard.contains('└'), "bottom-left corner missing");
        assert!(dashboard.contains('┘'), "bottom-right corner missing");
        assert!(dashboard.contains('│'), "vertical border missing");
        assert!(dashboard.contains('─'), "horizontal border missing");
        for line in dashboard.lines() {
            assert_eq!(line.chars().count(), DASHBOARD_WIDTH);
        }
    }
}