clash 0.5.1

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
//! App — the root TUI component that manages tabs, overlays, and the event loop.

use std::path::PathBuf;
use std::time::Instant;

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use ratatui::Frame;
use ratatui::Terminal;
use ratatui::backend::Backend;
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use similar::TextDiff;

use crate::policy::match_tree::{CompiledPolicy, Node, PolicyManifest};
use crate::policy_loader;

use super::includes_view::IncludesView;
use super::inline_form::{FormEvent, FormState};
use super::sandbox_view::SandboxView;
use super::settings_view::SettingsView;
use super::tea::{Action, Component};
use super::tree_view::TreeView;
use super::widgets::{self, DiffLine};

/// Which tab is active.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tab {
    Tree,
    Sandboxes,
    Includes,
    Settings,
}

/// Overlay mode the app can be in.
enum Mode {
    Normal,
    Help,
    Confirm(ConfirmAction),
    SaveReview(DiffState),
    Form(FormState),
}

/// What action to take after confirmation.
enum ConfirmAction {
    Quit,
}

/// State for the diff review overlay.
struct DiffState {
    lines: Vec<DiffLine>,
    scroll: usize,
}

/// Messages for the App component.
pub enum Msg {
    SwitchTab(Tab),
    NextTab,
    PrevTab,
    Save,
    Quit,
    ToggleHelp,
    ConfirmYes,
    ConfirmNo,
    DiffScrollDown,
    DiffScrollUp,
    TreeMsg(<TreeView as Component>::Msg),
    SandboxMsg(<SandboxView as Component>::Msg),
    IncludesMsg(<IncludesView as Component>::Msg),
    SettingsMsg(<SettingsView as Component>::Msg),
}

pub struct App {
    manifest: PolicyManifest,
    /// Content resolved from `includes` entries — shown as read-only.
    included: CompiledPolicy,
    original_json: String,
    path: PathBuf,
    active_tab: Tab,
    tree_view: TreeView,
    sandbox_view: SandboxView,
    includes_view: IncludesView,
    settings_view: SettingsView,
    mode: Mode,
    dirty: bool,
    flash: Option<(String, Instant)>,
}

impl App {
    pub fn new(path: PathBuf, manifest: PolicyManifest) -> Result<Self> {
        let original_json = serde_json::to_string_pretty(&manifest)?;

        // Resolve includes to show their rules/sandboxes as read-only
        let base_dir = path.parent().unwrap_or(std::path::Path::new("."));
        let (included, include_warnings) =
            match policy_loader::resolve_includes(&manifest, base_dir) {
                Ok((cp, warnings)) => (cp, warnings),
                Err(e) => (
                    CompiledPolicy {
                        sandboxes: std::collections::HashMap::new(),
                        tree: vec![],
                        default_effect: manifest.policy.default_effect,
                        default_sandbox: None,
                    },
                    vec![format!("{e}")],
                ),
            };

        let tree_view = TreeView::new(&manifest, &included);
        let sandbox_view = SandboxView::new(&manifest, &included);
        let includes_view = IncludesView::new();
        let settings_view = SettingsView::new();

        // Surface include errors loudly
        let flash = if !include_warnings.is_empty() {
            Some((
                format!("Include errors: {}", include_warnings.join("; ")),
                Instant::now(),
            ))
        } else {
            None
        };

        Ok(App {
            manifest,
            included,
            original_json,
            path,
            active_tab: Tab::Tree,
            tree_view,
            sandbox_view,
            includes_view,
            settings_view,
            mode: Mode::Normal,
            dirty: false,
            flash,
        })
    }

    /// Run the main event loop.
    pub fn run<B: Backend<Error: Send + Sync + 'static>>(
        &mut self,
        terminal: &mut Terminal<B>,
    ) -> Result<()> {
        loop {
            // Clone manifest for view to avoid borrow issues
            let manifest_snapshot = self.manifest.clone();
            terminal.draw(|frame| self.view(frame, frame.area(), &manifest_snapshot))?;

            let event = event::read()?;
            if let Event::Key(key) = event {
                // Form mode handles keys directly — not via Msg
                if matches!(self.mode, Mode::Form(_)) {
                    let FormHandled::Continue = self.handle_form_key(key);
                    continue;
                }

                if let Some(msg) = self.handle_key(key) {
                    let action = self.update_msg(msg);
                    match action {
                        Action::Quit => break,
                        Action::Modified => {
                            self.dirty = true;
                            self.rebuild_views();
                        }
                        Action::RunForm(req) => {
                            let form =
                                FormState::from_request(&req, &self.manifest, Some(&self.included));
                            self.mode = Mode::Form(form);
                        }
                        Action::Flash(s) => {
                            self.flash = Some((s, Instant::now()));
                        }
                        Action::None => {}
                    }
                }
            }
        }
        Ok(())
    }

    /// Handle a key event when in Form mode.
    fn handle_form_key(&mut self, key: KeyEvent) -> FormHandled {
        let Mode::Form(ref form) = self.mode else {
            return FormHandled::Continue;
        };

        // 'a' in an edit form → close and open AddChild for the same path.
        // Only when active field is a Select (not typing in a Text field).
        if key.code == KeyCode::Char('a') && form.active_field_is_select() {
            let add_path = match &form.kind {
                super::inline_form::FormKind::EditDecision { path }
                | super::inline_form::FormKind::EditCondition { path } => {
                    // For EditDecision on an inline leaf, the path points to the
                    // Condition node — use it directly as the parent.
                    // For a bare Decision, go up to the parent Condition.
                    let tree = &self.manifest.policy.tree;
                    if TreeView::get_node_at_path_ref(tree, path)
                        .is_some_and(|n| matches!(n, Node::Condition { .. }))
                    {
                        Some(path.clone())
                    } else if path.len() >= 2 {
                        Some(path[..path.len() - 1].to_vec())
                    } else {
                        None
                    }
                }
                _ => None,
            };

            if let Some(parent_path) = add_path {
                let req = super::tea::FormRequest::AddChild { parent_path };
                let new_form = FormState::from_request(&req, &self.manifest, Some(&self.included));
                self.mode = Mode::Form(new_form);
                return FormHandled::Continue;
            }
        }

        let Mode::Form(ref mut form) = self.mode else {
            return FormHandled::Continue;
        };

        match form.handle_key(key) {
            FormEvent::Continue => FormHandled::Continue,
            FormEvent::Cancel => {
                self.mode = Mode::Normal;
                FormHandled::Continue
            }
            FormEvent::Submit => {
                // Take the form out of mode so we can use it
                let Mode::Form(form) = std::mem::replace(&mut self.mode, Mode::Normal) else {
                    return FormHandled::Continue;
                };
                match form.apply(&mut self.manifest) {
                    Ok(true) => {
                        self.dirty = true;
                        self.rebuild_views();
                        self.flash = Some(("Added".into(), Instant::now()));
                    }
                    Ok(false) => {}
                    Err(msg) => {
                        self.flash = Some((msg, Instant::now()));
                    }
                }
                FormHandled::Continue
            }
        }
    }

    fn handle_key(&self, key: KeyEvent) -> Option<Msg> {
        // Mode-specific key handling
        match &self.mode {
            Mode::Help => return Some(Msg::ToggleHelp), // any key closes help
            Mode::Confirm(_) => {
                return match key.code {
                    KeyCode::Char('y') | KeyCode::Char('Y') => Some(Msg::ConfirmYes),
                    _ => Some(Msg::ConfirmNo),
                };
            }
            Mode::SaveReview(_) => {
                return match key.code {
                    KeyCode::Char('y') | KeyCode::Char('Y') => Some(Msg::ConfirmYes),
                    KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => Some(Msg::ConfirmNo),
                    KeyCode::Char('j') | KeyCode::Down => Some(Msg::DiffScrollDown),
                    KeyCode::Char('k') | KeyCode::Up => Some(Msg::DiffScrollUp),
                    _ => None,
                };
            }
            Mode::Form(_) => return None, // handled separately
            Mode::Normal => {}
        }

        // Global keys
        match key.code {
            KeyCode::Char('q') => return Some(Msg::Quit),
            KeyCode::Char('s') => return Some(Msg::Save),
            KeyCode::Char('?') => return Some(Msg::ToggleHelp),
            KeyCode::Char('1') => return Some(Msg::SwitchTab(Tab::Tree)),
            KeyCode::Char('2') => return Some(Msg::SwitchTab(Tab::Sandboxes)),
            KeyCode::Char('3') => return Some(Msg::SwitchTab(Tab::Includes)),
            KeyCode::Char('4') => return Some(Msg::SwitchTab(Tab::Settings)),
            KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => {
                return Some(Msg::PrevTab);
            }
            KeyCode::BackTab => return Some(Msg::PrevTab),
            KeyCode::Tab => return Some(Msg::NextTab),
            _ => {}
        }

        // Delegate to active tab
        match self.active_tab {
            Tab::Tree => self.tree_view.handle_key(key).map(Msg::TreeMsg),
            Tab::Sandboxes => self.sandbox_view.handle_key(key).map(Msg::SandboxMsg),
            Tab::Includes => self.includes_view.handle_key(key).map(Msg::IncludesMsg),
            Tab::Settings => self.settings_view.handle_key(key).map(Msg::SettingsMsg),
        }
    }

    /// Process a message and return an action.
    fn update_msg(&mut self, msg: Msg) -> Action {
        match msg {
            Msg::SwitchTab(tab) => {
                self.active_tab = tab;
                Action::None
            }
            Msg::NextTab => {
                self.active_tab = match self.active_tab {
                    Tab::Tree => Tab::Sandboxes,
                    Tab::Sandboxes => Tab::Includes,
                    Tab::Includes => Tab::Settings,
                    Tab::Settings => Tab::Tree,
                };
                Action::None
            }
            Msg::PrevTab => {
                self.active_tab = match self.active_tab {
                    Tab::Tree => Tab::Settings,
                    Tab::Sandboxes => Tab::Tree,
                    Tab::Includes => Tab::Sandboxes,
                    Tab::Settings => Tab::Includes,
                };
                Action::None
            }
            Msg::Save => {
                if !self.dirty {
                    return Action::Flash("No changes to save".into());
                }
                let new_json = serde_json::to_string_pretty(&self.manifest).unwrap_or_default();
                let diff_lines = compute_diff(&self.original_json, &new_json);
                self.mode = Mode::SaveReview(DiffState {
                    lines: diff_lines,
                    scroll: 0,
                });
                Action::None
            }
            Msg::Quit => {
                if self.dirty {
                    self.mode = Mode::Confirm(ConfirmAction::Quit);
                    Action::None
                } else {
                    Action::Quit
                }
            }
            Msg::ToggleHelp => {
                self.mode = match self.mode {
                    Mode::Help => Mode::Normal,
                    _ => Mode::Help,
                };
                Action::None
            }
            Msg::ConfirmYes => {
                let mode = std::mem::replace(&mut self.mode, Mode::Normal);
                match mode {
                    Mode::Confirm(ConfirmAction::Quit) => Action::Quit,
                    Mode::SaveReview(_) => {
                        // Actually save
                        match policy_loader::write_manifest(&self.path, &self.manifest) {
                            Ok(()) => {
                                self.original_json = serde_json::to_string_pretty(&self.manifest)
                                    .unwrap_or_default();
                                self.dirty = false;

                                // Post-save validation
                                let new_json = serde_json::to_string_pretty(&self.manifest)
                                    .unwrap_or_default();
                                match crate::policy::compile::compile_to_tree(&new_json) {
                                    Ok(policy) => {
                                        let warnings = policy.platform_warnings();
                                        if warnings.is_empty() {
                                            Action::Flash("Saved".into())
                                        } else {
                                            Action::Flash(format!(
                                                "Saved (warnings: {})",
                                                warnings.join("; ")
                                            ))
                                        }
                                    }
                                    Err(e) => {
                                        Action::Flash(format!("Saved (validation error: {e})"))
                                    }
                                }
                            }
                            Err(e) => Action::Flash(format!("Save failed: {e}")),
                        }
                    }
                    _ => Action::None,
                }
            }
            Msg::ConfirmNo => {
                self.mode = Mode::Normal;
                Action::None
            }
            Msg::DiffScrollDown => {
                if let Mode::SaveReview(ref mut state) = self.mode
                    && state.scroll + 1 < state.lines.len()
                {
                    state.scroll += 1;
                }
                Action::None
            }
            Msg::DiffScrollUp => {
                if let Mode::SaveReview(ref mut state) = self.mode {
                    state.scroll = state.scroll.saturating_sub(1);
                }
                Action::None
            }
            Msg::TreeMsg(m) => self.tree_view.update(m, &mut self.manifest),
            Msg::SandboxMsg(m) => self.sandbox_view.update(m, &mut self.manifest),
            Msg::IncludesMsg(m) => self.includes_view.update(m, &mut self.manifest),
            Msg::SettingsMsg(m) => self.settings_view.update(m, &mut self.manifest),
        }
    }

    fn rebuild_views(&mut self) {
        self.tree_view
            .rebuild_with_included(&self.manifest, &self.included);
        self.sandbox_view
            .rebuild_with_included(&self.manifest, &self.included);
    }

    fn view(&self, frame: &mut Frame, area: Rect, manifest: &PolicyManifest) {
        let chunks = Layout::vertical([
            Constraint::Length(2), // title + tab bar
            Constraint::Min(3),    // content
            Constraint::Length(1), // status bar
        ])
        .split(area);

        // Title bar
        let title = Line::from(vec![
            Span::styled(
                " clash policy editor ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("-- {} ", self.path.display()),
                Style::default().fg(Color::DarkGray),
            ),
        ]);
        frame.render_widget(
            Paragraph::new(title).alignment(Alignment::Left),
            Rect::new(chunks[0].x, chunks[0].y, chunks[0].width, 1),
        );

        // Tab bar
        widgets::render_tab_bar(
            frame,
            Rect::new(chunks[0].x, chunks[0].y + 1, chunks[0].width, 1),
            &self.active_tab,
            self.dirty,
        );

        // Content area — delegate to active tab
        match self.active_tab {
            Tab::Tree => self.tree_view.view(frame, chunks[1], manifest),
            Tab::Sandboxes => self.sandbox_view.view(frame, chunks[1], manifest),
            Tab::Includes => self.includes_view.view(frame, chunks[1], manifest),
            Tab::Settings => self.settings_view.view(frame, chunks[1], manifest),
        }

        // Status bar
        let flash_msg = self.flash.as_ref().and_then(|(msg, instant)| {
            if instant.elapsed().as_secs() < 3 {
                Some(msg.as_str())
            } else {
                None
            }
        });

        let hints: &[(&str, &str)] = match self.active_tab {
            Tab::Tree => &[
                ("j/k", "move"),
                ("h/l", "collapse/expand"),
                ("e", "edit"),
                ("a", "add"),
                ("d", "delete"),
                ("c", "copy to inline"),
                ("s", "save"),
            ],
            Tab::Sandboxes => &[
                ("j/k", "move"),
                ("l/h", "focus rules/back"),
                ("a", "add"),
                ("e", "edit"),
                ("d", "delete"),
                ("c", "copy to inline"),
                ("s", "save"),
            ],
            Tab::Includes => &[
                ("j/k", "move"),
                ("J/K", "reorder"),
                ("a", "add"),
                ("d", "delete"),
                ("s", "save"),
            ],
            Tab::Settings => &[("j/k", "move"), ("Enter", "cycle"), ("s", "save")],
        };

        widgets::render_status_bar(frame, chunks[2], hints, flash_msg);

        // Overlays
        match &self.mode {
            Mode::Help => widgets::render_help_overlay(frame, area),
            Mode::Confirm(ConfirmAction::Quit) => {
                widgets::render_confirm_overlay(frame, area, "Unsaved changes. Quit anyway?");
            }
            Mode::SaveReview(state) => {
                widgets::render_diff_overlay(frame, area, &state.lines, state.scroll);
            }
            Mode::Form(form) => {
                form.view(frame, area);
            }
            Mode::Normal => {}
        }
    }
}

/// Internal result from handling a form key.
enum FormHandled {
    Continue,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::Effect;
    use crate::policy::match_tree::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use ratatui::backend::TestBackend;
    use std::collections::HashMap;

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

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

    /// Simulate pressing a key and rendering the result.
    /// Panics if the render crashes.
    fn press_and_render(app: &mut App, terminal: &mut Terminal<TestBackend>, key_event: KeyEvent) {
        // Handle key
        if matches!(app.mode, Mode::Form(_)) {
            let FormHandled::Continue = app.handle_form_key(key_event);
        } else if let Some(msg) = app.handle_key(key_event) {
            let action = app.update_msg(msg);
            match action {
                Action::Quit => {}
                Action::Modified => {
                    app.dirty = true;
                    app.rebuild_views();
                }
                Action::RunForm(req) => {
                    let form = FormState::from_request(&req, &app.manifest, Some(&app.included));
                    app.mode = Mode::Form(form);
                }
                Action::Flash(s) => {
                    app.flash = Some((s, Instant::now()));
                }
                Action::None => {}
            }
        }

        // Render — this is what we're testing doesn't panic
        let manifest_snapshot = app.manifest.clone();
        terminal
            .draw(|frame| app.view(frame, frame.area(), &manifest_snapshot))
            .unwrap();
    }

    #[test]
    fn test_edit_on_root_renders_without_crash() {
        let manifest = empty_manifest();
        let mut app = App::new(PathBuf::from("/tmp/test.json"), manifest).unwrap();
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();

        // Initial render
        let snap = app.manifest.clone();
        terminal
            .draw(|frame| app.view(frame, frame.area(), &snap))
            .unwrap();

        // Press 'e' on root (selected=0)
        press_and_render(&mut app, &mut terminal, key(KeyCode::Char('e')));

        // Press another key — should still render fine
        press_and_render(&mut app, &mut terminal, key(KeyCode::Char('j')));
        press_and_render(&mut app, &mut terminal, key(KeyCode::Char('k')));
    }

    #[test]
    fn test_delete_on_root_renders_without_crash() {
        let manifest = empty_manifest();
        let mut app = App::new(PathBuf::from("/tmp/test.json"), manifest).unwrap();
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();

        let snap = app.manifest.clone();
        terminal
            .draw(|frame| app.view(frame, frame.area(), &snap))
            .unwrap();

        press_and_render(&mut app, &mut terminal, key(KeyCode::Char('d')));
        press_and_render(&mut app, &mut terminal, key(KeyCode::Char('j')));
    }

    #[test]
    fn test_add_on_root_opens_form_and_renders() {
        let manifest = empty_manifest();
        let mut app = App::new(PathBuf::from("/tmp/test.json"), manifest).unwrap();
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();

        let snap = app.manifest.clone();
        terminal
            .draw(|frame| app.view(frame, frame.area(), &snap))
            .unwrap();

        // Press 'a' on root — should open Add Rule form
        press_and_render(&mut app, &mut terminal, key(KeyCode::Char('a')));
        assert!(matches!(app.mode, Mode::Form(_)));

        // Render form overlay
        press_and_render(&mut app, &mut terminal, key(KeyCode::Esc));
        assert!(matches!(app.mode, Mode::Normal));
    }
}

/// Compute a diff between two strings, returning colored diff lines.
fn compute_diff(old: &str, new: &str) -> Vec<DiffLine> {
    let diff = TextDiff::from_lines(old, new);
    let mut lines = Vec::new();

    for (idx, group) in diff.grouped_ops(3).iter().enumerate() {
        if idx > 0 {
            lines.push(DiffLine::Header("---".into()));
        }
        for op in group {
            for change in diff.iter_changes(op) {
                let line_content = change.to_string_lossy();
                let s = line_content.trim_end_matches('\n').to_string();
                match change.tag() {
                    similar::ChangeTag::Equal => lines.push(DiffLine::Context(format!("  {s}"))),
                    similar::ChangeTag::Insert => lines.push(DiffLine::Add(format!("+ {s}"))),
                    similar::ChangeTag::Delete => lines.push(DiffLine::Remove(format!("- {s}"))),
                }
            }
        }
    }

    if lines.is_empty() {
        lines.push(DiffLine::Context("(no changes)".into()));
    }

    lines
}