clash 0.5.4

Command Line Agent Safety Harness — permission policies for coding 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
//! Test console panel — a persistent side panel for testing tool invocations
//! against the current policy in real-time.
//!
//! The panel maintains a history of test cases. When the policy is modified,
//! all cases are re-evaluated and changed results are flagged.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};

use crate::policy::Effect;
use crate::policy::match_tree::CompiledPolicy;
use crate::policy::test_eval;

/// A single test case in the console history.
#[derive(Debug, Clone)]
pub struct TestCase {
    /// The raw input string the user typed.
    pub input: String,
    /// The resolved tool name.
    pub tool_name: String,
    /// The resolved tool input JSON.
    pub tool_input: serde_json::Value,
    /// The most recent evaluation result.
    pub effect: Effect,
    /// Short summary of the decision.
    pub summary: String,
    /// Whether this test case is pinned (always visible).
    pub pinned: bool,
    /// Whether the result changed on the last re-evaluation.
    pub changed: bool,
    /// The previous effect before re-evaluation (for change detection).
    prev_effect: Option<Effect>,
}

/// Messages for the TestPanel component.
#[derive(Debug)]
pub enum Msg {
    ScrollUp,
    ScrollDown,
    JumpTop,
    JumpBottom,
    TogglePin,
    DeleteCase,
    ClearHistory,
    /// A character typed into the input line.
    InputChar(char),
    InputBackspace,
    InputDelete,
    InputLeft,
    InputRight,
    InputHome,
    InputEnd,
    InputSubmit,
    InputClear,
}

pub struct TestPanel {
    /// Test case history (newest last).
    cases: Vec<TestCase>,
    /// Currently selected case in the history.
    selected: usize,
    /// Scroll offset for the history view.
    scroll_offset: usize,
    /// Whether the input line is focused (vs history navigation).
    pub input_active: bool,
    /// The current input line text.
    input_line: String,
    /// Cursor position in the input line.
    input_cursor: usize,
    /// Whether the panel is visible.
    pub visible: bool,
    /// Flash message (error from last submit).
    flash: Option<String>,
}

impl Default for TestPanel {
    fn default() -> Self {
        Self::new()
    }
}

impl TestPanel {
    pub fn new() -> Self {
        TestPanel {
            cases: Vec::new(),
            selected: 0,
            scroll_offset: 0,
            input_active: true,
            input_line: String::new(),
            input_cursor: 0,
            visible: true,
            flash: None,
        }
    }

    /// Toggle panel visibility.
    pub fn toggle(&mut self) {
        self.visible = !self.visible;
        if self.visible {
            self.input_active = true;
        }
    }

    /// Handle a key event, returning a message if applicable.
    pub fn handle_key(&self, key: KeyEvent) -> Option<Msg> {
        if self.input_active {
            // Input mode keys
            match key.code {
                KeyCode::Enter => Some(Msg::InputSubmit),
                KeyCode::Backspace => Some(Msg::InputBackspace),
                KeyCode::Delete => Some(Msg::InputDelete),
                KeyCode::Left => Some(Msg::InputLeft),
                KeyCode::Right => Some(Msg::InputRight),
                KeyCode::Home => Some(Msg::InputHome),
                KeyCode::End => Some(Msg::InputEnd),
                KeyCode::Esc => Some(Msg::InputClear),
                KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                    Some(Msg::InputClear)
                }
                KeyCode::Char(c) => Some(Msg::InputChar(c)),
                _ => None,
            }
        } else {
            // History navigation mode
            match key.code {
                KeyCode::Char('k') | KeyCode::Up => Some(Msg::ScrollUp),
                KeyCode::Char('j') | KeyCode::Down => Some(Msg::ScrollDown),
                KeyCode::Char('g') => Some(Msg::JumpTop),
                KeyCode::Char('G') => Some(Msg::JumpBottom),
                KeyCode::Char('p') => Some(Msg::TogglePin),
                KeyCode::Char('d') => Some(Msg::DeleteCase),
                KeyCode::Char('x') => Some(Msg::ClearHistory),
                KeyCode::Char('i') | KeyCode::Enter => {
                    // Switch to input mode — handled by returning None and letting
                    // the caller set input_active
                    None
                }
                _ => None,
            }
        }
    }

    /// Process a message and update state. Returns true if a flash should be shown.
    pub fn update(&mut self, msg: Msg, policy: Option<&CompiledPolicy>) -> TestPanelAction {
        match msg {
            Msg::ScrollUp => {
                self.selected = self.selected.saturating_sub(1);
                TestPanelAction::None
            }
            Msg::ScrollDown => {
                if !self.cases.is_empty() {
                    self.selected = (self.selected + 1).min(self.cases.len() - 1);
                }
                TestPanelAction::None
            }
            Msg::JumpTop => {
                self.selected = 0;
                TestPanelAction::None
            }
            Msg::JumpBottom => {
                if !self.cases.is_empty() {
                    self.selected = self.cases.len() - 1;
                }
                TestPanelAction::None
            }
            Msg::TogglePin => {
                if let Some(case) = self.cases.get_mut(self.selected) {
                    case.pinned = !case.pinned;
                }
                TestPanelAction::None
            }
            Msg::DeleteCase => {
                if self.selected < self.cases.len() {
                    self.cases.remove(self.selected);
                    if self.selected >= self.cases.len() && !self.cases.is_empty() {
                        self.selected = self.cases.len() - 1;
                    }
                }
                TestPanelAction::None
            }
            Msg::ClearHistory => {
                // Keep pinned cases
                self.cases.retain(|c| c.pinned);
                self.selected = 0;
                TestPanelAction::None
            }
            Msg::InputChar(c) => {
                self.flash = None;
                self.input_line.insert(self.input_cursor, c);
                self.input_cursor += c.len_utf8();
                TestPanelAction::None
            }
            Msg::InputBackspace => {
                if self.input_cursor > 0 {
                    let prev = self.input_line[..self.input_cursor]
                        .chars()
                        .last()
                        .map(|c| c.len_utf8())
                        .unwrap_or(0);
                    self.input_cursor -= prev;
                    self.input_line.remove(self.input_cursor);
                }
                TestPanelAction::None
            }
            Msg::InputDelete => {
                if self.input_cursor < self.input_line.len() {
                    self.input_line.remove(self.input_cursor);
                }
                TestPanelAction::None
            }
            Msg::InputLeft => {
                if self.input_cursor > 0 {
                    let prev = self.input_line[..self.input_cursor]
                        .chars()
                        .last()
                        .map(|c| c.len_utf8())
                        .unwrap_or(0);
                    self.input_cursor -= prev;
                }
                TestPanelAction::None
            }
            Msg::InputRight => {
                if self.input_cursor < self.input_line.len() {
                    let next = self.input_line[self.input_cursor..]
                        .chars()
                        .next()
                        .map(|c| c.len_utf8())
                        .unwrap_or(0);
                    self.input_cursor += next;
                }
                TestPanelAction::None
            }
            Msg::InputHome => {
                self.input_cursor = 0;
                TestPanelAction::None
            }
            Msg::InputEnd => {
                self.input_cursor = self.input_line.len();
                TestPanelAction::None
            }
            Msg::InputSubmit => {
                let input = self.input_line.trim().to_string();
                if input.is_empty() {
                    return TestPanelAction::None;
                }

                let Some(policy) = policy else {
                    self.flash = Some("No policy loaded".into());
                    return TestPanelAction::Flash("No policy loaded".into());
                };

                match test_eval::evaluate_test(&input, policy) {
                    Ok(result) => {
                        let effect = result.effect();
                        let summary = result.summary();
                        let case = TestCase {
                            input: input.clone(),
                            tool_name: result.tool_name,
                            tool_input: result.tool_input,
                            effect,
                            summary,
                            pinned: false,
                            changed: false,
                            prev_effect: None,
                        };
                        self.cases.push(case);
                        self.selected = self.cases.len() - 1;
                        self.input_line.clear();
                        self.input_cursor = 0;
                        self.flash = None;
                        TestPanelAction::None
                    }
                    Err(e) => {
                        let msg = format!("Parse error: {e:#}");
                        self.flash = Some(msg.clone());
                        TestPanelAction::Flash(msg)
                    }
                }
            }
            Msg::InputClear => {
                self.input_line.clear();
                self.input_cursor = 0;
                self.flash = None;
                TestPanelAction::None
            }
        }
    }

    /// Re-evaluate all test cases against a new policy.
    /// Called whenever the policy is modified.
    pub fn re_evaluate(&mut self, policy: &CompiledPolicy) {
        for case in &mut self.cases {
            let new_decision = policy.evaluate(&case.tool_name, &case.tool_input);
            let new_effect = new_decision.effect;
            let new_summary = match &new_decision.reason {
                Some(reason) => format!("{} ({reason})", effect_str(new_effect)),
                None => effect_str(new_effect).to_string(),
            };

            // Detect changes: compare new effect against current effect
            let old_effect = case.effect;
            case.changed = new_effect != old_effect;
            case.prev_effect = Some(old_effect);
            case.effect = new_effect;
            case.summary = new_summary;
        }
    }

    /// Switch focus between input and history.
    pub fn toggle_input_focus(&mut self) {
        self.input_active = !self.input_active;
    }

    /// Render the test panel into the given area.
    pub fn view(&self, frame: &mut Frame, area: Rect) {
        self.view_with_focus(frame, area, true)
    }

    /// Render the test panel, with focus indicator.
    pub fn view_with_focus(&self, frame: &mut Frame, area: Rect, focused: bool) {
        let border_color = if focused {
            Color::Blue
        } else {
            Color::DarkGray
        };
        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(border_color))
            .title(" Test Console ");

        let inner = block.inner(area);
        frame.render_widget(block, area);

        if inner.height < 3 {
            return;
        }

        // Split: history area + input line (2 rows: prompt + hint)
        let chunks = Layout::vertical([
            Constraint::Min(1),    // history
            Constraint::Length(2), // input + hint
        ])
        .split(inner);

        self.render_history(frame, chunks[0]);
        self.render_input(frame, chunks[1]);
    }

    fn render_history(&self, frame: &mut Frame, area: Rect) {
        if self.cases.is_empty() {
            let empty = Paragraph::new(Line::from(Span::styled(
                " Type a test below...",
                Style::default().fg(Color::DarkGray),
            )));
            frame.render_widget(empty, area);
            return;
        }

        let visible_height = area.height as usize;

        // Adjust scroll to keep selected visible
        let scroll = if self.selected < self.scroll_offset {
            self.selected
        } else if self.selected >= self.scroll_offset + visible_height {
            self.selected.saturating_sub(visible_height - 1)
        } else {
            self.scroll_offset
        };

        // Separate pinned from unpinned for rendering
        let mut lines: Vec<Line> = Vec::new();

        // Render unpinned cases first, then pinned section
        let has_pinned = self.cases.iter().any(|c| c.pinned);

        for (i, case) in self
            .cases
            .iter()
            .enumerate()
            .skip(scroll)
            .take(visible_height)
        {
            if case.pinned && has_pinned {
                continue; // Render pinned separately below
            }
            lines.push(self.render_case(i, case));
        }

        // Pinned divider + pinned cases
        if has_pinned {
            let pinned_cases: Vec<(usize, &TestCase)> = self
                .cases
                .iter()
                .enumerate()
                .filter(|(_, c)| c.pinned)
                .collect();

            if !pinned_cases.is_empty() && lines.len() + 1 < visible_height {
                lines.push(Line::from(Span::styled(
                    " ┄┄ pinned ┄┄",
                    Style::default().fg(Color::DarkGray),
                )));
                for (i, case) in pinned_cases {
                    if lines.len() >= visible_height {
                        break;
                    }
                    lines.push(self.render_case(i, case));
                }
            }
        }

        let para = Paragraph::new(lines);
        frame.render_widget(para, area);
    }

    fn render_case(&self, index: usize, case: &TestCase) -> Line<'static> {
        let is_selected = index == self.selected && !self.input_active;
        let pin_marker = if case.pinned { "* " } else { "  " };
        let changed_badge = if case.changed { " [CHG]" } else { "" };

        let effect_icon = match case.effect {
            Effect::Allow => "",
            Effect::Deny => "",
            Effect::Ask => "?",
        };

        let effect_color = match case.effect {
            Effect::Allow => Color::Green,
            Effect::Deny => Color::Red,
            Effect::Ask => Color::Yellow,
        };

        let style = if is_selected {
            Style::default()
                .bg(Color::DarkGray)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };

        let mut spans = vec![
            Span::styled(pin_marker.to_string(), style),
            Span::styled(
                format!("{effect_icon} "),
                if is_selected {
                    style
                } else {
                    Style::default().fg(effect_color)
                },
            ),
            Span::styled(truncate_input(&case.input, 20), style.fg(Color::White)),
            Span::styled(
                format!(" {}", case.summary),
                if is_selected {
                    style
                } else {
                    Style::default().fg(effect_color)
                },
            ),
        ];

        if !changed_badge.is_empty() {
            spans.push(Span::styled(
                changed_badge.to_string(),
                Style::default()
                    .fg(Color::Magenta)
                    .add_modifier(Modifier::BOLD),
            ));
        }

        Line::from(spans)
    }

    fn render_input(&self, frame: &mut Frame, area: Rect) {
        if area.height < 1 {
            return;
        }

        // Input line
        let prompt_style = if self.input_active {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default().fg(Color::DarkGray)
        };

        let input_display = if self.input_line.is_empty() && self.input_active {
            "tool args — e.g. bash git status".to_string()
        } else {
            self.input_line.clone()
        };

        let input_style = if self.input_line.is_empty() && self.input_active {
            Style::default().fg(Color::DarkGray)
        } else if self.input_active {
            Style::default().fg(Color::White)
        } else {
            Style::default().fg(Color::DarkGray)
        };

        let input_line = Line::from(vec![
            Span::styled(" > ", prompt_style),
            Span::styled(input_display, input_style),
        ]);

        let mut lines = vec![input_line];

        // Flash/error message or hint
        if area.height >= 2 {
            if let Some(ref flash) = self.flash {
                lines.push(Line::from(Span::styled(
                    format!("   {flash}"),
                    Style::default().fg(Color::Red),
                )));
            } else {
                lines.push(Line::from(Span::styled(
                    "   Tab: focus history  p: pin",
                    Style::default().fg(Color::DarkGray),
                )));
            }
        }

        let para = Paragraph::new(lines);
        frame.render_widget(para, area);

        // Show cursor in input when active
        if self.input_active {
            let cursor_x = area.x + 3 + self.input_cursor as u16;
            let cursor_y = area.y;
            if cursor_x < area.x + area.width {
                frame.set_cursor_position((cursor_x, cursor_y));
            }
        }
    }
}

/// Action returned from TestPanel::update.
pub enum TestPanelAction {
    None,
    Flash(String),
}

fn effect_str(effect: Effect) -> &'static str {
    match effect {
        Effect::Allow => "allow",
        Effect::Deny => "deny",
        Effect::Ask => "ask",
    }
}

fn truncate_input(input: &str, max: usize) -> String {
    if input.len() <= max {
        input.to_string()
    } else {
        format!("{}", &input[..max - 1])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::manifest_edit;
    use crate::policy::match_tree::*;
    use std::collections::HashMap;

    fn empty_policy() -> CompiledPolicy {
        CompiledPolicy {
            sandboxes: HashMap::new(),
            tree: vec![],
            default_effect: Effect::Deny,
            default_sandbox: None,
        }
    }

    fn policy_allowing_read() -> CompiledPolicy {
        let mut manifest = PolicyManifest {
            includes: vec![],
            policy: empty_policy(),
        };
        manifest_edit::upsert_rule(
            &mut manifest,
            manifest_edit::build_tool_rule("Read", Decision::Allow(None)),
        );
        manifest.policy
    }

    #[test]
    fn test_submit_and_evaluate() {
        let mut panel = TestPanel::new();
        let policy = policy_allowing_read();

        // Type "Read /tmp/foo"
        for c in "Read /tmp/foo".chars() {
            panel.update(Msg::InputChar(c), Some(&policy));
        }
        panel.update(Msg::InputSubmit, Some(&policy));

        assert_eq!(panel.cases.len(), 1);
        assert_eq!(panel.cases[0].effect, Effect::Allow);
        assert!(panel.input_line.is_empty());
    }

    #[test]
    fn test_re_evaluate_detects_changes() {
        let mut panel = TestPanel::new();
        let policy = policy_allowing_read();

        // Submit a test
        panel.input_line = r#"Read { "file_path": "/tmp/foo" }"#.to_string();
        panel.input_cursor = panel.input_line.len();
        panel.update(Msg::InputSubmit, Some(&policy));

        assert_eq!(panel.cases[0].effect, Effect::Allow);

        // Re-evaluate against a deny-all policy
        let deny_policy = empty_policy();
        panel.re_evaluate(&deny_policy);

        assert_eq!(panel.cases[0].effect, Effect::Deny);
        assert!(panel.cases[0].changed);
    }

    #[test]
    fn test_pin_toggle() {
        let mut panel = TestPanel::new();
        let policy = empty_policy();

        panel.input_line = "bash ls".to_string();
        panel.input_cursor = panel.input_line.len();
        panel.update(Msg::InputSubmit, Some(&policy));

        assert!(!panel.cases[0].pinned);

        panel.input_active = false;
        panel.update(Msg::TogglePin, None);
        assert!(panel.cases[0].pinned);

        // Clear should keep pinned
        panel.update(Msg::ClearHistory, None);
        assert_eq!(panel.cases.len(), 1);
    }

    #[test]
    fn test_delete_case() {
        let mut panel = TestPanel::new();
        let policy = empty_policy();

        panel.input_line = "bash ls".to_string();
        panel.input_cursor = panel.input_line.len();
        panel.update(Msg::InputSubmit, Some(&policy));

        panel.input_line = "bash pwd".to_string();
        panel.input_cursor = panel.input_line.len();
        panel.update(Msg::InputSubmit, Some(&policy));

        assert_eq!(panel.cases.len(), 2);

        panel.input_active = false;
        panel.selected = 0;
        panel.update(Msg::DeleteCase, None);
        assert_eq!(panel.cases.len(), 1);
    }

    #[test]
    fn test_no_policy_flash() {
        let mut panel = TestPanel::new();
        panel.input_line = "bash ls".to_string();
        panel.input_cursor = panel.input_line.len();

        let action = panel.update(Msg::InputSubmit, None);
        assert!(matches!(action, TestPanelAction::Flash(_)));
        assert!(panel.cases.is_empty());
    }
}