episteme 0.3.9

Knowledge graph for software engineering — design patterns, refactorings, and laws for AI agents
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! Full-screen install picker: arrow keys / j-k, Space toggles, A toggles all, Enter confirms.

use crossterm::cursor::{Hide, MoveTo, Show};
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use crossterm::style::{Attribute, Print, ResetColor, SetAttribute, SetForegroundColor};
use crossterm::terminal::{
    Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use crossterm::{execute, queue};
use std::io::{self, IsTerminal, Write};

use crate::adapters::installer::Transport;

const DEFAULT_MCP_PORT: u16 = 43175;

/// Prompt the user to choose HTTP or stdio transport for MCP integration.
///
/// In a non-TTY environment (CI, pipes), silently returns HTTP + default port.
pub fn select_transport() -> io::Result<Transport> {
    if !io::stdin().is_terminal() {
        return Ok(Transport::Http {
            port: DEFAULT_MCP_PORT,
            token: None,
        });
    }
    run_transport_tui()
}

fn run_transport_tui() -> io::Result<Transport> {
    let options: &[(&str, &str)] = &[
        (
            "HTTP",
            "recommended — persistent server, instant tool calls",
        ),
        ("stdio", "spawns a new process per tool call"),
    ];
    let mut cursor = 0usize;

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(
        stdout,
        EnterAlternateScreen,
        Hide,
        MoveTo(0, 0),
        Clear(ClearType::All)
    )?;

    struct RawGuard;
    impl Drop for RawGuard {
        fn drop(&mut self) {
            let _ = execute!(io::stdout(), LeaveAlternateScreen, Show);
            let _ = disable_raw_mode();
        }
    }
    let _guard = RawGuard;

    let transport = loop {
        draw_transport(&mut stdout, options, cursor)?;
        stdout.flush()?;

        let ev = event::read()?;
        let Event::Key(key) = ev else { continue };
        if key.kind != KeyEventKind::Press {
            continue;
        }

        match key.code {
            KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('K') => {
                cursor = cursor.saturating_sub(1);
            }
            KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J') => {
                cursor = (cursor + 1).min(options.len() - 1);
            }
            KeyCode::Enter => break cursor,
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('Q') => break 0,
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => break 0,
            _ => {}
        }
    };

    drop(_guard);

    if transport == 0 {
        // HTTP selected — prompt for port in same style
        let port = prompt_port_tui(DEFAULT_MCP_PORT)?;
        Ok(Transport::Http { port, token: None })
    } else {
        Ok(Transport::Stdio)
    }
}

fn draw_transport(w: &mut impl Write, options: &[(&str, &str)], cursor: usize) -> io::Result<()> {
    queue!(w, MoveTo(0, 0), Clear(ClearType::All))?;
    tui_header(w, "MCP transport for Claude Code")?;
    queue!(w, Print("\r\n"))?;

    for (i, (name, desc)) in options.iter().enumerate() {
        let row_hi = i == cursor;
        let mark = if row_hi { "[•]" } else { "[ ]" };
        let prefix = if row_hi { "" } else { "   " };

        if row_hi {
            queue!(
                w,
                SetForegroundColor(HI),
                SetAttribute(Attribute::Bold),
                Print(prefix),
                Print(mark),
                Print("  "),
                Print(format!("{name:<8}")),
                ResetColor,
                SetForegroundColor(DIM),
                Print("  "),
                Print(truncate_desc(desc, 48)),
                ResetColor,
                Print("\r\n"),
            )?;
        } else {
            queue!(
                w,
                Print(prefix),
                SetForegroundColor(DIM),
                Print(mark),
                ResetColor,
                Print("  "),
                Print(format!("{name:<8}")),
                SetForegroundColor(DIM),
                Print("  "),
                Print(truncate_desc(desc, 48)),
                ResetColor,
                Print("\r\n"),
            )?;
        }
    }

    queue!(
        w,
        Print("\r\n"),
        SetForegroundColor(DIM),
        Print(" ────────────────────────────────────────────────────────────────────────\r\n"),
        Print("  ↑/↓ Move   Enter Confirm   Esc/Q Quit\r\n"),
        ResetColor,
    )?;
    Ok(())
}

fn prompt_port_tui(default: u16) -> io::Result<u16> {
    prompt_numeric_tui("MCP HTTP port", "port", default)
}

const ACCENT: crossterm::style::Color = crossterm::style::Color::Cyan;
const DIM: crossterm::style::Color = crossterm::style::Color::DarkGrey;
const HI: crossterm::style::Color = crossterm::style::Color::Yellow;

const TOOLS: &[(&str, &str)] = &[
    ("cursor", "Cursor (IDE)"),
    ("opencode", "OpenCode"),
    ("cline", "Cline (VS Code)"),
];

/// Interactive multi-select when stdin+stdout are TTYs.
/// Pre-selects tools whose names appear in `installed`.
/// On error or non-interactive, returns `Err` so caller can fall back.
pub fn interactive_select_tools(installed: &[&str]) -> io::Result<Vec<String>> {
    let mut checked: Vec<bool> = TOOLS
        .iter()
        .map(|(name, _)| installed.contains(name))
        .collect();

    let result = run_tui(&mut checked)?;

    if result.is_empty() {
        return Ok(vec![]);
    }

    Ok(result)
}

fn selected_names(checked: &[bool]) -> Vec<String> {
    TOOLS
        .iter()
        .zip(checked.iter())
        .filter_map(|((name, _), &on)| on.then_some(name.to_string()))
        .collect()
}

fn run_tui(checked: &mut [bool]) -> io::Result<Vec<String>> {
    enable_raw_mode()?;

    let mut stdout = io::stdout();
    execute!(
        stdout,
        EnterAlternateScreen,
        Hide,
        MoveTo(0, 0),
        Clear(ClearType::All)
    )?;

    struct RawGuard;
    impl Drop for RawGuard {
        fn drop(&mut self) {
            let _ = execute!(io::stdout(), LeaveAlternateScreen, Show);
            let _ = disable_raw_mode();
        }
    }
    let _guard = RawGuard;

    let mut cursor = 0usize;
    let mut warning = false;

    loop {
        draw(&mut stdout, checked, cursor, warning)?;
        stdout.flush()?;

        let ev = event::read()?;
        let Event::Key(key) = ev else {
            continue;
        };
        if key.kind != KeyEventKind::Press {
            continue;
        }

        warning = false;

        match key.code {
            KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('K') => {
                cursor = cursor.saturating_sub(1);
            }
            KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J') => {
                cursor = (cursor + 1).min(TOOLS.len() - 1);
            }
            KeyCode::Char(' ') => {
                checked[cursor] = !checked[cursor];
            }
            KeyCode::Char('a') | KeyCode::Char('A') => {
                let all_on = checked.iter().all(|&c| c);
                checked.fill(!all_on);
            }
            KeyCode::Char('n') | KeyCode::Char('N') => {
                checked.fill(false);
            }
            KeyCode::Enter => {
                if checked.iter().any(|&c| c) {
                    return Ok(selected_names(checked));
                }
                warning = true;
            }
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('Q') => {
                return Ok(vec![]);
            }
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                return Ok(vec![]);
            }
            _ => {}
        }
    }
}

fn draw(w: &mut impl Write, checked: &[bool], cursor: usize, warning: bool) -> io::Result<()> {
    queue!(w, MoveTo(0, 0), Clear(ClearType::All))?;

    queue!(
        w,
        SetForegroundColor(ACCENT),
        SetAttribute(Attribute::Bold),
        Print(" ╭────────────────────────────────────────────────────────────────────────╮\r\n"),
        Print(""),
        ResetColor,
        SetForegroundColor(ACCENT),
        SetAttribute(Attribute::Bold),
        Print("Episteme"),
        ResetColor,
        Print("  ·  Install integrations"),
        SetForegroundColor(ACCENT),
        Print("\r\n"),
        Print(" ╰────────────────────────────────────────────────────────────────────────╯\r\n"),
        ResetColor,
        Print("\r\n"),
    )?;

    for (i, ((name, desc), on)) in TOOLS.iter().zip(checked.iter()).enumerate() {
        let row_hi = i == cursor;
        let mark = if *on { "[x]" } else { "[ ]" };
        let prefix = if row_hi { "" } else { "   " };

        if row_hi {
            queue!(
                w,
                SetForegroundColor(HI),
                SetAttribute(Attribute::Bold),
                Print(prefix),
                Print(mark),
                Print("  "),
                Print(format!("{name:<12}")),
                ResetColor,
                SetForegroundColor(DIM),
                Print("  "),
                Print(truncate_desc(desc, 44)),
                ResetColor,
                Print("\r\n"),
            )?;
        } else {
            queue!(
                w,
                Print(prefix),
                SetForegroundColor(DIM),
                Print(mark),
                ResetColor,
                Print("  "),
                Print(format!("{name:<12}")),
                SetForegroundColor(DIM),
                Print("  "),
                Print(truncate_desc(desc, 44)),
                ResetColor,
                Print("\r\n"),
            )?;
        }
    }

    queue!(
        w,
        Print("\r\n"),
        SetForegroundColor(DIM),
        Print(" ────────────────────────────────────────────────────────────────────────\r\n"),
    )?;

    if warning {
        queue!(
            w,
            SetForegroundColor(crossterm::style::Color::Red),
            SetAttribute(Attribute::Bold),
            Print("  Select at least one tool.\r\n"),
            ResetColor,
        )?;
    } else {
        queue!(
            w,
            SetForegroundColor(DIM),
            Print("  ↑/↓ Move   Space Toggle   A All   N Clear   Enter Confirm   Esc/Q Quit\r\n"),
            ResetColor,
        )?;
    }

    Ok(())
}

fn truncate_desc(s: &str, max_chars: usize) -> String {
    let count = s.chars().count();
    if count <= max_chars {
        return s.to_string();
    }
    let take = max_chars.saturating_sub(1);
    s.chars().take(take).chain(std::iter::once('')).collect()
}

// ---------------------------------------------------------------------------
// Server config TUI (host + bearer token)
// ---------------------------------------------------------------------------

pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub token: Option<String>,
}

/// Interactive server configuration screen.
///
/// - Asks for bind address (127.0.0.1 or 0.0.0.0)
/// - If 0.0.0.0: token is auto-generated and mandatory
/// - If 127.0.0.1: token is optional (recommended)
///
/// Non-TTY returns defaults (127.0.0.1, current port, no token).
pub fn configure_server_tui(
    server_label: &str,
    current_host: &str,
    current_port: u16,
    current_token: &str,
) -> io::Result<ServerConfig> {
    if !io::stdin().is_terminal() {
        return Ok(ServerConfig {
            host: current_host.to_owned(),
            port: current_port,
            token: None,
        });
    }

    // Step 1: Host selection
    let host = run_host_select_tui()?;

    // Step 2: Token decision
    let is_public = !crate::server::mcp_auth::is_localhost(&host);
    let token = if is_public {
        // Mandatory token for non-localhost
        let t = crate::server::mcp_auth::generate_token();
        show_token_tui(&t, true)?;
        Some(t)
    } else {
        // Optional but recommended
        let generate = run_yes_no_tui(
            "Server auth",
            &format!("Generate a bearer token for {server_label} access? (recommended)"),
            true,
        )?;
        if generate {
            let t = crate::server::mcp_auth::generate_token();
            show_token_tui(&t, false)?;
            Some(t)
        } else if !current_token.is_empty() {
            // Keep existing token if present
            Some(current_token.to_owned())
        } else {
            None
        }
    };

    // Step 3: Port (reuse existing)
    let port = prompt_numeric_tui::<u16>(server_label, "port", current_port)?;

    Ok(ServerConfig { host, port, token })
}

fn run_host_select_tui() -> io::Result<String> {
    let options: &[(&str, &str, &str)] = &[
        (
            "127.0.0.1",
            "Local only (recommended)",
            "Only connections from this machine",
        ),
        (
            "0.0.0.0",
            "Remote accessible",
            "Allows connections from other machines (token required)",
        ),
    ];
    let mut cursor = 0usize;

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(
        stdout,
        EnterAlternateScreen,
        Hide,
        MoveTo(0, 0),
        Clear(ClearType::All)
    )?;

    struct RawGuard;
    impl Drop for RawGuard {
        fn drop(&mut self) {
            let _ = execute!(io::stdout(), LeaveAlternateScreen, Show);
            let _ = disable_raw_mode();
        }
    }
    let _guard = RawGuard;

    loop {
        queue!(stdout, MoveTo(0, 0), Clear(ClearType::All))?;
        tui_header(&mut stdout, "API bind address")?;
        queue!(stdout, Print("\r\n"))?;

        for (i, (addr, label, desc)) in options.iter().enumerate() {
            let row_hi = i == cursor;
            let mark = if row_hi { "[•]" } else { "[ ]" };
            let prefix = if row_hi { "" } else { "   " };

            if row_hi {
                queue!(
                    stdout,
                    SetForegroundColor(HI),
                    SetAttribute(Attribute::Bold),
                    Print(prefix),
                    Print(mark),
                    Print("  "),
                    Print(format!("{addr:<12}")),
                    ResetColor,
                    SetForegroundColor(DIM),
                    Print("  "),
                    Print(truncate_desc(label, 28)),
                    ResetColor,
                    Print("\r\n"),
                )?;
                queue!(
                    stdout,
                    SetForegroundColor(DIM),
                    Print("                 "),
                    Print(truncate_desc(desc, 50)),
                    Print("\r\n"),
                    ResetColor,
                )?;
            } else {
                queue!(
                    stdout,
                    Print(prefix),
                    SetForegroundColor(DIM),
                    Print(mark),
                    ResetColor,
                    Print("  "),
                    Print(format!("{addr:<12}")),
                    SetForegroundColor(DIM),
                    Print("  "),
                    Print(truncate_desc(label, 28)),
                    ResetColor,
                    Print("\r\n"),
                )?;
            }
        }

        queue!(
            stdout,
            Print("\r\n"),
            SetForegroundColor(DIM),
            Print(" ────────────────────────────────────────────────────────────────────────\r\n"),
            Print("  ↑/↓ Move   Enter Confirm\r\n"),
            ResetColor,
        )?;
        stdout.flush()?;

        let ev = event::read()?;
        let Event::Key(key) = ev else { continue };
        if key.kind != KeyEventKind::Press {
            continue;
        }

        match key.code {
            KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('K') => {
                cursor = cursor.saturating_sub(1);
            }
            KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J') => {
                cursor = (cursor + 1).min(options.len() - 1);
            }
            KeyCode::Enter => {
                let selected = options[cursor].0;
                drop(_guard);
                return Ok(selected.to_owned());
            }
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('Q') => {
                drop(_guard);
                return Ok("127.0.0.1".to_owned());
            }
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                drop(_guard);
                return Ok("127.0.0.1".to_owned());
            }
            _ => {}
        }
    }
}

/// Display a generated token to the user and wait for Enter.
fn show_token_tui(token: &str, mandatory: bool) -> io::Result<()> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(
        stdout,
        EnterAlternateScreen,
        Hide,
        MoveTo(0, 0),
        Clear(ClearType::All)
    )?;

    struct RawGuard;
    impl Drop for RawGuard {
        fn drop(&mut self) {
            let _ = execute!(io::stdout(), LeaveAlternateScreen, Show);
            let _ = disable_raw_mode();
        }
    }
    let _guard = RawGuard;

    let title = if mandatory {
        "Token generated (required for 0.0.0.0)"
    } else {
        "Token generated"
    };

    loop {
        queue!(stdout, MoveTo(0, 0), Clear(ClearType::All))?;
        tui_header(&mut stdout, title)?;
        queue!(
            stdout,
            Print("\r\n"),
            SetForegroundColor(HI),
            Print("  Bearer token:\r\n"),
            ResetColor,
            Print("\r\n"),
            SetForegroundColor(ACCENT),
            SetAttribute(Attribute::Bold),
            Print(format!("  {token}\r\n")),
            ResetColor,
            Print("\r\n"),
            SetForegroundColor(DIM),
            Print("  Copy this token now. It will be saved to config.yaml\r\n"),
            Print("  and seeded to your AI tool MCP configurations.\r\n"),
            Print("\r\n"),
            Print(" ────────────────────────────────────────────────────────────────────────\r\n"),
            Print("  Press Enter to continue\r\n"),
            ResetColor,
        )?;
        stdout.flush()?;

        let ev = event::read()?;
        let Event::Key(key) = ev else { continue };
        if key.kind != KeyEventKind::Press {
            continue;
        }
        match key.code {
            KeyCode::Enter | KeyCode::Esc => break,
            _ => {}
        }
    }

    drop(_guard);
    // Also print to stdout so it appears in terminal scrollback
    println!("\nEpisteme bearer token: {token}\n");
    Ok(())
}

// ---------------------------------------------------------------------------
// Redis config TUI (only available when compiled with `redis-cache` feature)
// ---------------------------------------------------------------------------

#[cfg(feature = "redis-cache")]
pub struct RedisConfig {
    pub enabled: bool,
    pub host: String,
    pub port: u16,
    pub db: u16,
    pub ttl: u64,
}

/// Interactive Redis config screen. Returns None if user skips.
#[cfg(feature = "redis-cache")]
pub fn configure_redis_tui(current: RedisConfig) -> io::Result<Option<RedisConfig>> {
    if !io::stdin().is_terminal() {
        return Ok(None);
    }

    // Ask enable/skip first
    let enable = run_yes_no_tui("Redis cache", "Configure Redis now?", true)?;
    if !enable {
        return Ok(None);
    }

    // Field editing: host, port, db, ttl
    let host = prompt_field_tui("Redis cache", "host", &current.host)?;
    let port = prompt_numeric_tui::<u16>("Redis cache", "port", current.port)?;
    let db = prompt_numeric_tui::<u16>("Redis cache", "db", current.db)?;
    let ttl = prompt_numeric_tui::<u64>("Redis cache", "ttl (seconds)", current.ttl)?;

    Ok(Some(RedisConfig {
        enabled: true,
        host,
        port,
        db,
        ttl,
    }))
}

/// Interactive telemetry consent screen. Returns true if user consents.
pub fn configure_telemetry_tui() -> io::Result<bool> {
    if !io::stdin().is_terminal() {
        return Ok(true);
    }
    run_yes_no_tui(
        "Telemetry",
        "Share anonymous usage data to improve Episteme?",
        true,
    )
}

fn run_yes_no_tui(title: &str, question: &str, default_yes: bool) -> io::Result<bool> {
    let options = if default_yes {
        vec![("Yes", true), ("No", false)]
    } else {
        vec![("No", false), ("Yes", true)]
    };
    let mut cursor = 0usize;

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(
        stdout,
        EnterAlternateScreen,
        Hide,
        MoveTo(0, 0),
        Clear(ClearType::All)
    )?;

    struct RawGuard;
    impl Drop for RawGuard {
        fn drop(&mut self) {
            let _ = execute!(io::stdout(), LeaveAlternateScreen, Show);
            let _ = disable_raw_mode();
        }
    }
    let _guard = RawGuard;

    loop {
        queue!(stdout, MoveTo(0, 0), Clear(ClearType::All))?;
        tui_header(&mut stdout, title)?;
        queue!(
            stdout,
            Print("\r\n"),
            SetForegroundColor(HI),
            Print(format!("  {question}\r\n")),
            ResetColor,
            Print("\r\n"),
        )?;

        for (i, (label, _)) in options.iter().enumerate() {
            let row_hi = i == cursor;
            if row_hi {
                queue!(
                    stdout,
                    SetForegroundColor(HI),
                    SetAttribute(Attribute::Bold),
                    Print(format!(" › [•]  {label}\r\n")),
                    ResetColor,
                )?;
            } else {
                queue!(
                    stdout,
                    SetForegroundColor(DIM),
                    Print(format!("   [ ]  {label}\r\n")),
                    ResetColor,
                )?;
            }
        }

        queue!(
            stdout,
            Print("\r\n"),
            SetForegroundColor(DIM),
            Print(" ────────────────────────────────────────────────────────────────────────\r\n"),
            Print("  ↑/↓ Move   Enter Confirm\r\n"),
            ResetColor,
        )?;
        stdout.flush()?;

        let ev = event::read()?;
        let Event::Key(key) = ev else { continue };
        if key.kind != KeyEventKind::Press {
            continue;
        }

        match key.code {
            KeyCode::Up | KeyCode::Char('k') => cursor = cursor.saturating_sub(1),
            KeyCode::Down | KeyCode::Char('j') => cursor = (cursor + 1).min(options.len() - 1),
            KeyCode::Enter => return Ok(options[cursor].1),
            KeyCode::Esc | KeyCode::Char('q') => return Ok(!default_yes),
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                return Ok(!default_yes);
            }
            _ => {}
        }
    }
}

fn prompt_field_tui(title: &str, label: &str, default: &str) -> io::Result<String> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(
        stdout,
        EnterAlternateScreen,
        Hide,
        MoveTo(0, 0),
        Clear(ClearType::All)
    )?;

    struct RawGuard;
    impl Drop for RawGuard {
        fn drop(&mut self) {
            let _ = execute!(io::stdout(), LeaveAlternateScreen, Show);
            let _ = disable_raw_mode();
        }
    }
    let _guard = RawGuard;

    let mut input = String::new();

    loop {
        queue!(stdout, MoveTo(0, 0), Clear(ClearType::All))?;
        tui_header(&mut stdout, title)?;

        let display = if input.is_empty() {
            format!("{label}: {default}_")
        } else {
            format!("{label}: {input}_")
        };
        queue!(
            stdout,
            Print("\r\n"),
            SetForegroundColor(HI),
            SetAttribute(Attribute::Bold),
            Print(&display),
            ResetColor,
            Print("\r\n\r\n"),
            SetForegroundColor(DIM),
            Print(" ────────────────────────────────────────────────────────────────────────\r\n"),
            Print("  Type value · Enter to confirm · Esc to keep default\r\n"),
            ResetColor,
        )?;
        stdout.flush()?;

        let ev = event::read()?;
        let Event::Key(key) = ev else { continue };
        if key.kind != KeyEventKind::Press {
            continue;
        }

        match key.code {
            KeyCode::Enter => {
                return Ok(if input.is_empty() {
                    default.to_owned()
                } else {
                    input
                });
            }
            KeyCode::Backspace => {
                input.pop();
            }
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                input.push(c);
            }
            KeyCode::Esc => return Ok(default.to_owned()),
            _ => {}
        }
    }
}

fn prompt_numeric_tui<T>(title: &str, label: &str, default: T) -> io::Result<T>
where
    T: std::str::FromStr + std::fmt::Display + Copy,
{
    let default_str = default.to_string();
    let raw = prompt_field_tui(title, label, &default_str)?;
    Ok(raw.parse::<T>().unwrap_or(default))
}

fn tui_header(w: &mut impl Write, subtitle: &str) -> io::Result<()> {
    let right_pad = 72usize.saturating_sub(12 + subtitle.len());
    let pad = " ".repeat(right_pad);
    queue!(
        w,
        SetForegroundColor(ACCENT),
        SetAttribute(Attribute::Bold),
        Print(" ╭────────────────────────────────────────────────────────────────────────╮\r\n"),
        Print(""),
        ResetColor,
        SetForegroundColor(ACCENT),
        SetAttribute(Attribute::Bold),
        Print("Episteme"),
        ResetColor,
        Print(format!("  ·  {subtitle}")),
        SetForegroundColor(ACCENT),
        Print(format!("{pad}\r\n")),
        Print(" ╰────────────────────────────────────────────────────────────────────────╯\r\n"),
        ResetColor,
    )?;
    Ok(())
}

/// Non-TTY (CI, pipes): comma-separated indices or `a` / `all` for everything.
pub fn fallback_select_tools() -> Vec<String> {
    eprintln!();
    eprintln!("Episteme — Select integrations to install");
    eprintln!("──────────────────────────────────────────");
    for (i, (name, desc)) in TOOLS.iter().enumerate() {
        eprintln!("  [{}] {:<12} {}", i + 1, name, desc);
    }
    eprintln!("  [a] All of the above");
    eprintln!();
    eprint!("Selection (e.g. 1,3 or a): ");
    let _ = io::stderr().flush();

    let mut line = String::new();
    if io::stdin().read_line(&mut line).is_err() {
        return vec![];
    }
    let line = line.trim().to_lowercase();

    if line == "a" || line == "all" {
        return TOOLS.iter().map(|(name, _)| name.to_string()).collect();
    }

    let mut selected = Vec::new();
    for token in line.split(',') {
        let token = token.trim();
        if let Ok(n) = token.parse::<usize>()
            && n >= 1
            && n <= TOOLS.len()
        {
            selected.push(TOOLS[n - 1].0.to_string());
        }
    }
    selected
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapters::installer::Transport;

    #[test]
    fn selected_names_filters_checked() {
        let checked = vec![true, false, true];
        assert_eq!(
            selected_names(&checked),
            vec!["cursor".to_string(), "cline".to_string()]
        );
    }

    /// In a non-TTY context (stdin is not a terminal, e.g. CI), `select_transport`
    /// must return HTTP + default port without blocking.
    #[test]
    fn select_transport_non_tty_returns_http_default() {
        // stdin is redirected (not a terminal) in the test harness.
        if io::stdin().is_terminal() {
            // Skip when running interactively; the non-TTY branch is what we test.
            return;
        }
        let result = select_transport().unwrap();
        assert_eq!(
            result,
            Transport::Http {
                port: 43175,
                token: None,
            }
        );
    }
}