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
//! Renders [`MentorMessage`]s as friendly, color-coded advice boxes.
//!
//! Every message is drawn inside a Unicode box (`┌─┐│└┘`) whose accent
//! color and emoji reflect the [`Severity`] of the underlying issue:
//!
//! | Severity | Emoji | Accent                | ANSI code |
//! |----------|-------|-----------------------|-----------|
//! | Info     | 💡    | soft light blue       | `\x1b[94m` |
//! | Warning  | ⚠️    | amber / yellow        | `\x1b[33m` |
//! | Critical | 🚨    | bright red            | `\x1b[91m` |
//!
//! The box is a fixed width ([`BOX_WIDTH`]) and all body text is word-wrapped
//! to keep every line exactly one terminal column wide.
//!
//! ```
//! use limitless_cli::models::{MentorMessage, Severity};
//! use limitless_cli::modules::message_formatter::{format_mentor_message, BOX_WIDTH};
//!
//! let msg = MentorMessage {
//!     severity: Severity::Critical,
//!     plain_english: "Port 3000 is already in use.".into(),
//!     technical_detail: "Another process listens on 0.0.0.0:3000.".into(),
//!     suggested_action: "Run `lsof -i :3000` and stop that process.".into(),
//! };
//! let rendered = format_mentor_message(&msg);
//! assert!(rendered.contains("🚨 MENTOR NOTE:"));
//! assert!(rendered.contains("URGENT ACTION REQUIRED:"));
//!
//! // Pure text (no ANSI) is handy for logging and tests:
//! use limitless_cli::modules::message_formatter::format_mentor_message_plain;
//! let plain = format_mentor_message_plain(&msg);
//! assert!(!plain.contains('\x1b'));
//! for line in plain.lines() {
//!     assert_eq!(line.chars().count(), BOX_WIDTH);
//! }
//! ```

use crate::models::{MentorMessage, Severity};

/// Overall box width measured in terminal columns / string characters.
///
/// Every frame line — border, heading or body — is exactly this wide.
pub const BOX_WIDTH: usize = 60;

/// Inner text width between the two vertical bars.
const INNER_WIDTH: usize = BOX_WIDTH - 4;

/// Leading spaces used for the indented "why / action" body text.
const BODY_INDENT: usize = 4;

/// Regular box corners used for the top border.
const TOP_LEFT: char = '┌';
const TOP_RIGHT: char = '┐';

/// Regular box corners used for the bottom border.
const BOTTOM_LEFT: char = '└';
const BOTTOM_RIGHT: char = '┘';

/// Horizontal / vertical frame characters.
const HORIZONTAL: char = '─';
const VERTICAL: char = '│';

/// The muted ANSI color palette backing the three severity levels.
///
/// | Severity | Code        |
/// |----------|-------------|
/// | Info     | `\x1b[94m`  |
/// | Warning  | `\x1b[33m`  |
/// | Critical | `\x1b[91m`  |
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Palette {
    /// Soft light blue — `\x1b[94m`
    pub info: &'static str,
    /// Amber / yellow — `\x1b[33m`
    pub warning: &'static str,
    /// Bright red — `\x1b[91m`
    pub critical: &'static str,
    /// ANSI reset — `\x1b[0m`
    pub reset: &'static str,
}

/// The muted ANSI color scheme used everywhere in this module.
pub const PALETTE: Palette = Palette {
    info: "\x1b[94m",
    warning: "\x1b[33m",
    critical: "\x1b[91m",
    reset: "\x1b[0m",
};

/// Accent color configured for one severity level.
///
/// ```
/// use limitless_cli::modules::message_formatter::{PALETTE, accent_for};
/// use limitless_cli::models::Severity;
///
/// assert_eq!(accent_for(Severity::Info), PALETTE.info);
/// assert_eq!(accent_for(Severity::Warning), PALETTE.warning);
/// assert_eq!(accent_for(Severity::Critical), PALETTE.critical);
/// ```
pub fn accent_for(severity: Severity) -> &'static str {
    match severity {
        Severity::Info => PALETTE.info,
        Severity::Warning => PALETTE.warning,
        Severity::Critical => PALETTE.critical,
    }
}

/// Emoji + label pairing for the note header.
///
/// ```
/// use limitless_cli::modules::message_formatter::note_emoji;
/// use limitless_cli::models::Severity;
///
/// assert_eq!(note_emoji(Severity::Info), "💡");
/// assert_eq!(note_emoji(Severity::Critical), "🚨");
/// ```
pub fn note_emoji(severity: Severity) -> &'static str {
    match severity {
        Severity::Info => "💡",
        Severity::Warning => "⚠️",
        Severity::Critical => "🚨",
    }
}

/// Emoji used next to the suggested-action heading.
///
/// ```
/// use limitless_cli::modules::message_formatter::action_emoji;
/// use limitless_cli::models::Severity;
///
/// assert_eq!(action_emoji(Severity::Info), "✅");
/// assert_eq!(action_emoji(Severity::Warning), "⚡");
/// assert_eq!(action_emoji(Severity::Critical), "🚨");
/// ```
pub fn action_emoji(severity: Severity) -> &'static str {
    match severity {
        Severity::Info => "✅",
        Severity::Warning => "⚡",
        Severity::Critical => "🚨",
    }
}

/// Heading shown above the suggested action.
///
/// Critical messages signal urgency; warnings ask for a quick action.
///
/// ```
/// use limitless_cli::modules::message_formatter::action_label;
/// use limitless_cli::models::Severity;
///
/// assert_eq!(action_label(Severity::Info), "Next step:");
/// assert_eq!(action_label(Severity::Warning), "Quick action:");
/// assert_eq!(action_label(Severity::Critical), "URGENT ACTION REQUIRED:");
/// ```
pub fn action_label(severity: Severity) -> &'static str {
    match severity {
        Severity::Info => "Next step:",
        Severity::Warning => "Quick action:",
        Severity::Critical => "URGENT ACTION REQUIRED:",
    }
}

/// Render `msg` as a colorized advice box (ANSI escape codes included).
///
/// The accent color, note emoji and action heading all follow [`msg.severity`]
/// (see [`Severity`] / [`PALETTE`]).
pub fn format_mentor_message(msg: &MentorMessage) -> String {
    render_box(msg, true)
}

/// Render `msg` as a plain advice box with zero ANSI escape codes.
///
/// Useful for logging verbatim or for exact-output tests.
pub fn format_mentor_message_plain(msg: &MentorMessage) -> String {
    render_box(msg, false)
}

/// Which frame lines get tinted with the severity accent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RowKind {
    Border,
    Heading,
    Body,
}

fn render_box(msg: &MentorMessage, colored: bool) -> String {
    let severity = msg.severity;
    let accent = accent_for(severity);

    let header_lines = wrap(
        &format!(
            "{} MENTOR NOTE: {}",
            note_emoji(severity),
            msg.plain_english
        ),
        INNER_WIDTH,
    );

    let mut rows: Vec<(RowKind, String)> = Vec::new();
    rows.push((RowKind::Border, border_line(TOP_LEFT, TOP_RIGHT)));
    for line in header_lines {
        rows.push((RowKind::Heading, content_line(&line)));
    }
    rows.push((RowKind::Body, content_line("")));
    rows.push((RowKind::Heading, content_line("📋 Why this matters:")));
    for line in wrap_indented(&msg.technical_detail) {
        rows.push((RowKind::Body, content_line(&line)));
    }
    rows.push((RowKind::Body, content_line("")));
    rows.push((
        RowKind::Heading,
        content_line(&format!(
            "{} {}",
            action_emoji(severity),
            action_label(severity)
        )),
    ));
    for line in wrap_indented(&msg.suggested_action) {
        rows.push((RowKind::Body, content_line(&line)));
    }
    rows.push((RowKind::Border, border_line(BOTTOM_LEFT, BOTTOM_RIGHT)));

    let mut out = String::new();
    for (kind, line) in rows {
        let rendered = if colored && kind != RowKind::Body {
            format!("{accent}{line}{}", PALETTE.reset)
        } else {
            line
        };
        out.push_str(&rendered);
        out.push('\n');
    }
    out
}

/// Produces a horizontal frame line, e.g. `┌─────┐` or `└─────┘`.
fn border_line(left: char, right: char) -> String {
    let mut line = String::new();
    line.push(left);
    for _ in 0..(BOX_WIDTH - 2) {
        line.push(HORIZONTAL);
    }
    line.push(right);
    line
}

/// Produces a vertical frame row holding `content` padded to `INNER_WIDTH`.
fn content_line(content: &str) -> String {
    format!("{VERTICAL} {content:<INNER_WIDTH$} {VERTICAL}")
}

/// Body text wrapped at the box's text width and indented by `BODY_INDENT`.
fn wrap_indented(text: &str) -> Vec<String> {
    let width = INNER_WIDTH - BODY_INDENT;
    wrap(text, width)
        .into_iter()
        .map(|line| format!("{}{line}", " ".repeat(BODY_INDENT)))
        .collect()
}

/// Word-wraps `text` so every line is at most `width` characters long.
///
/// Words longer than `width` are hard-split across lines. Multiple
/// consecutive 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
}

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

    fn msg(severity: Severity) -> MentorMessage {
        MentorMessage {
            severity,
            plain_english: "Node is ready.".into(),
            technical_detail: "Runtime v22.9.0 detected.".into(),
            suggested_action: "None.".into(),
        }
    }

    #[test]
    fn info_box_renders_exact_plain_output() {
        let pad = |content: &str| {
            format!(
                "{content}{}",
                " ".repeat(INNER_WIDTH - content.chars().count())
            )
        };
        let row = |content: String| format!("│ {content} │");
        let border =
            |left: char, right: char| format!("{left}{}{right}", "─".repeat(BOX_WIDTH - 2));

        let expected = format!(
            "{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n",
            border(TOP_LEFT, TOP_RIGHT),
            row(pad("💡 MENTOR NOTE: Node is ready.")),
            row(pad("")),
            row(pad("📋 Why this matters:")),
            row(pad("    Runtime v22.9.0 detected.")),
            row(pad("")),
            row(pad("✅ Next step:")),
            row(pad("    None.")),
            border(BOTTOM_LEFT, BOTTOM_RIGHT),
        );
        assert_eq!(format_mentor_message_plain(&msg(Severity::Info)), expected);
    }

    #[test]
    fn warning_box_uses_quick_action_label() {
        let out = format_mentor_message_plain(&msg(Severity::Warning));
        assert!(out.contains("⚠️ MENTOR NOTE:"));
        assert!(out.contains("⚡ Quick action:"));
        assert!(!out.contains("URGENT ACTION REQUIRED:"));
    }

    #[test]
    fn critical_box_marks_action_as_urgent() {
        let out = format_mentor_message_plain(&msg(Severity::Critical));
        assert!(out.contains("🚨 MENTOR NOTE:"));
        assert!(out.contains("🚨 URGENT ACTION REQUIRED:"));
    }

    #[test]
    fn every_plain_line_is_exactly_box_width() {
        for severity in [Severity::Info, Severity::Warning, Severity::Critical] {
            let out = format_mentor_message_plain(&msg(severity));
            for line in out.lines() {
                assert_eq!(line.chars().count(), BOX_WIDTH);
            }
            assert!(!out.contains('\x1b'));
        }
    }

    #[test]
    fn colored_output_uses_muted_ansi_palette() {
        let info = format_mentor_message(&msg(Severity::Info));
        assert!(info.contains(accent_for(Severity::Info)));
        assert!(info.contains(PALETTE.reset));

        let warning = format_mentor_message(&msg(Severity::Warning));
        assert!(warning.contains(accent_for(Severity::Warning)));
        assert!(warning.contains(PALETTE.reset));

        let critical = format_mentor_message(&msg(Severity::Critical));
        assert!(critical.contains(accent_for(Severity::Critical)));
        assert!(critical.contains(PALETTE.reset));
    }

    #[test]
    fn long_messages_wrap_within_box() {
        let long = MentorMessage {
            severity: Severity::Info,
            plain_english: "The npm package manager was not found on your PATH, which means the install command cannot resolve it.".into(),
            technical_detail: "Neither `npm` nor `npx` resolve to an executable under any of the configured PATH entries.".into(),
            suggested_action: "Run `npm install -g node` or reinstall Node and then restart your terminal before trying again.".into(),
        };
        let plain = format_mentor_message_plain(&long);
        assert!(plain.lines().count() > 9, "wrapping should add rows");
        for line in plain.lines() {
            assert_eq!(line.chars().count(), BOX_WIDTH);
        }
        assert!(plain.contains("📋 Why this matters:"));
        assert!(plain.contains("Next step:"));
    }

    #[test]
    fn wrap_respects_width() {
        let text = "one two three four five";
        assert_eq!(
            wrap(text, 10),
            vec![
                "one two".to_string(),
                "three four".to_string(),
                "five".to_string(),
            ]
        );
    }

    #[test]
    fn wrap_hard_splits_overlong_words() {
        assert_eq!(
            wrap("abcdefghijk", 4),
            vec!["abcd".to_string(), "efgh".to_string(), "ijk".to_string(),]
        );
    }

    #[test]
    fn wrap_collapses_multiple_spaces() {
        assert_eq!(wrap("a   b", 10), vec!["a b".to_string()]);
    }

    #[test]
    fn wrap_empty_and_width_zero() {
        assert_eq!(wrap("", 10), vec![String::new()]);
        assert_eq!(wrap("abc", 0), vec![String::new()]);
    }

    #[test]
    fn indented_body_stays_within_inner_width() {
        let lines = wrap_indented("Short body.");
        assert_eq!(lines[0], "    Short body.");
        assert!(lines.iter().all(|l| l.chars().count() <= INNER_WIDTH));
    }

    #[test]
    fn palette_values_are_exact_ansi_codes() {
        assert_eq!(PALETTE.info, "\x1b[94m");
        assert_eq!(PALETTE.warning, "\x1b[33m");
        assert_eq!(PALETTE.critical, "\x1b[91m");
        assert_eq!(PALETTE.reset, "\x1b[0m");
    }

    #[test]
    fn test_mentor_message_formatting() {
        let msg = MentorMessage {
            severity: Severity::Warning,
            plain_english: "Port 3000 is jammed.".to_string(),
            technical_detail: "EADDRINUSE".to_string(),
            suggested_action: "Free the port, then retry".to_string(),
        };

        let plain = format_mentor_message_plain(&msg);
        assert!(!plain.contains("\x1b["), "plain output must have no ANSI");
        assert!(plain.contains("Port 3000 is jammed."));
        assert!(plain.contains("EADDRINUSE"));
        assert!(plain.contains("Free the port, then retry"));
        assert!(plain.contains("MENTOR NOTE:"), "severity label should be rendered");

        let colored = format_mentor_message(&msg);
        assert!(colored.contains("\x1b["), "colored output must use ANSI");
        assert!(colored.contains("Port 3000 is jammed."));
    }
}