claude_settings 0.3.4

A library for reading and writing Claude Code settings on Unix-like systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! Structured permission parsing, querying, and mutation.
//!
//! This module provides a structured representation of Claude Code permission
//! patterns, enabling easy querying and mutation of permission rules.
//!
//! ## Permission Pattern Format
//!
//! Claude Code permissions follow these formats:
//! - `ToolName` - Matches all uses of a tool
//! - `ToolName(pattern)` - Matches tool uses with a specific pattern
//! - `ToolName(prefix:*)` - Matches tool uses with a wildcard prefix
//! - `mcp__server__tool` - MCP tool permissions
//!
//! ## Examples
//!
//! ```rust
//! use claude_settings::permission::{Permission, PermissionRule, PermissionSet};
//!
//! // Parse a permission pattern
//! let perm = Permission::parse("Bash(git status:*)").unwrap();
//! assert_eq!(perm.tool(), "Bash");
//! assert!(perm.matches("Bash", Some("git status --verbose")));
//!
//! // Create a permission set
//! let set = PermissionSet::new()
//!     .allow(Permission::parse("Bash(git:*)").unwrap())
//!     .deny(Permission::parse("Read(.env)").unwrap());
//!
//! // Query permissions
//! assert_eq!(set.check("Bash", Some("git status")), PermissionRule::Allow);
//! assert_eq!(set.check("Read", Some(".env")), PermissionRule::Deny);
//! ```

use std::fmt;
use std::str::FromStr;

use regex::Regex;
use serde::{Deserialize, Serialize};

use tracing::{Level, instrument};

use crate::error::{Result, SettingsError};
use crate::types::Permissions;

/// The rule applied to a permission (allow, ask, or deny).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PermissionRule {
    /// Permission is granted without confirmation.
    Allow,
    /// Permission requires user confirmation.
    Ask,
    /// Permission is explicitly denied.
    Deny,
    /// No rule matches (default behavior applies).
    #[default]
    Unset,
}

/// A structured representation of a Claude Code permission pattern.
///
/// Permissions can match:
/// - A tool by name only (e.g., `Edit`)
/// - A tool with an exact pattern (e.g., `Read(.env)`)
/// - A tool with a wildcard pattern (e.g., `Bash(git:*)`)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Permission {
    /// The tool name (e.g., "Bash", "Read", "Edit").
    tool: String,
    /// The pattern to match against (if any).
    pattern: Option<PermissionPattern>,
}

/// Pattern matching mode for permissions.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PermissionPattern {
    /// Exact match required.
    Exact(String),
    /// Prefix match with wildcard (e.g., "git:*" matches "git status").
    Prefix(String),
    /// Glob-style pattern (for file paths).
    Glob(String),
}

impl Permission {
    /// Creates a new permission for a tool with no pattern (matches all uses).
    #[instrument(level = Level::TRACE, skip(name))]
    pub fn for_tool(name: impl Into<String>) -> Self {
        Self {
            tool: name.into(),
            pattern: None,
        }
    }

    /// Creates a new permission with an exact pattern match.
    #[instrument(level = Level::TRACE, skip(tool, pattern))]
    pub fn exact(tool: impl Into<String>, pattern: impl Into<String>) -> Self {
        Self {
            tool: tool.into(),
            pattern: Some(PermissionPattern::Exact(pattern.into())),
        }
    }

    /// Creates a new permission with a prefix wildcard match.
    #[instrument(level = Level::TRACE, skip(tool, prefix))]
    pub fn prefix(tool: impl Into<String>, prefix: impl Into<String>) -> Self {
        Self {
            tool: tool.into(),
            pattern: Some(PermissionPattern::Prefix(prefix.into())),
        }
    }

    /// Creates a new permission with a glob pattern match.
    #[instrument(level = Level::TRACE, skip(tool, glob))]
    pub fn glob(tool: impl Into<String>, glob: impl Into<String>) -> Self {
        Self {
            tool: tool.into(),
            pattern: Some(PermissionPattern::Glob(glob.into())),
        }
    }

    /// Parses a permission from a string pattern.
    ///
    /// Supported formats:
    /// - `ToolName` - matches all uses of the tool
    /// - `ToolName(pattern)` - exact pattern match
    /// - `ToolName(prefix:*)` - prefix wildcard match
    /// - `ToolName(glob:**/*.rs)` - glob pattern match
    #[instrument(level = Level::TRACE)]
    pub fn parse(s: &str) -> Result<Self> {
        let s = s.trim();

        // Check for pattern in parentheses
        if let Some(paren_start) = s.find('(') {
            if !s.ends_with(')') {
                return Err(SettingsError::InvalidPermission(format!(
                    "malformed permission pattern: {}",
                    s
                )));
            }

            let tool = s[..paren_start].to_string();
            let pattern_str = &s[paren_start + 1..s.len() - 1];

            if tool.is_empty() {
                return Err(SettingsError::InvalidPermission(
                    "empty tool name".to_string(),
                ));
            }

            let pattern = if let Some(prefix) = pattern_str.strip_suffix(":*") {
                // Prefix wildcard pattern
                PermissionPattern::Prefix(prefix.to_string())
            } else if pattern_str.contains('*') || pattern_str.contains("**") {
                // Glob pattern
                PermissionPattern::Glob(pattern_str.to_string())
            } else {
                // Exact pattern
                PermissionPattern::Exact(pattern_str.to_string())
            };

            Ok(Self {
                tool,
                pattern: Some(pattern),
            })
        } else {
            // Tool-only permission
            if s.is_empty() {
                return Err(SettingsError::InvalidPermission(
                    "empty permission".to_string(),
                ));
            }
            Ok(Self::for_tool(s))
        }
    }

    /// Returns the tool name.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn tool(&self) -> &str {
        &self.tool
    }

    /// Returns the pattern, if any.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn pattern(&self) -> Option<&PermissionPattern> {
        self.pattern.as_ref()
    }

    /// Returns true if this permission matches the given tool and argument.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn matches(&self, tool: &str, arg: Option<&str>) -> bool {
        if self.tool != tool {
            return false;
        }

        match (&self.pattern, arg) {
            // No pattern = matches all uses of this tool
            (None, _) => true,
            // Pattern but no arg = no match
            (Some(_), None) => false,
            // Both pattern and arg
            (Some(pattern), Some(arg)) => pattern.matches(arg),
        }
    }

    /// Converts this permission back to its string representation.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn to_pattern_string(&self) -> String {
        match &self.pattern {
            None => self.tool.clone(),
            Some(PermissionPattern::Exact(p)) => format!("{}({})", self.tool, p),
            Some(PermissionPattern::Prefix(p)) => format!("{}({}:*)", self.tool, p),
            Some(PermissionPattern::Glob(p)) => format!("{}({})", self.tool, p),
        }
    }
}

impl PermissionPattern {
    /// Returns true if this pattern matches the given argument.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn matches(&self, arg: &str) -> bool {
        match self {
            PermissionPattern::Exact(pattern) => arg == pattern,
            PermissionPattern::Prefix(prefix) => {
                arg == prefix || arg.starts_with(&format!("{} ", prefix))
            }
            PermissionPattern::Glob(glob) => glob_matches(glob, arg),
        }
    }
}

impl FromStr for Permission {
    type Err = SettingsError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Permission::parse(s)
    }
}

impl From<&str> for Permission {
    fn from(value: &str) -> Self {
        Self::parse(value).unwrap_or_else(|_| Self {
            // TODO(eliot): Is this always valid? We should consider any string a tool. We can detect it's
            // invalid if it's an empy string?
            tool: value.to_string(),
            pattern: None,
        })
    }
}

impl fmt::Display for Permission {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_pattern_string())
    }
}

impl Serialize for Permission {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_pattern_string())
    }
}

impl<'de> Deserialize<'de> for Permission {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Permission::parse(&s).map_err(serde::de::Error::custom)
    }
}

/// A set of permissions with rules for allow, ask, and deny.
///
/// This provides an easy-to-use API for querying and mutating permissions.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PermissionSet {
    /// The default permission mode (e.g., "default", "bypassPermissions", "plan").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    default_mode: Option<String>,
    /// Permissions that are allowed without confirmation.
    #[serde(default)]
    allow: Vec<Permission>,
    /// Permissions that require confirmation.
    #[serde(default)]
    ask: Vec<Permission>,
    /// Permissions that are denied.
    #[serde(default)]
    deny: Vec<Permission>,
}

impl PermissionSet {
    /// Creates a new empty permission set.
    #[instrument(level = Level::TRACE)]
    pub fn new() -> Self {
        Self::default()
    }

    #[instrument(level = Level::TRACE, skip(self))]
    pub fn is_empty(&self) -> bool {
        self.default_mode.is_none()
            && self.allow.is_empty()
            && self.deny.is_empty()
            && self.ask.is_empty()
    }

    /// Sets the default permission mode (builder pattern).
    #[instrument(level = Level::TRACE, skip(self, mode))]
    pub fn with_default_mode(mut self, mode: impl Into<String>) -> Self {
        self.default_mode = Some(mode.into());
        self
    }

    /// Returns the default permission mode, if set.
    pub fn default_mode(&self) -> Option<&str> {
        self.default_mode.as_deref()
    }

    /// Sets the default permission mode in place.
    #[instrument(level = Level::TRACE, skip(self, mode))]
    pub fn set_default_mode(&mut self, mode: impl Into<String>) -> &mut Self {
        self.default_mode = Some(mode.into());
        self
    }

    /// Creates a permission set from a Permissions struct.
    #[instrument(level = Level::TRACE)]
    pub fn from_permissions(perms: &Permissions) -> Result<Self> {
        let mut set = Self::new();

        for pattern in &perms.allow {
            set.allow.push(Permission::parse(pattern)?);
        }
        for pattern in &perms.ask {
            set.ask.push(Permission::parse(pattern)?);
        }
        for pattern in &perms.deny {
            set.deny.push(Permission::parse(pattern)?);
        }

        Ok(set)
    }

    /// Converts this permission set to a Permissions struct.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn to_permissions(&self) -> Permissions {
        Permissions {
            allow: self.allow.iter().map(|p| p.to_pattern_string()).collect(),
            ask: self.ask.iter().map(|p| p.to_pattern_string()).collect(),
            deny: self.deny.iter().map(|p| p.to_pattern_string()).collect(),
        }
    }

    /// Adds a permission to the allow list.
    #[instrument(level = Level::TRACE, skip(self, perm))]
    pub fn allow(mut self, perm: impl Into<Permission>) -> Self {
        let perm = perm.into();
        if !self.allow.contains(&perm) {
            self.allow.push(perm);
        }
        self
    }

    /// Adds a permission to the ask list.
    #[instrument(level = Level::TRACE, skip(self, perm))]
    pub fn ask(mut self, perm: impl Into<Permission>) -> Self {
        let perm = perm.into();
        if !self.ask.contains(&perm) {
            self.ask.push(perm);
        }
        self
    }

    /// Adds a permission to the deny list.
    #[instrument(level = Level::TRACE, skip(self, perm))]
    pub fn deny(mut self, perm: impl Into<Permission>) -> Self {
        let perm = perm.into();
        if !self.deny.contains(&perm) {
            self.deny.push(perm);
        }
        self
    }

    /// Adds a permission to the allow list in place.
    #[instrument(level = Level::TRACE, skip(self, perm))]
    pub fn insert_allow(&mut self, perm: impl Into<Permission>) -> &mut Self {
        let perm = perm.into();
        if !self.allow.contains(&perm) {
            self.allow.push(perm);
        }
        self
    }

    /// Adds a permission to the ask list in place.
    #[instrument(level = Level::TRACE, skip(self, perm))]
    pub fn insert_ask(&mut self, perm: impl Into<Permission>) -> &mut Self {
        let perm = perm.into();
        if !self.ask.contains(&perm) {
            self.ask.push(perm);
        }
        self
    }

    /// Adds a permission to the deny list in place.
    #[instrument(level = Level::TRACE, skip(self, perm))]
    pub fn insert_deny(&mut self, perm: impl Into<Permission>) -> &mut Self {
        let perm = perm.into();
        if !self.deny.contains(&perm) {
            self.deny.push(perm);
        }
        self
    }

    /// Removes a permission from the allow list.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn remove_allow(&mut self, perm: &Permission) -> &mut Self {
        self.allow.retain(|p| p != perm);
        self
    }

    /// Removes a permission from the ask list.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn remove_ask(&mut self, perm: &Permission) -> &mut Self {
        self.ask.retain(|p| p != perm);
        self
    }

    /// Removes a permission from the deny list.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn remove_deny(&mut self, perm: &Permission) -> &mut Self {
        self.deny.retain(|p| p != perm);
        self
    }

    /// Removes a permission from all lists.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn remove(&mut self, perm: &Permission) -> &mut Self {
        self.remove_allow(perm).remove_ask(perm).remove_deny(perm)
    }

    /// Checks the permission rule for a given tool and argument.
    ///
    /// Returns the first matching rule in order: Deny > Ask > Allow > Unset
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn check(&self, tool: &str, arg: Option<&str>) -> PermissionRule {
        // Deny takes highest precedence
        for perm in &self.deny {
            if perm.matches(tool, arg) {
                return PermissionRule::Deny;
            }
        }

        // Ask takes second precedence
        for perm in &self.ask {
            if perm.matches(tool, arg) {
                return PermissionRule::Ask;
            }
        }

        // Allow takes third precedence
        for perm in &self.allow {
            if perm.matches(tool, arg) {
                return PermissionRule::Allow;
            }
        }

        PermissionRule::Unset
    }

    /// Returns true if the given tool/arg is explicitly allowed.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn is_allowed(&self, tool: &str, arg: Option<&str>) -> bool {
        self.check(tool, arg) == PermissionRule::Allow
    }

    /// Returns true if the given tool/arg is explicitly denied.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn is_denied(&self, tool: &str, arg: Option<&str>) -> bool {
        self.check(tool, arg) == PermissionRule::Deny
    }

    /// Returns true if the given tool/arg requires asking.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn requires_ask(&self, tool: &str, arg: Option<&str>) -> bool {
        self.check(tool, arg) == PermissionRule::Ask
    }

    /// Returns all allow permissions.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn allowed(&self) -> &[Permission] {
        &self.allow
    }

    /// Returns all ask permissions.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn asking(&self) -> &[Permission] {
        &self.ask
    }

    /// Returns all deny permissions.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn denied(&self) -> &[Permission] {
        &self.deny
    }

    /// Returns all permissions for a specific tool.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn for_tool(&self, tool: &str) -> ToolPermissions {
        ToolPermissions {
            tool: tool.to_string(),
            allow: self
                .allow
                .iter()
                .filter(|p| p.tool() == tool)
                .cloned()
                .collect(),
            ask: self
                .ask
                .iter()
                .filter(|p| p.tool() == tool)
                .cloned()
                .collect(),
            deny: self
                .deny
                .iter()
                .filter(|p| p.tool() == tool)
                .cloned()
                .collect(),
        }
    }

    /// Clears all permissions and resets the default mode.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn clear(&mut self) {
        self.default_mode = None;
        self.allow.clear();
        self.ask.clear();
        self.deny.clear();
    }

    /// Merges another permission set into this one.
    ///
    /// The `other` set takes precedence (its rules are added first in each list).
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn merge(&self, other: &Self) -> Self {
        let mut this = self.clone();
        // Higher precedence default_mode wins
        if other.default_mode.is_some() {
            this.default_mode = other.default_mode.clone();
        }
        // Add other's permissions, avoiding duplicates
        for perm in &other.allow {
            if !this.allow.contains(perm) {
                this.allow.push(perm.clone());
            }
        }
        for perm in &other.ask {
            if !this.ask.contains(perm) {
                this.ask.push(perm.clone());
            }
        }
        for perm in &other.deny {
            if !this.deny.contains(perm) {
                this.deny.push(perm.clone());
            }
        }
        this
    }
}

/// Permissions filtered for a specific tool.
#[derive(Debug, Clone)]
pub struct ToolPermissions {
    /// The tool name.
    pub tool: String,
    /// Allow permissions for this tool.
    pub allow: Vec<Permission>,
    /// Ask permissions for this tool.
    pub ask: Vec<Permission>,
    /// Deny permissions for this tool.
    pub deny: Vec<Permission>,
}

impl ToolPermissions {
    /// Checks the permission rule for a given argument.
    #[instrument(level = Level::TRACE, skip(self))]
    pub fn check(&self, arg: Option<&str>) -> PermissionRule {
        for perm in &self.deny {
            if perm.matches(&self.tool, arg) {
                return PermissionRule::Deny;
            }
        }
        for perm in &self.ask {
            if perm.matches(&self.tool, arg) {
                return PermissionRule::Ask;
            }
        }
        for perm in &self.allow {
            if perm.matches(&self.tool, arg) {
                return PermissionRule::Allow;
            }
        }
        PermissionRule::Unset
    }
}

/// Simple glob matching for file paths.
fn glob_matches(pattern: &str, path: &str) -> bool {
    // Convert glob to regex
    let regex_pattern = pattern
        .replace('.', "\\.")
        .replace("**", "<<<DOUBLESTAR>>>")
        .replace('*', "[^/]*")
        .replace("<<<DOUBLESTAR>>>", ".*")
        .replace('?', ".");

    let regex_pattern = format!("^{}$", regex_pattern);

    Regex::new(&regex_pattern)
        .map(|re| re.is_match(path))
        .unwrap_or(false)
}

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

    #[test]
    fn test_parse_tool_only() {
        let perm = Permission::parse("Edit").unwrap();
        assert_eq!(perm.tool(), "Edit");
        assert!(perm.pattern().is_none());
        assert!(perm.matches("Edit", None));
        assert!(perm.matches("Edit", Some("anything")));
        assert!(!perm.matches("Read", None));
    }

    #[test]
    fn test_parse_exact_pattern() {
        let perm = Permission::parse("Read(.env)").unwrap();
        assert_eq!(perm.tool(), "Read");
        assert!(matches!(perm.pattern(), Some(PermissionPattern::Exact(_))));
        assert!(perm.matches("Read", Some(".env")));
        assert!(!perm.matches("Read", Some(".env.local")));
        assert!(!perm.matches("Read", None));
    }

    #[test]
    fn test_parse_prefix_wildcard() {
        let perm = Permission::parse("Bash(git:*)").unwrap();
        assert_eq!(perm.tool(), "Bash");
        assert!(matches!(perm.pattern(), Some(PermissionPattern::Prefix(_))));
        assert!(perm.matches("Bash", Some("git")));
        assert!(perm.matches("Bash", Some("git status")));
        assert!(perm.matches("Bash", Some("git commit -m 'test'")));
        assert!(!perm.matches("Bash", Some("gitk")));
        assert!(!perm.matches("Bash", Some("npm install")));
    }

    #[test]
    fn test_parse_glob_pattern() {
        let perm = Permission::parse("Read(**/*.rs)").unwrap();
        assert_eq!(perm.tool(), "Read");
        assert!(matches!(perm.pattern(), Some(PermissionPattern::Glob(_))));
        assert!(perm.matches("Read", Some("src/main.rs")));
        assert!(perm.matches("Read", Some("lib/utils/helper.rs")));
        assert!(!perm.matches("Read", Some("src/main.py")));
    }

    #[test]
    fn test_permission_display() {
        assert_eq!(Permission::for_tool("Edit").to_string(), "Edit");
        assert_eq!(Permission::exact("Read", ".env").to_string(), "Read(.env)");
        assert_eq!(Permission::prefix("Bash", "git").to_string(), "Bash(git:*)");
        assert_eq!(
            Permission::glob("Read", "**/*.rs").to_string(),
            "Read(**/*.rs)"
        );
    }

    #[test]
    fn test_permission_serde() {
        let perm = Permission::prefix("Bash", "git");
        let json = serde_json::to_string(&perm).unwrap();
        assert_eq!(json, "\"Bash(git:*)\"");

        let parsed: Permission = serde_json::from_str(&json).unwrap();
        assert_eq!(perm, parsed);
    }

    #[test]
    fn test_permission_set_check() {
        let set = PermissionSet::new()
            .allow(Permission::prefix("Bash", "git"))
            .deny(Permission::exact("Read", ".env"))
            .ask(Permission::for_tool("Write"));

        assert_eq!(set.check("Bash", Some("git status")), PermissionRule::Allow);
        assert_eq!(set.check("Read", Some(".env")), PermissionRule::Deny);
        assert_eq!(set.check("Write", Some("file.txt")), PermissionRule::Ask);
        assert_eq!(set.check("Edit", None), PermissionRule::Unset);
    }

    #[test]
    fn test_permission_set_precedence() {
        let set = PermissionSet::new()
            .allow(Permission::for_tool("Bash"))
            .deny(Permission::prefix("Bash", "rm"));

        // Deny takes precedence over allow
        assert_eq!(set.check("Bash", Some("rm -rf /")), PermissionRule::Deny);
        assert_eq!(set.check("Bash", Some("ls")), PermissionRule::Allow);
    }

    #[test]
    fn test_permission_set_from_permissions() {
        let perms = Permissions {
            allow: vec!["Bash(git:*)".to_string(), "Edit".to_string()],
            ask: vec!["Write".to_string()],
            deny: vec!["Read(.env)".to_string()],
        };

        let set = PermissionSet::from_permissions(&perms).unwrap();
        assert_eq!(set.allowed().len(), 2);
        assert_eq!(set.asking().len(), 1);
        assert_eq!(set.denied().len(), 1);

        let back = set.to_permissions();
        assert_eq!(perms.allow, back.allow);
        assert_eq!(perms.ask, back.ask);
        assert_eq!(perms.deny, back.deny);
    }

    #[test]
    fn test_permission_set_for_tool() {
        let set = PermissionSet::new()
            .allow(Permission::prefix("Bash", "git"))
            .allow(Permission::prefix("Bash", "npm"))
            .deny(Permission::exact("Read", ".env"));

        let bash_perms = set.for_tool("Bash");
        assert_eq!(bash_perms.allow.len(), 2);
        assert_eq!(bash_perms.deny.len(), 0);

        let read_perms = set.for_tool("Read");
        assert_eq!(read_perms.deny.len(), 1);
    }

    #[test]
    fn test_permission_set_merge() {
        let mut base = PermissionSet::new().allow(Permission::prefix("Bash", "git"));

        let overlay = PermissionSet::new()
            .allow(Permission::prefix("Bash", "npm"))
            .deny(Permission::exact("Read", ".env"));

        base = base.merge(&overlay);

        assert_eq!(base.allowed().len(), 2);
        assert_eq!(base.denied().len(), 1);
    }

    #[test]
    fn test_default_mode_builder() {
        let set = PermissionSet::new().with_default_mode("bypassPermissions");
        assert_eq!(set.default_mode(), Some("bypassPermissions"));
        assert!(!set.is_empty());
    }

    #[test]
    fn test_default_mode_serialization() {
        let set = PermissionSet::new()
            .with_default_mode("bypassPermissions")
            .allow(Permission::prefix("Bash", "git"));
        let json = serde_json::to_string(&set).unwrap();
        assert!(json.contains("\"defaultMode\":\"bypassPermissions\""));

        let parsed: PermissionSet = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.default_mode(), Some("bypassPermissions"));
        assert_eq!(parsed.allowed().len(), 1);
    }

    #[test]
    fn test_default_mode_deserialization() {
        let json = r#"{"defaultMode": "bypassPermissions", "allow": ["Edit"]}"#;
        let set: PermissionSet = serde_json::from_str(json).unwrap();
        assert_eq!(set.default_mode(), Some("bypassPermissions"));
        assert_eq!(set.allowed().len(), 1);
    }

    #[test]
    fn test_default_mode_merge_precedence() {
        let base = PermissionSet::new().with_default_mode("default");
        let overlay = PermissionSet::new().with_default_mode("bypassPermissions");
        let merged = base.merge(&overlay);
        assert_eq!(merged.default_mode(), Some("bypassPermissions"));
    }

    #[test]
    fn test_default_mode_merge_preserves_lower() {
        let base = PermissionSet::new().with_default_mode("bypassPermissions");
        let overlay = PermissionSet::new(); // no default_mode
        let merged = base.merge(&overlay);
        assert_eq!(merged.default_mode(), Some("bypassPermissions"));
    }

    #[test]
    fn test_glob_matches() {
        assert!(glob_matches("*.rs", "main.rs"));
        assert!(!glob_matches("*.rs", "src/main.rs"));
        assert!(glob_matches("**/*.rs", "src/main.rs"));
        assert!(glob_matches("**/*.rs", "a/b/c/d.rs"));
        assert!(glob_matches("src/*.rs", "src/lib.rs"));
        assert!(!glob_matches("src/*.rs", "src/sub/lib.rs"));
        assert!(glob_matches("src/**/*.rs", "src/sub/lib.rs"));
    }
}