claux 20260907.0.1

Terminal AI coding assistant with tool execution
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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
use serde::{Deserialize, Serialize};

use crate::utils::diff::generate_diff;

/// One configured permission rule: `Tool` or `Tool(pattern)`.
///
/// A bare tool name matches every call of that tool. A pattern is matched as
/// a glob against the call's subject: the command for Bash, the path for
/// file tools, the URL for WebFetch, the prompt for Agent. `*` as the tool
/// name matches every tool. Pattern rules never match a tool whose input has
/// no recognizable subject, so they cannot accidentally widen.
#[derive(Debug, Clone)]
pub struct PermissionRule {
    raw: String,
    tool: String,
    pattern: Option<glob::Pattern>,
}

impl PermissionRule {
    pub fn parse(rule: &str) -> Result<Self, String> {
        let raw = rule.trim();
        if raw.is_empty() {
            return Err("permission rule is empty".to_string());
        }
        let (tool, pattern) = match raw.split_once('(') {
            Some((tool, rest)) => {
                let Some(pattern) = rest.strip_suffix(')') else {
                    return Err(format!(
                        "permission rule {raw:?} is missing its closing ')'"
                    ));
                };
                (tool.trim(), Some(pattern.trim()))
            }
            None => (raw, None),
        };
        if tool.is_empty()
            || !tool
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '*'))
        {
            return Err(format!("permission rule {raw:?} has an invalid tool name"));
        }
        let pattern = match pattern {
            Some("") => return Err(format!("permission rule {raw:?} has an empty pattern")),
            Some(pattern) => Some(
                glob::Pattern::new(pattern)
                    .map_err(|error| format!("permission rule {raw:?}: {error}"))?,
            ),
            None => None,
        };
        Ok(Self {
            raw: raw.to_string(),
            tool: tool.to_string(),
            pattern,
        })
    }

    pub fn as_str(&self) -> &str {
        &self.raw
    }

    pub fn matches(&self, tool_name: &str, input: &serde_json::Value) -> bool {
        if self.tool != "*" && self.tool != tool_name {
            return false;
        }
        match &self.pattern {
            None => true,
            Some(pattern) => rule_subject(tool_name, input)
                .map(|subject| pattern.matches(subject))
                .unwrap_or(false),
        }
    }
}

/// The part of a tool call that pattern rules are matched against.
fn rule_subject<'a>(tool_name: &str, input: &'a serde_json::Value) -> Option<&'a str> {
    let keys: &[&str] = match tool_name {
        "Bash" => &["command"],
        "Read" | "Write" | "Edit" => &["file_path"],
        "Glob" | "Grep" => &["path", "pattern"],
        "WebFetch" => &["url"],
        "Agent" => &["prompt"],
        _ => &[
            "command",
            "file_path",
            "path",
            "url",
            "pattern",
            "prompt",
            "query",
            "name",
        ],
    };
    keys.iter()
        .find_map(|key| input.get(key).and_then(|v| v.as_str()))
}

/// Parsed `[permissions]` rules. Deny wins over ask, ask over allow.
#[derive(Debug, Clone, Default)]
pub struct PermissionRules {
    pub allow: Vec<PermissionRule>,
    pub deny: Vec<PermissionRule>,
    pub ask: Vec<PermissionRule>,
}

impl PermissionRules {
    pub fn parse(allow: &[String], deny: &[String], ask: &[String]) -> Result<Self, String> {
        let parse_all = |rules: &[String]| {
            rules
                .iter()
                .map(|rule| PermissionRule::parse(rule))
                .collect::<Result<Vec<_>, _>>()
        };
        Ok(Self {
            allow: parse_all(allow)?,
            deny: parse_all(deny)?,
            ask: parse_all(ask)?,
        })
    }

    fn first_match<'a>(
        rules: &'a [PermissionRule],
        tool_name: &str,
        input: &serde_json::Value,
    ) -> Option<&'a PermissionRule> {
        rules.iter().find(|rule| rule.matches(tool_name, input))
    }
}

/// How permissions are handled.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum PermissionMode {
    /// Prompt for write operations, auto-allow reads
    #[default]
    Default,
    /// Auto-allow file edits, still prompt for bash
    AcceptEdits,
    /// Allow everything without prompting
    Bypass,
    /// Deny all write operations
    Plan,
}

/// Result of a permission check.
pub enum PermissionResult {
    Allow,
    Deny(String),
    Ask {
        message: String,
        diff: Option<String>,
    },
}

/// User's response to a permission prompt.
#[derive(Debug, Clone, PartialEq)]
pub enum PermissionResponse {
    /// Allow this one time
    Allow,
    /// Deny this one time and cancel remaining tools in the batch
    Deny,
    /// Always allow this tool for the rest of the session
    AlwaysAllow,
    /// Always allow this specific command (for Bash tool only)
    AlwaysAllowCommand(String),
    /// Deny and cancel remaining tools, with a message sent to the model
    DenyAndCancel,
}

impl PermissionResponse {
    /// Build an "always allow" response with the narrowest useful scope.
    ///
    /// Bash grants are tied to the exact raw command rather than the
    /// human-readable (and potentially truncated) permission summary.
    pub fn always_allow_for(tool_name: &str, input: &serde_json::Value) -> Self {
        if tool_name == "Bash" {
            return input["command"]
                .as_str()
                .map(|command| Self::AlwaysAllowCommand(command.to_string()))
                .unwrap_or(Self::Allow);
        }
        Self::AlwaysAllow
    }
}

/// A decision returned by an `on_permission_check` hook.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HookDecision {
    Allow,
    Deny,
    Ask,
}

#[derive(Debug, Deserialize)]
struct HookVerdict {
    decision: HookDecision,
    #[serde(default)]
    reason: Option<String>,
}

/// Parse a hook's stdout. Empty output is "no opinion"; anything else must
/// be the documented JSON object.
pub fn parse_hook_verdict(output: &str) -> Result<Option<(HookDecision, Option<String>)>, String> {
    let output = output.trim();
    if output.is_empty() {
        return Ok(None);
    }
    let verdict: HookVerdict = serde_json::from_str(output)
        .map_err(|error| format!("hook output is not a decision object: {error}"))?;
    Ok(Some((verdict.decision, verdict.reason)))
}

/// The proposed decision as a hook sees it.
pub fn proposed_decision(result: &PermissionResult) -> &'static str {
    match result {
        PermissionResult::Allow => "allow",
        PermissionResult::Deny(_) => "deny",
        PermissionResult::Ask { .. } => "ask",
    }
}

/// Fold hook verdicts into the checker's result. The most restrictive
/// verdict wins: any deny denies, any ask escalates an allow to a prompt,
/// and allow only clears a prompt. A configured or mode deny is final and
/// no hook can lift it.
pub fn apply_hook_verdicts(
    tool_name: &str,
    input: &serde_json::Value,
    result: PermissionResult,
    verdicts: &[(String, HookDecision, Option<String>)],
) -> PermissionResult {
    if let PermissionResult::Deny(_) = result {
        return result;
    }
    if let Some((name, _, reason)) = verdicts
        .iter()
        .find(|(_, decision, _)| *decision == HookDecision::Deny)
    {
        let reason = reason.as_deref().unwrap_or("no reason given");
        return PermissionResult::Deny(format!("blocked by hook {name}: {reason}"));
    }
    if verdicts
        .iter()
        .any(|(_, decision, _)| *decision == HookDecision::Ask)
    {
        return match result {
            PermissionResult::Ask { .. } => result,
            _ => PermissionChecker::ask_for(tool_name, input),
        };
    }
    if verdicts
        .iter()
        .any(|(_, decision, _)| *decision == HookDecision::Allow)
    {
        return PermissionResult::Allow;
    }
    result
}

/// A mode plus its rules: everything a checker needs, passed as one value
/// so sub-agents inherit both together.
#[derive(Debug, Clone, Default)]
pub struct PermissionPolicy {
    pub mode: PermissionMode,
    pub rules: PermissionRules,
}

impl PermissionPolicy {
    pub fn new(mode: PermissionMode, rules: PermissionRules) -> Self {
        Self { mode, rules }
    }

    pub fn checker(&self) -> PermissionChecker {
        PermissionChecker::new(self.mode).with_rules(self.rules.clone())
    }
}

pub struct PermissionChecker {
    mode: PermissionMode,
    /// Configured allow/deny/ask rules, evaluated before the mode.
    rules: PermissionRules,
    /// Tools the user has "always allowed" this session
    session_allows: std::collections::HashSet<String>,
    /// Specific bash commands the user has "always allowed" this session
    bash_command_allows: std::collections::HashSet<String>,
}

impl PermissionChecker {
    pub fn new(mode: PermissionMode) -> Self {
        Self {
            mode,
            rules: PermissionRules::default(),
            session_allows: std::collections::HashSet::new(),
            bash_command_allows: std::collections::HashSet::new(),
        }
    }

    pub fn with_rules(mut self, rules: PermissionRules) -> Self {
        self.rules = rules;
        self
    }

    pub fn mode(&self) -> PermissionMode {
        self.mode
    }

    /// The prompt a tool call would show if it needed confirmation.
    pub(crate) fn ask_for(tool_name: &str, input: &serde_json::Value) -> PermissionResult {
        match tool_name {
            "Bash" => {
                let cmd = input["command"].as_str().unwrap_or("");
                PermissionResult::Ask {
                    message: format!("bash: {}", truncate(cmd, 80)),
                    diff: None,
                }
            }
            "Write" => {
                let path = input["file_path"].as_str().unwrap_or("?");
                PermissionResult::Ask {
                    message: format!("write: {path}"),
                    diff: None,
                }
            }
            "Edit" => {
                let path = input["file_path"].as_str().unwrap_or("?");
                let old_string = input["old_string"].as_str().unwrap_or("");
                let new_string = input["new_string"].as_str().unwrap_or("");
                let diff = if !old_string.is_empty() && !new_string.is_empty() {
                    Some(generate_diff(old_string, new_string, path))
                } else {
                    None
                };
                PermissionResult::Ask {
                    message: format!("edit: {path}"),
                    diff,
                }
            }
            "WebFetch" => {
                let url = input["url"].as_str().unwrap_or("?");
                PermissionResult::Ask {
                    message: format!("fetch: {url}"),
                    diff: None,
                }
            }
            _ => PermissionResult::Ask {
                message: tool_name.to_string(),
                diff: None,
            },
        }
    }

    /// Record that the user chose "always allow" for a tool.
    pub fn always_allow(&mut self, tool_name: &str) {
        self.session_allows.insert(tool_name.to_string());
    }

    /// Record that the user chose "always allow" for a specific bash command.
    pub fn always_allow_command(&mut self, cmd: &str) {
        self.bash_command_allows.insert(cmd.to_string());
    }

    /// Clear permissions granted for the previous conversation.
    pub fn reset_session(&mut self) {
        self.session_allows.clear();
        self.bash_command_allows.clear();
    }

    /// Check whether a tool invocation should be allowed.
    pub fn check(
        &self,
        tool_name: &str,
        input: &serde_json::Value,
        is_read_only: bool,
    ) -> PermissionResult {
        // Configured deny rules win over everything, including session
        // grants and bypass mode.
        if let Some(rule) = PermissionRules::first_match(&self.rules.deny, tool_name, input) {
            return PermissionResult::Deny(format!(
                "blocked by permission rule `{}`",
                rule.as_str()
            ));
        }

        // Session-level always-allow overrides
        if self.session_allows.contains(tool_name) {
            return PermissionResult::Allow;
        }

        // Command-specific allows for Bash
        if tool_name == "Bash" {
            if let Some(cmd) = input["command"].as_str() {
                if self.bash_command_allows.contains(cmd) {
                    return PermissionResult::Allow;
                }
            }
        }

        // Configured ask rules force a prompt even where the mode would
        // auto-allow; configured allow rules skip the prompt the mode would
        // show. Plan mode's write denial still applies to allow rules.
        if PermissionRules::first_match(&self.rules.ask, tool_name, input).is_some() {
            return Self::ask_for(tool_name, input);
        }
        if PermissionRules::first_match(&self.rules.allow, tool_name, input).is_some()
            && (is_read_only || self.mode != PermissionMode::Plan)
        {
            return PermissionResult::Allow;
        }

        match self.mode {
            PermissionMode::Bypass => PermissionResult::Allow,

            PermissionMode::Plan => {
                if is_read_only {
                    PermissionResult::Allow
                } else {
                    PermissionResult::Deny("Plan mode: write operations are disabled".to_string())
                }
            }

            PermissionMode::AcceptEdits => {
                if is_read_only || tool_name == "Write" || tool_name == "Edit" {
                    PermissionResult::Allow
                } else if tool_name == "Bash" {
                    let cmd = input["command"].as_str().unwrap_or("");
                    PermissionResult::Ask {
                        message: format!("Allow bash: {}?", truncate(cmd, 80)),
                        diff: None,
                    }
                } else {
                    // AcceptEdits grants implicit approval only to file edits.
                    // Agent, MCP, and future mutating tools retain an explicit
                    // permission boundary.
                    PermissionResult::Ask {
                        message: tool_name.to_string(),
                        diff: None,
                    }
                }
            }

            PermissionMode::Default => {
                if is_read_only {
                    // Local inspection is safe and must also work for
                    // non-interactive sub-agents. Network reads retain a
                    // prompt boundary because they disclose request data.
                    if tool_name == "WebFetch" {
                        let url = input["url"].as_str().unwrap_or("?");
                        PermissionResult::Ask {
                            message: format!("fetch: {url}"),
                            diff: None,
                        }
                    } else {
                        PermissionResult::Allow
                    }
                } else {
                    match tool_name {
                        "Bash" => {
                            let cmd = input["command"].as_str().unwrap_or("");
                            PermissionResult::Ask {
                                message: format!("bash: {}", truncate(cmd, 80)),
                                diff: None,
                            }
                        }
                        "Write" => {
                            let path = input["file_path"].as_str().unwrap_or("?");
                            PermissionResult::Ask {
                                message: format!("write: {path}"),
                                diff: None,
                            }
                        }
                        "Edit" => {
                            let path = input["file_path"].as_str().unwrap_or("?");
                            let old_string = input["old_string"].as_str().unwrap_or("");
                            let new_string = input["new_string"].as_str().unwrap_or("");

                            let diff = if !old_string.is_empty() && !new_string.is_empty() {
                                Some(generate_diff(old_string, new_string, path))
                            } else {
                                None
                            };

                            PermissionResult::Ask {
                                message: format!("edit: {path}"),
                                diff,
                            }
                        }
                        _ => PermissionResult::Ask {
                            message: tool_name.to_string(),
                            diff: None,
                        },
                    }
                }
            }
        }
    }
}

fn truncate(s: &str, max: usize) -> &str {
    crate::utils::truncate_str(s, max)
}

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

    #[test]
    fn bypass_allows_everything() {
        let checker = PermissionChecker::new(PermissionMode::Bypass);
        let input = json!({"command": "rm -rf /"});
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn plan_denies_writes() {
        let checker = PermissionChecker::new(PermissionMode::Plan);
        let input = json!({"file_path": "/tmp/test"});
        assert!(matches!(
            checker.check("Write", &input, false),
            PermissionResult::Deny(_)
        ));
    }

    #[test]
    fn plan_allows_reads() {
        let checker = PermissionChecker::new(PermissionMode::Plan);
        let input = json!({"file_path": "/tmp/test"});
        assert!(matches!(
            checker.check("Read", &input, true),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn default_allows_read_only() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"pattern": "*.rs"});
        assert!(matches!(
            checker.check("Glob", &input, true),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn default_asks_for_bash() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"command": "cargo test"});
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn default_asks_for_write() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"file_path": "/tmp/test", "content": "hello"});
        assert!(matches!(
            checker.check("Write", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn accept_edits_allows_write_and_edit() {
        let checker = PermissionChecker::new(PermissionMode::AcceptEdits);
        let input = json!({"file_path": "/tmp/test"});
        assert!(matches!(
            checker.check("Write", &input, false),
            PermissionResult::Allow
        ));
        assert!(matches!(
            checker.check("Edit", &input, false),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn accept_edits_asks_for_bash() {
        let checker = PermissionChecker::new(PermissionMode::AcceptEdits);
        let input = json!({"command": "rm -rf /"});
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn accept_edits_asks_for_agent() {
        let checker = PermissionChecker::new(PermissionMode::AcceptEdits);
        let input = json!({"prompt": "run a shell command"});

        assert!(matches!(
            checker.check("Agent", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn accept_edits_asks_for_mcp_tools() {
        let checker = PermissionChecker::new(PermissionMode::AcceptEdits);
        let input = json!({"repository": "example/project"});

        assert!(matches!(
            checker.check("github__delete_repository", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn always_allow_overrides_mode() {
        let mut checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"command": "cargo test"});

        // First call should ask
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Ask { .. }
        ));

        // After always_allow, should allow
        checker.always_allow("Bash");
        assert!(matches!(
            checker.check("Bash", &input, false),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn always_allow_is_tool_specific() {
        let mut checker = PermissionChecker::new(PermissionMode::Default);
        checker.always_allow("Bash");

        let input = json!({"file_path": "/tmp/test"});
        // Write should still ask
        assert!(matches!(
            checker.check("Write", &input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn reset_session_clears_all_session_grants() {
        let mut checker = PermissionChecker::new(PermissionMode::Default);
        let bash_input = json!({"command": "cargo test"});
        let write_input = json!({"file_path": "/tmp/test"});

        checker.always_allow("Write");
        checker.always_allow_command("cargo test");
        assert!(matches!(
            checker.check("Write", &write_input, false),
            PermissionResult::Allow
        ));
        assert!(matches!(
            checker.check("Bash", &bash_input, false),
            PermissionResult::Allow
        ));

        checker.reset_session();

        assert!(matches!(
            checker.check("Write", &write_input, false),
            PermissionResult::Ask { .. }
        ));
        assert!(matches!(
            checker.check("Bash", &bash_input, false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn ask_summary_contains_command() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"command": "cargo test"});
        if let PermissionResult::Ask { message, diff: _ } = checker.check("Bash", &input, false) {
            assert!(message.contains("cargo test"));
        } else {
            panic!("expected Ask");
        }
    }

    #[test]
    fn ask_summary_contains_file_path() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"file_path": "/home/ducks/important.rs"});
        if let PermissionResult::Ask { message, diff: _ } = checker.check("Edit", &input, false) {
            assert!(message.contains("important.rs"));
        } else {
            panic!("expected Ask");
        }
    }

    #[test]
    fn edit_permission_includes_diff_when_fields_present() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({
            "file_path": "src/main.rs",
            "old_string": "let x = 1",
            "new_string": "let x = 2"
        });

        if let PermissionResult::Ask { message, diff } = checker.check("Edit", &input, false) {
            assert!(message.contains("src/main.rs"));
            assert!(
                diff.is_some(),
                "Diff should be generated when old_string and new_string are provided"
            );
            let diff_content = diff.unwrap();
            assert!(diff_content.contains("src/main.rs"));
            assert!(diff_content.contains("-let x = 1"));
            assert!(diff_content.contains("+let x = 2"));
        } else {
            panic!("expected Ask");
        }
    }

    #[test]
    fn edit_permission_no_diff_when_fields_missing() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"file_path": "src/main.rs"});

        if let PermissionResult::Ask { message, diff } = checker.check("Edit", &input, false) {
            assert!(message.contains("src/main.rs"));
            assert!(
                diff.is_none(),
                "Diff should be None when old_string/new_string are missing"
            );
        } else {
            panic!("expected Ask");
        }
    }

    #[test]
    fn default_auto_allows_read_tool() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"file_path": "src/secret.rs"});

        assert!(matches!(
            checker.check("Read", &input, true),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn default_auto_allows_grep_tool() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"pattern": "SECRET_KEY", "path": "src/"});

        assert!(matches!(
            checker.check("Grep", &input, true),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn default_auto_allows_glob_tool() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"pattern": "*.rs"});

        assert!(matches!(
            checker.check("Glob", &input, true),
            PermissionResult::Allow
        ));
    }

    fn rules(allow: &[&str], deny: &[&str], ask: &[&str]) -> PermissionRules {
        let owned = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        PermissionRules::parse(&owned(allow), &owned(deny), &owned(ask)).unwrap()
    }

    #[test]
    fn rule_parsing_accepts_bare_and_pattern_forms_and_rejects_malformed() {
        assert!(PermissionRule::parse("Read").is_ok());
        assert!(PermissionRule::parse("Bash(git *)").is_ok());
        assert!(PermissionRule::parse("*").is_ok());
        assert!(PermissionRule::parse("mcp__github__list_issues").is_ok());
        for bad in ["", "Bash(", "Bash()", "Ba sh", "Bash(git [)"] {
            assert!(PermissionRule::parse(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn pattern_rules_match_the_tool_subject() {
        let rule = PermissionRule::parse("Bash(git *)").unwrap();
        assert!(rule.matches("Bash", &json!({"command": "git status"})));
        assert!(!rule.matches("Bash", &json!({"command": "gitk"})));
        assert!(!rule.matches("Write", &json!({"command": "git status"})));
        // No subject: a pattern rule cannot match.
        assert!(!rule.matches("Bash", &json!({})));

        let paths = PermissionRule::parse("Edit(src/**)").unwrap();
        assert!(paths.matches("Edit", &json!({"file_path": "src/a/b.rs"})));
        assert!(!paths.matches("Edit", &json!({"file_path": "tests/a.rs"})));

        let any = PermissionRule::parse("*").unwrap();
        assert!(any.matches("mcp__x__y", &json!({})));
    }

    #[test]
    fn deny_rules_win_over_bypass_and_session_grants() {
        let mut checker = PermissionChecker::new(PermissionMode::Bypass).with_rules(rules(
            &[],
            &["Bash(rm -rf *)"],
            &[],
        ));
        checker.always_allow("Bash");
        checker.always_allow_command("rm -rf /");
        match checker.check("Bash", &json!({"command": "rm -rf /"}), false) {
            PermissionResult::Deny(reason) => assert!(reason.contains("Bash(rm -rf *)")),
            _ => panic!("expected Deny"),
        }
        assert!(matches!(
            checker.check("Bash", &json!({"command": "ls"}), false),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn allow_rules_skip_the_prompt_in_default_mode() {
        let checker = PermissionChecker::new(PermissionMode::Default).with_rules(rules(
            &["Bash(cargo *)", "Edit(src/**)"],
            &[],
            &[],
        ));
        assert!(matches!(
            checker.check("Bash", &json!({"command": "cargo test"}), false),
            PermissionResult::Allow
        ));
        assert!(matches!(
            checker.check("Bash", &json!({"command": "rm x"}), false),
            PermissionResult::Ask { .. }
        ));
        assert!(matches!(
            checker.check("Edit", &json!({"file_path": "src/lib.rs"}), false),
            PermissionResult::Allow
        ));
        assert!(matches!(
            checker.check("Edit", &json!({"file_path": "README.md"}), false),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn allow_rules_do_not_override_plan_mode_writes() {
        let checker =
            PermissionChecker::new(PermissionMode::Plan).with_rules(rules(&["Write"], &[], &[]));
        assert!(matches!(
            checker.check("Write", &json!({"file_path": "x"}), false),
            PermissionResult::Deny(_)
        ));
    }

    #[test]
    fn ask_rules_force_a_prompt_where_the_mode_would_allow() {
        let checker = PermissionChecker::new(PermissionMode::AcceptEdits).with_rules(rules(
            &[],
            &[],
            &["Edit(Cargo.toml)", "Read(.env*)"],
        ));
        match checker.check("Edit", &json!({"file_path": "Cargo.toml"}), false) {
            PermissionResult::Ask { message, .. } => assert!(message.contains("Cargo.toml")),
            _ => panic!("expected Ask"),
        }
        assert!(matches!(
            checker.check("Edit", &json!({"file_path": "src/main.rs"}), false),
            PermissionResult::Allow
        ));
        assert!(matches!(
            checker.check("Read", &json!({"file_path": ".env.local"}), true),
            PermissionResult::Ask { .. }
        ));
    }

    #[test]
    fn ask_rules_yield_to_a_session_always_allow() {
        let mut checker = PermissionChecker::new(PermissionMode::Default).with_rules(rules(
            &[],
            &[],
            &["Bash(cargo *)"],
        ));
        assert!(matches!(
            checker.check("Bash", &json!({"command": "cargo test"}), false),
            PermissionResult::Ask { .. }
        ));
        checker.always_allow_command("cargo test");
        assert!(matches!(
            checker.check("Bash", &json!({"command": "cargo test"}), false),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn hook_verdict_parsing_accepts_empty_and_documented_json_only() {
        assert_eq!(parse_hook_verdict("  \n").unwrap(), None);
        assert_eq!(
            parse_hook_verdict(r#"{"decision":"deny","reason":"nope"}"#).unwrap(),
            Some((HookDecision::Deny, Some("nope".to_string())))
        );
        assert_eq!(
            parse_hook_verdict(r#"{"decision":"allow"}"#).unwrap(),
            Some((HookDecision::Allow, None))
        );
        assert!(parse_hook_verdict("allow").is_err());
        assert!(parse_hook_verdict(r#"{"decision":"maybe"}"#).is_err());
    }

    #[test]
    fn hook_verdicts_fold_to_the_most_restrictive_and_never_lift_a_deny() {
        let input = json!({"command": "ls"});
        let verdict = |d: HookDecision| ("h".to_string(), d, Some("r".to_string()));

        // deny beats allow and ask
        match apply_hook_verdicts(
            "Bash",
            &input,
            PermissionResult::Allow,
            &[verdict(HookDecision::Allow), verdict(HookDecision::Deny)],
        ) {
            PermissionResult::Deny(reason) => assert!(reason.contains("blocked by hook h: r")),
            _ => panic!("expected Deny"),
        }
        // ask escalates allow
        assert!(matches!(
            apply_hook_verdicts(
                "Bash",
                &input,
                PermissionResult::Allow,
                &[verdict(HookDecision::Ask)]
            ),
            PermissionResult::Ask { .. }
        ));
        // allow clears ask
        let ask = PermissionChecker::ask_for("Bash", &input);
        assert!(matches!(
            apply_hook_verdicts("Bash", &input, ask, &[verdict(HookDecision::Allow)]),
            PermissionResult::Allow
        ));
        // a configured deny is final
        assert!(matches!(
            apply_hook_verdicts(
                "Bash",
                &input,
                PermissionResult::Deny("rule".into()),
                &[verdict(HookDecision::Allow)]
            ),
            PermissionResult::Deny(_)
        ));
        // no verdicts: unchanged
        assert!(matches!(
            apply_hook_verdicts("Bash", &input, PermissionResult::Allow, &[]),
            PermissionResult::Allow
        ));
    }

    #[test]
    fn default_prompts_for_webfetch_tool() {
        let checker = PermissionChecker::new(PermissionMode::Default);
        let input = json!({"url": "https://example.com/api"});

        if let PermissionResult::Ask { message, diff } = checker.check("WebFetch", &input, true) {
            assert!(message.contains("https://example.com/api"));
            assert!(diff.is_none());
        } else {
            panic!("expected Ask for WebFetch tool");
        }
    }
}