shellfirm 0.4.2

`shellfirm` will intercept any risky patterns (default or defined by you) and prompt you a small challenge for double verification, kinda like a captcha for your terminal.
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
//! General tab — drill-down model.
//!
//! Browsing mode:  ↑↓ moves the cursor between three sections
//!                 (Challenge type, Minimum severity, Behavior).
//!                 Enter drills into the focused section.
//! Editing mode:   ↑↓ navigates options inside the active section.
//!                 Space commits the highlighted option.
//!                 Esc returns to Browsing mode.

use crate::checks::Severity;
use crate::config::Challenge;
use crate::tui::draft::DraftSettings;
use crate::tui::tabs::{FieldFocus, Tab, TabOutcome};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};

const SECTION_CHALLENGE: usize = 0;
const SECTION_SEVERITY: usize = 1;
const SECTION_BEHAVIOR: usize = 2;
const NUM_SECTIONS: usize = 3;

const CHALLENGE_OPTIONS: &[&str] = &["Math", "Enter", "Yes"];
const CHALLENGE_DESCRIPTIONS: &[&str] = &[
    "Solve a quick math problem (e.g. 3 + 7 = ?)",
    "Just press Enter to confirm",
    "Type \"yes\" to confirm",
];

const SEVERITY_OPTIONS: &[&str] = &["(all)", "Info", "Low", "Medium", "High", "Critical"];
const SEVERITY_DESCRIPTIONS: &[&str] = &[
    "Trigger on every match (paranoid)",
    "Informational only",
    "Minor risk",
    "Moderate risk (recommended)",
    "Serious risk",
    "Destructive — almost certainly unrecoverable",
];

#[derive(Debug, Default)]
pub struct GeneralTab {
    /// Which section header the cursor sits on (0..NUM_SECTIONS).
    pub section: usize,
    /// `None` = Browsing. `Some(inner)` = Editing the section, with the
    /// inner cursor at row `inner`.
    pub edit_cursor: Option<usize>,
}

fn challenge_index(c: Challenge) -> usize {
    match c {
        Challenge::Math => 0,
        Challenge::Enter => 1,
        Challenge::Yes => 2,
    }
}
fn challenge_from_index(i: usize) -> Challenge {
    match i {
        1 => Challenge::Enter,
        2 => Challenge::Yes,
        _ => Challenge::Math,
    }
}
fn severity_index(s: Option<Severity>) -> usize {
    match s {
        None => 0,
        Some(Severity::Info) => 1,
        Some(Severity::Low) => 2,
        Some(Severity::Medium) => 3,
        Some(Severity::High) => 4,
        Some(Severity::Critical) => 5,
    }
}
fn severity_from_index(i: usize) -> Option<Severity> {
    match i {
        1 => Some(Severity::Info),
        2 => Some(Severity::Low),
        3 => Some(Severity::Medium),
        4 => Some(Severity::High),
        5 => Some(Severity::Critical),
        _ => None,
    }
}

fn section_options_count(section: usize) -> usize {
    match section {
        SECTION_CHALLENGE => CHALLENGE_OPTIONS.len(),
        SECTION_SEVERITY => SEVERITY_OPTIONS.len(),
        SECTION_BEHAVIOR => 3, // Audit, Blast radius, Approved line
        _ => 0,
    }
}

fn initial_inner_cursor(section: usize, draft: &DraftSettings) -> usize {
    match section {
        SECTION_CHALLENGE => challenge_index(draft.current.challenge),
        SECTION_SEVERITY => severity_index(draft.current.min_severity),
        SECTION_BEHAVIOR => 0,
        _ => 0,
    }
}

impl GeneralTab {
    fn is_editing(&self) -> bool {
        self.edit_cursor.is_some()
    }

    fn focus_for_browsing(section: usize) -> FieldFocus {
        let (name, help) = match section {
            SECTION_CHALLENGE => (
                "Challenge type",
                "↑↓ navigate sections · Enter to edit · Tab next.",
            ),
            SECTION_SEVERITY => (
                "Minimum severity",
                "↑↓ navigate sections · Enter to edit · Tab next.",
            ),
            SECTION_BEHAVIOR => (
                "Behavior",
                "↑↓ navigate sections · Enter to edit · Tab next.",
            ),
            _ => ("", ""),
        };
        FieldFocus {
            name: name.into(),
            badges: vec!["all"],
            help: help.into(),
        }
    }

    fn focus_for_editing(section: usize) -> FieldFocus {
        let (name, help) = match section {
            SECTION_CHALLENGE => (
                "Editing: Challenge type",
                "↑↓ navigate · Space to select · Enter to exit · Esc to exit.",
            ),
            SECTION_SEVERITY => (
                "Editing: Minimum severity",
                "↑↓ navigate · Space to select · Enter to exit · Esc to exit.",
            ),
            SECTION_BEHAVIOR => (
                "Editing: Behavior",
                "↑↓ navigate · Space to toggle · Enter to exit · Esc to exit.",
            ),
            _ => ("", ""),
        };
        FieldFocus {
            name: name.into(),
            badges: vec!["all"],
            help: help.into(),
        }
    }
}

impl Tab for GeneralTab {
    fn is_editing(&self) -> bool {
        self.edit_cursor.is_some()
    }

    fn title(&self) -> &str {
        "General"
    }

    fn render(&self, area: Rect, buf: &mut Buffer, draft: &DraftSettings) {
        if area.height < 16 || area.width < 50 {
            return;
        }

        let mut y = area.y;
        for section in 0..NUM_SECTIONS {
            let is_focused = section == self.section;
            let is_editing_this = is_focused && self.is_editing();

            // Bar color: yellow when focused (browsing), green when editing,
            // dim when other.
            let bar_color = if is_editing_this {
                Color::Green
            } else if is_focused {
                Color::Yellow
            } else {
                Color::DarkGray
            };
            buf.set_string(area.x, y, "▌", Style::default().fg(bar_color));

            // Section title
            let title = match section {
                SECTION_CHALLENGE => "Challenge type",
                SECTION_SEVERITY => "Minimum severity",
                SECTION_BEHAVIOR => "Behavior",
                _ => "",
            };
            let title_style = if is_focused {
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default()
                    .fg(Color::Gray)
                    .add_modifier(Modifier::BOLD)
            };
            buf.set_string(area.x + 2, y, title, title_style);

            // Right-aligned [all] badge
            let badge = "[all]";
            buf.set_string(
                area.x + area.width.saturating_sub(badge.chars().count() as u16),
                y,
                badge,
                Style::default().fg(Color::DarkGray),
            );

            y += 1;

            // Section body
            if is_editing_this {
                y = self.render_editing_body(buf, area.x, y, area.width, draft, section);
            } else {
                y = render_summary_body(buf, area.x, y, area.width, draft, section, is_focused);
            }

            y += 1; // blank line between sections
        }
    }

    fn handle_key(&mut self, key: KeyEvent, draft: &mut DraftSettings) -> TabOutcome {
        match self.edit_cursor {
            None => {
                // Browsing mode — ↑↓/jk navigate sections; Enter/→ drills in.
                // ← / → at the App level switch top-level tabs, so we let
                // them fall through (return None) here.
                match key.code {
                    KeyCode::Up | KeyCode::Char('k') => {
                        if self.section > 0 {
                            self.section -= 1;
                            return TabOutcome::FieldFocusChanged(Self::focus_for_browsing(
                                self.section,
                            ));
                        }
                        TabOutcome::None
                    }
                    KeyCode::Down | KeyCode::Char('j') => {
                        if self.section + 1 < NUM_SECTIONS {
                            self.section += 1;
                            return TabOutcome::FieldFocusChanged(Self::focus_for_browsing(
                                self.section,
                            ));
                        }
                        TabOutcome::None
                    }
                    KeyCode::Enter | KeyCode::Char('l') => {
                        let inner = initial_inner_cursor(self.section, draft);
                        self.edit_cursor = Some(inner);
                        TabOutcome::FieldFocusChanged(Self::focus_for_editing(self.section))
                    }
                    _ => TabOutcome::None,
                }
            }
            Some(mut inner) => {
                // Editing mode — Left also exits (alias for Esc).
                let count = section_options_count(self.section);
                match key.code {
                    KeyCode::Esc | KeyCode::Left | KeyCode::Char('h') => {
                        self.edit_cursor = None;
                        TabOutcome::FieldFocusChanged(Self::focus_for_browsing(self.section))
                    }
                    KeyCode::Up | KeyCode::Char('k') => {
                        if inner > 0 {
                            inner -= 1;
                        }
                        self.edit_cursor = Some(inner);
                        TabOutcome::None
                    }
                    KeyCode::Down | KeyCode::Char('j') => {
                        if inner + 1 < count {
                            inner += 1;
                        }
                        self.edit_cursor = Some(inner);
                        TabOutcome::None
                    }
                    KeyCode::Char(' ') => {
                        // Space writes the cursor's value to the draft (and
                        // stays in edit mode so the user can continue, or
                        // press Enter to exit).
                        let mutated = match self.section {
                            SECTION_CHALLENGE => {
                                let new_c = challenge_from_index(inner);
                                if draft.current.challenge != new_c {
                                    draft.current.challenge = new_c;
                                    true
                                } else {
                                    false
                                }
                            }
                            SECTION_SEVERITY => {
                                let new_s = severity_from_index(inner);
                                if draft.current.min_severity != new_s {
                                    draft.current.min_severity = new_s;
                                    true
                                } else {
                                    false
                                }
                            }
                            SECTION_BEHAVIOR => {
                                match inner {
                                    0 => {
                                        draft.current.audit_enabled = !draft.current.audit_enabled;
                                    }
                                    // One switch: the budget (`0` = off).
                                    1 => {
                                        let on = draft.current.blast_radius_on();
                                        draft.current.set_blast_radius_on(!on);
                                    }
                                    _ => {
                                        draft.current.approved_notice =
                                            !draft.current.approved_notice;
                                    }
                                }
                                true
                            }
                            _ => false,
                        };
                        if mutated {
                            TabOutcome::Mutated
                        } else {
                            TabOutcome::None
                        }
                    }
                    KeyCode::Enter => {
                        // Enter exits edit mode (Space already wrote the value).
                        self.edit_cursor = None;
                        TabOutcome::FieldFocusChanged(Self::focus_for_browsing(self.section))
                    }
                    _ => TabOutcome::None,
                }
            }
        }
    }

    fn current_focus(&self) -> FieldFocus {
        if self.is_editing() {
            Self::focus_for_editing(self.section)
        } else {
            Self::focus_for_browsing(self.section)
        }
    }
}

/// `text` cut to `width` characters, ending with `…` when it was longer
/// (shown as `...` in ASCII mode).
fn clip(text: &str, width: usize) -> String {
    if text.chars().count() <= width {
        return text.to_string();
    }
    let mark = crate::tui::a11y::sym("…", "...");
    let mut out: String = text
        .chars()
        .take(width.saturating_sub(mark.chars().count()))
        .collect::<String>()
        .trim_end()
        .to_string();
    out.push_str(mark);
    out
}

/// Render a section's summary line (when not in edit mode).
fn render_summary_body(
    buf: &mut Buffer,
    area_x: u16,
    y: u16,
    area_width: u16,
    draft: &DraftSettings,
    section: usize,
    is_focused: bool,
) -> u16 {
    let indent_x = area_x + 2;
    let value_text = match section {
        SECTION_CHALLENGE => format!("Currently: {}", draft.current.challenge),
        SECTION_SEVERITY => {
            let v = match draft.current.min_severity {
                None => "(all)".to_string(),
                Some(s) => format!("{s}"),
            };
            format!("Currently: {v}")
        }
        SECTION_BEHAVIOR => {
            // Words, not glyphs: a lone `x` reads as "no" to many people,
            // and screen readers say "check mark" / "ballot x".
            let mark = |on: bool| if on { "on" } else { "off" };
            format!(
                "Audit: {} · Blast radius: {} · Approved line: {}",
                mark(draft.current.audit_enabled),
                mark(draft.current.blast_radius_on()),
                mark(draft.current.approved_notice),
            )
        }
        _ => String::new(),
    };
    let value_text = clip(&value_text, area_width.saturating_sub(2) as usize);
    buf.set_string(indent_x, y, &value_text, Style::default().fg(Color::Cyan));

    let hint = "Enter to edit";
    // The hint never covers the summary (the help line says it too).
    let fits = 2 + value_text.chars().count() + 2 + hint.chars().count() <= area_width as usize;
    if is_focused && fits {
        let hint_x = area_x + area_width.saturating_sub(hint.chars().count() as u16);
        buf.set_string(
            hint_x,
            y,
            hint,
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        );
    }
    y + 1
}

impl GeneralTab {
    fn render_editing_body(
        &self,
        buf: &mut Buffer,
        area_x: u16,
        y: u16,
        area_width: u16,
        draft: &DraftSettings,
        section: usize,
    ) -> u16 {
        let inner = self.edit_cursor.unwrap_or(0);
        let indent_x = area_x + 2;

        // Divider line below the section header
        let divider_w = area_width.saturating_sub(2) as usize;
        buf.set_string(
            indent_x,
            y,
            "─".repeat(divider_w),
            Style::default().fg(Color::DarkGray),
        );
        let mut y = y + 1;
        // Room for a row: anything longer ends with `…` (never cut silently).
        let row_w = (area_x + area_width).saturating_sub(indent_x) as usize;

        match section {
            SECTION_CHALLENGE => {
                let saved = challenge_index(draft.current.challenge);
                for (i, label) in CHALLENGE_OPTIONS.iter().enumerate() {
                    let bullet = if i == saved { "(•)" } else { "( )" };
                    let highlight = i == inner;
                    let line_style = if highlight {
                        Style::default()
                            .fg(Color::Black)
                            .bg(Color::Green)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default()
                    };
                    let line = format!(
                        "{bullet} {label:<8}  {desc}",
                        desc = CHALLENGE_DESCRIPTIONS[i]
                    );
                    buf.set_string(indent_x, y, clip(&line, row_w), line_style);
                    y += 1;
                }
            }
            SECTION_SEVERITY => {
                let saved = severity_index(draft.current.min_severity);
                for (i, label) in SEVERITY_OPTIONS.iter().enumerate() {
                    let bullet = if i == saved { "(•)" } else { "( )" };
                    let highlight = i == inner;
                    let line_style = if highlight {
                        Style::default()
                            .fg(Color::Black)
                            .bg(Color::Green)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default()
                    };
                    let line = format!(
                        "{bullet} {label:<10}  {desc}",
                        desc = SEVERITY_DESCRIPTIONS[i]
                    );
                    buf.set_string(indent_x, y, clip(&line, row_w), line_style);
                    y += 1;
                }
            }
            SECTION_BEHAVIOR => {
                let toggles = [
                    (
                        "Audit log",
                        draft.current.audit_enabled,
                        "log every intercepted command",
                    ),
                    (
                        "Blast radius",
                        draft.current.blast_radius_on(),
                        "show the impact (files, size) before the prompt",
                    ),
                    (
                        "Approved line",
                        draft.current.approved_notice,
                        "after a passed challenge, print `approved — running: <command>`",
                    ),
                ];
                for (i, (label, on, desc)) in toggles.iter().enumerate() {
                    let highlight = i == inner;
                    let label_style = if highlight {
                        Style::default()
                            .fg(Color::Black)
                            .bg(Color::Green)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default()
                    };
                    buf.set_string(indent_x, y, label, label_style);
                    let value = if *on {
                        "[ ✓ enabled  ]"
                    } else {
                        "[   disabled ]"
                    };
                    let value_style = if highlight {
                        Style::default()
                            .fg(Color::Black)
                            .bg(Color::Green)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(Color::Cyan)
                    };
                    buf.set_string(indent_x + 16, y, value, value_style);
                    // What the switch does, where there is room.
                    let desc_x = indent_x + 16 + 16;
                    let room = (area_x + area_width).saturating_sub(desc_x) as usize;
                    if room >= 12 {
                        buf.set_string(
                            desc_x,
                            y,
                            clip(&crate::config::ascii_fallback(desc), room),
                            Style::default().fg(Color::DarkGray),
                        );
                    }
                    y += 1;
                }
            }
            _ => {}
        }
        y
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Settings;
    use crossterm::event::KeyModifiers;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::empty())
    }

    fn fresh() -> (GeneralTab, DraftSettings) {
        (
            GeneralTab::default(),
            DraftSettings::from_settings(Settings::default()),
        )
    }

    #[test]
    fn down_in_browsing_moves_section() {
        let (mut tab, mut draft) = fresh();
        let _ = tab.handle_key(key(KeyCode::Down), &mut draft);
        assert_eq!(tab.section, SECTION_SEVERITY);
        assert!(tab.edit_cursor.is_none()); // still browsing
    }

    #[test]
    fn enter_in_browsing_drills_in() {
        let (mut tab, mut draft) = fresh();
        tab.section = SECTION_SEVERITY;
        let _ = tab.handle_key(key(KeyCode::Enter), &mut draft);
        assert!(tab.edit_cursor.is_some());
        // Inner cursor starts at the saved value (default = None → idx 0).
        assert_eq!(tab.edit_cursor, Some(0));
    }

    #[test]
    fn esc_in_editing_returns_to_browsing() {
        let (mut tab, mut draft) = fresh();
        tab.section = SECTION_SEVERITY;
        tab.handle_key(key(KeyCode::Enter), &mut draft);
        assert!(tab.edit_cursor.is_some());
        tab.handle_key(key(KeyCode::Esc), &mut draft);
        assert!(tab.edit_cursor.is_none());
    }

    #[test]
    fn space_on_radio_writes_value_and_stays_in_edit() {
        // Unified model: Space commits cursor's value. Enter just exits.
        let (mut tab, mut draft) = fresh();
        tab.section = SECTION_SEVERITY;
        tab.handle_key(key(KeyCode::Enter), &mut draft);
        // Default cursor = 0 ((all)). Down 5× to Critical.
        for _ in 0..5 {
            tab.handle_key(key(KeyCode::Down), &mut draft);
        }
        assert_eq!(
            draft.current.min_severity, None,
            "navigation alone does not write"
        );
        // Space writes.
        let out = tab.handle_key(key(KeyCode::Char(' ')), &mut draft);
        assert!(matches!(out, TabOutcome::Mutated));
        assert_eq!(draft.current.min_severity, Some(Severity::Critical));
        // Still in edit mode.
        assert!(tab.edit_cursor.is_some(), "Space stays in edit mode");
    }

    #[test]
    fn enter_in_editing_just_exits_without_extra_write() {
        // Enter exits — does NOT write the cursor's value.
        let (mut tab, mut draft) = fresh();
        tab.section = SECTION_SEVERITY;
        tab.handle_key(key(KeyCode::Enter), &mut draft);
        for _ in 0..5 {
            tab.handle_key(key(KeyCode::Down), &mut draft);
        }
        // Cursor on Critical, but nothing was Spaced. Enter exits.
        tab.handle_key(key(KeyCode::Enter), &mut draft);
        assert_eq!(
            draft.current.min_severity, None,
            "Enter must NOT commit — only Space commits"
        );
        assert!(tab.edit_cursor.is_none());
    }

    #[test]
    fn esc_in_editing_just_exits() {
        let (mut tab, mut draft) = fresh();
        tab.section = SECTION_SEVERITY;
        tab.handle_key(key(KeyCode::Enter), &mut draft);
        for _ in 0..5 {
            tab.handle_key(key(KeyCode::Down), &mut draft);
        }
        // Esc exits without writing (no Space was pressed).
        tab.handle_key(key(KeyCode::Esc), &mut draft);
        assert!(tab.edit_cursor.is_none());
        assert_eq!(draft.current.min_severity, None);
    }

    #[test]
    fn space_in_behavior_toggles_focused_toggle() {
        let (mut tab, mut draft) = fresh();
        tab.section = SECTION_BEHAVIOR;
        tab.handle_key(key(KeyCode::Enter), &mut draft);
        // Inner cursor = 0 (Audit log).
        let initial = draft.current.audit_enabled;
        tab.handle_key(key(KeyCode::Char(' ')), &mut draft);
        assert_eq!(draft.current.audit_enabled, !initial);
        // Down to Blast radius, Space.
        tab.handle_key(key(KeyCode::Down), &mut draft);
        let initial_blast = draft.current.blast_radius_on();
        tab.handle_key(key(KeyCode::Char(' ')), &mut draft);
        assert_eq!(draft.current.blast_radius_on(), !initial_blast);
        // Off is the budget, not a second key that would override it.
        assert!(draft.current.blast_radius);
        assert_eq!(draft.current.blast_radius_budget_ms, 0);
        tab.handle_key(key(KeyCode::Char(' ')), &mut draft);
        assert_eq!(
            draft.current.blast_radius_budget_ms,
            crate::config::DEFAULT_BLAST_RADIUS_BUDGET_MS
        );
    }

    #[test]
    fn cut_behavior_rows_end_with_a_marker() {
        let (mut tab, mut draft) = fresh();
        tab.section = SECTION_BEHAVIOR;
        tab.handle_key(key(KeyCode::Enter), &mut draft);
        for w in [50u16, 60, 76] {
            let mut buf = Buffer::empty(Rect::new(0, 0, w, 20));
            tab.render(Rect::new(0, 0, w, 20), &mut buf, &draft);
            let rows: Vec<String> = (0..20)
                .map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect())
                .collect();
            let mut seen = 0;
            for row in rows
                .iter()
                .filter(|r| r.contains("enabled") || r.contains("disabled"))
            {
                seen += 1;
                let desc = row.trim_end();
                let full = [
                    "log every intercepted command",
                    "show the impact (files, size) before the prompt",
                    "after a passed challenge, print `approved — running: <command>`",
                ]
                .iter()
                .any(|d| desc.ends_with(d));
                let cut_marked = desc.ends_with('…') || desc.ends_with("...");
                let no_desc = desc.ends_with(']');
                assert!(
                    full || cut_marked || no_desc,
                    "{w}: cut with no marker: {row:?}"
                );
            }
            assert_eq!(seen, 3, "{w}\n{}", rows.join("\n"));
        }
    }

    #[test]
    fn approved_line_is_the_third_behavior_toggle() {
        // The "approved, running" line can be switched off.
        let (mut tab, mut draft) = fresh();
        assert!(draft.current.approved_notice, "on by default");
        tab.section = SECTION_BEHAVIOR;
        tab.handle_key(key(KeyCode::Enter), &mut draft);
        tab.handle_key(key(KeyCode::Down), &mut draft);
        tab.handle_key(key(KeyCode::Down), &mut draft);
        let out = tab.handle_key(key(KeyCode::Char(' ')), &mut draft);
        assert!(matches!(out, TabOutcome::Mutated));
        assert!(!draft.current.approved_notice);
        assert!(draft.current.audit_enabled && draft.current.blast_radius_on());
        // The cursor stops on the last toggle.
        tab.handle_key(key(KeyCode::Down), &mut draft);
        tab.handle_key(key(KeyCode::Char(' ')), &mut draft);
        assert!(draft.current.approved_notice);
        let yaml = serde_yaml::to_string(&draft.current).unwrap();
        assert!(yaml.contains("approved_notice: true"), "{yaml}");
    }
}