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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! Interactive user-confirmation dialogs for auto-fixes.
//!
//! [`prompt_user_confirmation`] asks a yes/no question and reads a single
//! keypress (no Enter required) with a 30 second timeout; the default is used
//! when the user presses Enter or the prompt expires. [`prompt_fix_selection`]
//! renders a checkbox list that is navigated with the arrow keys, toggled with
//! space and confirmed with Enter.
//!
//! Both prompts are written against the [`KeyReader`] / [`PromptWriter`]
//! abstractions so the same logic is unit-testable with [`MockKeyReader`] and
//! [`CapturingWriter`] instead of a real terminal.
//!
//! ```
//! use limitless_cli::modules::interactive_prompt::{
//!     prompt_user_confirmation_with, CapturingWriter, Key, MockKeyReader,
//!     CONFIRM_TIMEOUT,
//! };
//!
//! let mut reader = MockKeyReader::new(vec![Key::Enter]);
//! let mut writer = CapturingWriter::default();
//! let confirmed = prompt_user_confirmation_with(
//!     "Copy .env.example to .env?",
//!     true,
//!     CONFIRM_TIMEOUT,
//!     &mut reader,
//!     &mut writer,
//! );
//! assert!(confirmed);
//! assert!(writer.output.contains("❓ Copy .env.example to .env? (Y/n) [y]"));
//! ```

use std::collections::VecDeque;
use std::io::{self, Write};
use std::time::Duration;

/// How long a confirmation prompt waits for input before using its default.
pub const CONFIRM_TIMEOUT: Duration = Duration::from_secs(30);

/// How long the fix-selection list stays idle before it confirms what is
/// currently selected (avoids the prompt hanging forever).
const SELECT_IDLE_TIMEOUT: Duration = Duration::from_secs(600);

/// Shown when the user types anything other than `y` / `n`.
const INVALID_INPUT_MSG: &str = "Please enter y or n";

/// One auto-fix candidate offered by the selection UI.
///
/// ```
/// use limitless_cli::modules::interactive_prompt::Fix;
///
/// let fix = Fix::new("Copy .env.example to .env");
/// assert_eq!(fix.description, "Copy .env.example to .env");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Fix {
    /// Short, human-readable description shown in the checklist.
    pub description: String,
}

impl Fix {
    /// Creates a fix candidate from a description.
    pub fn new(description: impl Into<String>) -> Self {
        Self {
            description: description.into(),
        }
    }
}

/// A normalized key press that the prompts understand.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Key {
    /// A printable character, e.g. `'y'`.
    Char(char),
    /// Enter / return key.
    Enter,
    /// Up arrow.
    Up,
    /// Down arrow.
    Down,
    /// Space bar.
    Space,
    /// Escape key (cancels a selection).
    Esc,
    /// Any other key we intentionally ignore.
    Unknown,
}

/// Abstraction over the terminal so prompts can be driven by mock input.
///
/// Implementors return the next normalized [`Key`], or `None` when `timeout`
/// elapses without a key press (or at end of a mocked input queue).
pub trait KeyReader {
    /// Blocks up to `timeout`, returning the next key or `None` on timeout.
    fn read_key(&mut self, timeout: Duration) -> Option<Key>;
}

/// Abstraction over the output stream so prompts can capture their text.
pub trait PromptWriter {
    /// Buffers `text` for display.
    fn write(&mut self, text: &str);
    /// Flushes buffered text to the real output.
    fn flush(&mut self) -> io::Result<()>;
}

/// Key reader backed by a real terminal via the `crossterm` crate.
pub struct TerminalKeyReader;

impl KeyReader for TerminalKeyReader {
    fn read_key(&mut self, timeout: Duration) -> Option<Key> {
        // Non-key events (mouse moves, resizes) are ignored so `None` only
        // ever means "no key was pressed within `timeout`".
        loop {
            if !crossterm::event::poll(timeout).unwrap_or(false) {
                return None;
            }
            match crossterm::event::read() {
                Ok(crossterm::event::Event::Key(event)) => return Some(key_from_crossterm(event)),
                _ => continue,
            }
        }
    }
}

fn key_from_crossterm(event: crossterm::event::KeyEvent) -> Key {
    // In raw mode Ctrl-C arrives as CONTROL + `c`, never as `\u{3}`; map it
    // back so the prompts still treat it as "bail with the default".
    if event
        .modifiers
        .contains(crossterm::event::KeyModifiers::CONTROL)
        && event.code == crossterm::event::KeyCode::Char('c')
    {
        return Key::Char('\u{3}');
    }
    match event.code {
        crossterm::event::KeyCode::Char(' ') => Key::Space,
        crossterm::event::KeyCode::Char(c) => Key::Char(c),
        crossterm::event::KeyCode::Enter => Key::Enter,
        crossterm::event::KeyCode::Up => Key::Up,
        crossterm::event::KeyCode::Down => Key::Down,
        crossterm::event::KeyCode::Esc => Key::Esc,
        _ => Key::Unknown,
    }
}

/// Writer backed by the real standard output.
pub struct StdoutWriter;

impl PromptWriter for StdoutWriter {
    fn write(&mut self, text: &str) {
        let _ = io::stdout().write_all(text.as_bytes());
    }

    fn flush(&mut self) -> io::Result<()> {
        io::stdout().flush()
    }
}

/// Restores the terminal to cooked mode when dropped, even on early returns.
struct RawModeGuard;

impl RawModeGuard {
    fn enable() -> io::Result<Self> {
        crossterm::terminal::enable_raw_mode()?;
        Ok(Self)
    }
}

impl Drop for RawModeGuard {
    fn drop(&mut self) {
        let _ = crossterm::terminal::disable_raw_mode();
    }
}

/// Asks `message` as a yes/no question and returns the user's decision.
///
/// - `(Y/n)` / `[y]` when `default` is `true`; `(y/N)` / `[n]` otherwise.
/// - A single `y`/`Y` (or `yes`) answers yes; `n`/`N` (or `no`) answers no.
/// - Enter (empty input) answers with `default`.
/// - Anything else prints `Please enter y or n` and asks again.
/// - After [`CONFIRM_TIMEOUT`] the prompt falls back to `default`.
///
/// No confirmation prompt works without a terminal; use
/// [`prompt_user_confirmation_with`] for mockable input.
pub fn prompt_user_confirmation(message: &str, default: bool) -> bool {
    let _guard = RawModeGuard::enable().ok();
    let mut reader = TerminalKeyReader;
    let mut writer = StdoutWriter;
    prompt_user_confirmation_with(message, default, CONFIRM_TIMEOUT, &mut reader, &mut writer)
}

/// Testable core of [`prompt_user_confirmation`]; see the module docs.
pub fn prompt_user_confirmation_with(
    message: &str,
    default: bool,
    timeout: Duration,
    reader: &mut dyn KeyReader,
    writer: &mut dyn PromptWriter,
) -> bool {
    loop {
        writer.write(&prompt_line(message, default));
        let _ = writer.flush();

        let Some(key) = reader.read_key(timeout) else {
            writer.write(&format!(
                "\n(timeout after {timeout:?} — using default {})",
                if default { "yes" } else { "no" }
            ));
            let _ = writer.flush();
            return default;
        };

        // Visual feedback: one star per received keypress.
        writer.write("*");
        let _ = writer.flush();

        match parse_confirmation_key(key, default) {
            Some(decision) => {
                writer.write("\n");
                let _ = writer.flush();
                return decision;
            }
            None => {
                writer.write(format!("\n{INVALID_INPUT_MSG}\n").as_str());
                let _ = writer.flush();
            }
        }
    }
}

/// Builds the `❓ … (Y/n) [y]\n>> ` prompt line for `default`.
fn prompt_line(message: &str, default: bool) -> String {
    let hint = if default { "(Y/n)" } else { "(y/N)" };
    let bracket = if default { "[y]" } else { "[n]" };
    format!("❓ {message} {hint} {bracket}\n>> ")
}

/// Maps one key press to a decision. Returns:
/// - `Some(true|false)` — decisive, stop asking;
/// - `Some(_)` on Enter — use the default;
/// - `None` — invalid input, ask again.
fn parse_confirmation_key(key: Key, default: bool) -> Option<bool> {
    match key {
        Key::Char(c) if c.eq_ignore_ascii_case(&'y') => Some(true),
        Key::Char(c) if c.eq_ignore_ascii_case(&'n') => Some(false),
        Key::Enter | Key::Char('\r') | Key::Char('\n') => Some(default),
        Key::Char('\u{3}') => Some(default), // Ctrl-C: bail with default
        _ => None,
    }
}

/// Builds a fix list from `mentor_messages`-style suggestions.
///
/// ```
/// use limitless_cli::modules::interactive_prompt::{Fix, fixes_from_mentors};
/// let fixes = fixes_from_mentors(&["Fix A".into(), "Fix B".into()]);
/// assert_eq!(fixes.len(), 2);
/// assert_eq!(fixes[0].description, "Fix A");
/// ```
pub fn fixes_from_mentors(suggestions: &[String]) -> Vec<Fix> {
    suggestions.iter().map(|s| Fix::new(s.clone())).collect()
}

/// Renders a checkbox list and returns the user-selected fixes.
///
/// - Up / Down arrows move the highlight.
/// - Space toggles the highlighted entry.
/// - Enter confirms; Escape cancels (returns `[]`).
/// - If nothing is pressed for [`SELECT_IDLE_TIMEOUT`], the currently
///   selected entries are returned.
///
/// ```
/// use limitless_cli::modules::interactive_prompt::{
///     CapturingWriter, Fix, Key, MockKeyReader, prompt_fix_selection_with,
/// };
///
/// let fixes = vec![Fix::new("Copy .env.example"), Fix::new("Terminate ghost"),
///                  Fix::new("Update dependencies")];
/// let mut reader = MockKeyReader::new(vec![Key::Down, Key::Space, Key::Enter]);
/// let mut writer = CapturingWriter::default();
/// let chosen = prompt_fix_selection_with(&fixes, &mut reader, &mut writer);
/// assert_eq!(chosen.len(), 1);
/// assert_eq!(chosen[0].description, "Terminate ghost");
/// assert!(writer.output.contains("☑ Terminate ghost"));
/// ```
pub fn prompt_fix_selection(fixes: &[Fix]) -> Vec<Fix> {
    let _guard = RawModeGuard::enable().ok();
    let mut reader = TerminalKeyReader;
    let mut writer = StdoutWriter;
    prompt_fix_selection_with(fixes, &mut reader, &mut writer)
}

/// Testable core of [`prompt_fix_selection`]; see the module docs.
pub fn prompt_fix_selection_with(
    fixes: &[Fix],
    reader: &mut dyn KeyReader,
    writer: &mut dyn PromptWriter,
) -> Vec<Fix> {
    if fixes.is_empty() {
        return Vec::new();
    }

    let count = fixes.len();
    let mut index = 0usize;
    let mut toggled = vec![false; count];

    render_all(writer, fixes, index, &toggled, false);
    let _ = writer.flush();

    loop {
        match reader.read_key(SELECT_IDLE_TIMEOUT) {
            Some(Key::Up) => {
                index = (index + count - 1) % count;
                redraw(writer, fixes, index, &toggled);
            }
            Some(Key::Down) => {
                index = (index + 1) % count;
                redraw(writer, fixes, index, &toggled);
            }
            Some(Key::Space) => {
                toggled[index] = !toggled[index];
                redraw(writer, fixes, index, &toggled);
            }
            Some(Key::Enter) | Some(Key::Char('\r')) | Some(Key::Char('\n')) => {
                writer.write("\x1b[2K\r");
                let _ = writer.flush();
                return collect_selected(fixes, &toggled);
            }
            Some(Key::Esc) => {
                writer.write("\n");
                let _ = writer.flush();
                return Vec::new();
            }
            None => {
                // Idle for SELECT_IDLE_TIMEOUT: return the current selection.
                writer.write("\n");
                let _ = writer.flush();
                return collect_selected(fixes, &toggled);
            }
            Some(Key::Unknown) => {
                // Ignore keys we do not understand and keep waiting.
                continue;
            }
            Some(_) => {
                // Any other printable character: ignore and keep waiting.
                continue;
            }
        }
    }
}

/// Collects the fixes whose checkbox is toggled on.
fn collect_selected(fixes: &[Fix], toggled: &[bool]) -> Vec<Fix> {
    fixes
        .iter()
        .zip(toggled)
        .filter(|(_, on)| **on)
        .map(|(fix, _)| fix.clone())
        .collect()
}

/// Draws the header plus one row per fix.
///
/// When `clear` is set every line is first erased with `\r\x1b[2K`, which lets
/// callers refresh the list in place after a key press.
fn render_all(
    writer: &mut dyn PromptWriter,
    fixes: &[Fix],
    index: usize,
    toggled: &[bool],
    clear: bool,
) {
    let erase = if clear { "\r\x1b[2K" } else { "" };
    let mut out = String::new();
    out.push_str(&format!(
        "{erase}Which issues should we fix? (arrow keys to move, space to select)\n"
    ));
    for (i, fix) in fixes.iter().enumerate() {
        let marker = if toggled[i] { "☑" } else { "☐" };
        if i == index {
            out.push_str(&format!(
                "{erase}\x1b[7m> {marker} {}\x1b[0m\n",
                fix.description
            ));
        } else {
            out.push_str(&format!("{erase}  {marker} {}\n", fix.description));
        }
    }
    writer.write(&out);
}

/// Moves the cursor back up over the rendered list and redraws it.
fn redraw(writer: &mut dyn PromptWriter, fixes: &[Fix], index: usize, toggled: &[bool]) {
    let lines = 1 + fixes.len();
    writer.write(&format!("\x1b[{lines}A"));
    render_all(writer, fixes, index, toggled, true);
    let _ = writer.flush();
}

/// A [`KeyReader`] that replays a canned sequence of keys for tests.
#[derive(Debug, Clone)]
pub struct MockKeyReader {
    keys: VecDeque<Key>,
    timeouts: u32,
}

impl MockKeyReader {
    /// Creates a reader that will replay `keys` in order, then return `None`.
    pub fn new(keys: Vec<Key>) -> Self {
        Self {
            keys: keys.into(),
            timeouts: 0,
        }
    }

    /// Prepends `timeouts` simulated `None` results (i.e. expired waits).
    pub fn with_timeouts(mut self, timeouts: u32) -> Self {
        self.timeouts = timeouts;
        self
    }
}

impl KeyReader for MockKeyReader {
    fn read_key(&mut self, _timeout: Duration) -> Option<Key> {
        if self.timeouts > 0 {
            self.timeouts -= 1;
            return None;
        }
        self.keys.pop_front()
    }
}

/// A [`PromptWriter`] that records everything written for assertions.
#[derive(Debug, Clone, Default)]
pub struct CapturingWriter {
    /// All text written so far, in order.
    pub output: String,
}

impl PromptWriter for CapturingWriter {
    fn write(&mut self, text: &str) {
        self.output.push_str(text);
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

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

    fn keys(values: &[char]) -> Vec<Key> {
        values.iter().map(|c| Key::Char(*c)).collect()
    }

    fn run_confirmation(keys: Vec<Key>, default: bool, timeouts: u32) -> (bool, String) {
        let mut reader = MockKeyReader::new(keys).with_timeouts(timeouts);
        let mut writer = CapturingWriter::default();
        let result = prompt_user_confirmation_with(
            "Copy .env.example to .env?",
            default,
            Duration::from_secs(30),
            &mut reader,
            &mut writer,
        );
        (result, writer.output)
    }

    #[test]
    fn lower_y_answers_yes() {
        let (ok, out) = run_confirmation(keys(&['y']), true, 0);
        assert!(ok);
        assert!(out.contains("❓ Copy .env.example to .env? (Y/n) [y]"));
        assert!(out.contains(">> "));
        assert!(out.contains('*'), "visual feedback star expected");
    }

    #[test]
    fn upper_y_answers_yes() {
        let (ok, _) = run_confirmation(keys(&['Y']), false, 0);
        assert!(ok);
    }

    #[test]
    fn lower_n_answers_no() {
        let (ok, _) = run_confirmation(keys(&['n']), true, 0);
        assert!(!ok);
    }

    #[test]
    fn upper_n_answers_no() {
        let (ok, _) = run_confirmation(keys(&['N']), true, 0);
        assert!(!ok);
    }

    #[test]
    fn yes_word_first_char_decides() {
        let (ok, _) = run_confirmation(keys(&['y', 'e', 's']), false, 0);
        assert!(ok);
    }

    #[test]
    fn no_word_first_char_decides() {
        let (ok, _) = run_confirmation(keys(&['n', 'o']), true, 0);
        assert!(!ok);
    }

    #[test]
    fn enter_uses_default_true() {
        let (ok, _) = run_confirmation(vec![Key::Enter], true, 0);
        assert!(ok);
    }

    #[test]
    fn enter_uses_default_false() {
        let (ok, _) = run_confirmation(vec![Key::Enter], false, 0);
        assert!(!ok);
    }

    #[test]
    fn default_true_renders_caps_hint() {
        let (_, out) = run_confirmation(keys(&['y']), true, 0);
        assert!(out.contains("(Y/n) [y]"));
    }

    #[test]
    fn default_false_renders_other_hint() {
        let (_, out) = run_confirmation(keys(&['n']), false, 0);
        assert!(out.contains("(y/N) [n]"));
    }

    #[test]
    fn invalid_input_reprompts_then_accepts() {
        let (ok, out) = run_confirmation(vec![Key::Char('x'), Key::Char('n')], true, 0);
        assert!(!ok, "second key 'n' should answer no");
        assert_eq!(out.matches(INVALID_INPUT_MSG).count(), 1);
        assert_eq!(out.matches(">> ").count(), 2);
    }

    #[test]
    fn invalid_input_until_enter_uses_default() {
        let (ok, out) = run_confirmation(vec![Key::Char('?'), Key::Enter], true, 0);
        assert!(ok);
        assert_eq!(out.matches(INVALID_INPUT_MSG).count(), 1);
    }

    #[test]
    fn timeout_uses_default() {
        let (ok, out) = run_confirmation(vec![], true, 1);
        assert!(ok, "timeout should fall back to default(true)");
        assert!(out.contains("timeout"));
        assert!(out.contains("default yes"));
    }

    #[test]
    fn timeout_uses_default_false() {
        let (ok, out) = run_confirmation(vec![], false, 1);
        assert!(!ok);
        assert!(out.contains("default no"));
    }

    #[test]
    fn repeated_timeouts_do_not_hang() {
        let (ok, out) = run_confirmation(vec![], true, 5);
        assert!(ok);
        assert_eq!(out.matches("timeout").count(), 1);
    }

    #[test]
    fn unicode_message_preserved() {
        let mut reader = MockKeyReader::new(vec![Key::Char('y')]);
        let mut writer = CapturingWriter::default();
        prompt_user_confirmation_with(
            "Déployer 🚀 ?",
            true,
            Duration::from_secs(30),
            &mut reader,
            &mut writer,
        );
        assert!(writer.output.contains("Déployer 🚀 ?"));
    }

    // ------------------------------------------------------------------
    // Fix selection
    // ------------------------------------------------------------------

    fn sample_fixes() -> Vec<Fix> {
        vec![
            Fix::new("Copy .env.example to .env"),
            Fix::new("Terminate ghost process on port 3000"),
            Fix::new("Update dependencies"),
        ]
    }

    fn run_selection(keys: Vec<Key>) -> (Vec<Fix>, String) {
        let mut reader = MockKeyReader::new(keys);
        let mut writer = CapturingWriter::default();
        let chosen = prompt_fix_selection_with(&sample_fixes(), &mut reader, &mut writer);
        (chosen, writer.output)
    }

    #[test]
    fn selection_toggle_with_arrows_and_space() {
        let (chosen, out) = run_selection(vec![
            Key::Down,  // move to 1
            Key::Space, // toggle fix 1 on
            Key::Down,  // move to 2
            Key::Space, // toggle fix 2 on
            Key::Up,    // back to 1
            Key::Space, // toggle fix 1 off
            Key::Enter,
        ]);
        assert_eq!(chosen.len(), 1);
        assert_eq!(chosen[0].description, "Update dependencies");
        assert!(out.contains("Which issues should we fix?"));
        assert!(out.contains("☑") && out.contains("☐"));
        assert!(out.contains("☑ Update dependencies"));
    }

    #[test]
    fn selection_enter_without_toggles_returns_empty() {
        let (chosen, _) = run_selection(vec![Key::Enter]);
        assert!(chosen.is_empty());
    }

    #[test]
    fn selection_escape_cancels() {
        let (chosen, _) = run_selection(vec![Key::Down, Key::Space, Key::Esc]);
        assert!(chosen.is_empty());
    }

    #[test]
    fn selection_wraps_around_top_and_bottom() {
        let (chosen, _) = run_selection(vec![
            Key::Up,    // wraps to last (index 2)
            Key::Space, // toggle last on
            Key::Enter,
        ]);
        assert_eq!(chosen.len(), 1);
        assert_eq!(chosen[0].description, "Update dependencies");
    }

    #[test]
    fn selection_unknown_keys_are_ignored() {
        let (chosen, _) = run_selection(vec![
            Key::Unknown,
            Key::Unknown,
            Key::Space,
            Key::Unknown,
            Key::Enter,
        ]);
        assert_eq!(chosen.len(), 1);
        assert_eq!(chosen[0].description, "Copy .env.example to .env");
    }

    #[test]
    fn selection_empty_fixes_returns_empty_immediately() {
        let mut reader = MockKeyReader::new(vec![Key::Enter]);
        let mut writer = CapturingWriter::default();
        let chosen = prompt_fix_selection_with(&[], &mut reader, &mut writer);
        assert!(chosen.is_empty());
        assert!(writer.output.is_empty());
    }

    #[test]
    fn selection_idle_timeout_keeps_current_choice() {
        let mut reader = MockKeyReader::new(vec![Key::Down, Key::Space]);
        let mut writer = CapturingWriter::default();
        let chosen = prompt_fix_selection_with(&sample_fixes(), &mut reader, &mut writer);
        assert_eq!(chosen.len(), 1);
        assert_eq!(
            chosen[0].description,
            "Terminate ghost process on port 3000"
        );
    }

    #[test]
    fn fixes_from_mentors_maps_descriptions() {
        let suggestions = vec![
            "Install npm".to_string(),
            "Set EDITOR".to_string(),
            "Kill ghost process".to_string(),
        ];
        let fixes = fixes_from_mentors(&suggestions);
        assert_eq!(fixes.len(), 3);
        assert_eq!(fixes[2].description, "Kill ghost process");
    }
}