guardrail 0.1.0

Defensive guardrails for AI coding agents — block destructive commands via hooks
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
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Severity {
    Block,
    Warn,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Category {
    Filesystem,
    Git,
    Database,
    Kubernetes,
    Nix,
    Docker,
    Secrets,
    Terraform,
    Cloud,
    Flux,
    Akeyless,
    Process,
    Network,
    Nosql,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rule {
    pub name: String,
    pub pattern: String,
    pub severity: Severity,
    pub message: String,
    pub category: Category,
    /// Command that MUST match this rule (for testing).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_block: Option<String>,
    /// Command that must NOT match this rule (for testing).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_allow: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[must_use = "a Decision should be inspected, not discarded"]
pub enum Decision {
    Allow,
    Block { rule: String, message: String },
    Warn { rule: String, message: String },
}

// ── Display implementations ─────────────────────────────────────

impl Severity {
    /// Returns `true` for `Block` severity.
    #[must_use]
    pub const fn is_blocking(self) -> bool {
        matches!(self, Self::Block)
    }
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Block => f.write_str("block"),
            Self::Warn => f.write_str("warn"),
        }
    }
}

impl Category {
    /// Returns a slice of all known categories.
    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::Filesystem, Self::Git, Self::Database, Self::Kubernetes,
            Self::Nix, Self::Docker, Self::Secrets, Self::Terraform,
            Self::Cloud, Self::Flux, Self::Akeyless, Self::Process,
            Self::Network, Self::Nosql,
        ]
    }
}

impl fmt::Display for Category {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::Filesystem => "filesystem",
            Self::Git => "git",
            Self::Database => "database",
            Self::Kubernetes => "kubernetes",
            Self::Nix => "nix",
            Self::Docker => "docker",
            Self::Secrets => "secrets",
            Self::Terraform => "terraform",
            Self::Cloud => "cloud",
            Self::Flux => "flux",
            Self::Akeyless => "akeyless",
            Self::Process => "process",
            Self::Network => "network",
            Self::Nosql => "nosql",
        };
        f.write_str(s)
    }
}

impl FromStr for Severity {
    type Err = ParseEnumError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "block" => Ok(Self::Block),
            "warn" => Ok(Self::Warn),
            _ => Err(ParseEnumError {
                type_name: "Severity",
                value: s.to_owned(),
            }),
        }
    }
}

impl FromStr for Category {
    type Err = ParseEnumError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "filesystem" => Ok(Self::Filesystem),
            "git" => Ok(Self::Git),
            "database" => Ok(Self::Database),
            "kubernetes" => Ok(Self::Kubernetes),
            "nix" => Ok(Self::Nix),
            "docker" => Ok(Self::Docker),
            "secrets" => Ok(Self::Secrets),
            "terraform" => Ok(Self::Terraform),
            "cloud" => Ok(Self::Cloud),
            "flux" => Ok(Self::Flux),
            "akeyless" => Ok(Self::Akeyless),
            "process" => Ok(Self::Process),
            "network" => Ok(Self::Network),
            "nosql" => Ok(Self::Nosql),
            _ => Err(ParseEnumError {
                type_name: "Category",
                value: s.to_owned(),
            }),
        }
    }
}

/// Error returned when parsing a string into a `Severity` or `Category` fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseEnumError {
    pub type_name: &'static str,
    pub value: String,
}

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

impl std::error::Error for ParseEnumError {}

impl fmt::Display for Decision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Allow => f.write_str("allow"),
            Self::Block { rule, message } => write!(f, "block [{rule}]: {message}"),
            Self::Warn { rule, message } => write!(f, "warn [{rule}]: {message}"),
        }
    }
}

impl fmt::Display for Rule {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {}: {}", self.severity, self.name, self.message)
    }
}

impl Decision {
    /// Returns `true` if this decision allows the command.
    #[must_use]
    pub const fn is_allowed(&self) -> bool {
        matches!(self, Self::Allow)
    }

    /// Returns `true` if this decision blocks the command.
    #[must_use]
    pub const fn is_blocked(&self) -> bool {
        matches!(self, Self::Block { .. })
    }

    /// Create a Block or Warn decision from a rule, based on its severity.
    #[must_use]
    pub fn from_rule(rule: &Rule) -> Self {
        match rule.severity {
            Severity::Block => Self::Block {
                rule: rule.name.clone(),
                message: rule.message.clone(),
            },
            Severity::Warn => Self::Warn {
                rule: rule.name.clone(),
                message: rule.message.clone(),
            },
            _ => Self::Allow,
        }
    }
}

// ── Builder ─────────────────────────────────────────────────────

/// Fluent builder for constructing `Rule` values (primarily for tests).
pub struct RuleBuilder {
    name: String,
    pattern: String,
    severity: Severity,
    message: String,
    category: Category,
    test_block: Option<String>,
    test_allow: Option<String>,
}

impl RuleBuilder {
    #[must_use]
    pub fn severity(mut self, s: Severity) -> Self {
        self.severity = s;
        self
    }
    #[must_use]
    pub fn message(mut self, m: impl Into<String>) -> Self {
        self.message = m.into();
        self
    }
    #[must_use]
    pub fn category(mut self, c: Category) -> Self {
        self.category = c;
        self
    }
    #[must_use]
    pub fn test_block(mut self, t: impl Into<String>) -> Self {
        self.test_block = Some(t.into());
        self
    }
    #[must_use]
    pub fn test_allow(mut self, t: impl Into<String>) -> Self {
        self.test_allow = Some(t.into());
        self
    }
    #[must_use]
    pub fn build(self) -> Rule {
        Rule {
            name: self.name,
            pattern: self.pattern,
            severity: self.severity,
            message: self.message,
            category: self.category,
            test_block: self.test_block,
            test_allow: self.test_allow,
        }
    }
}

impl Rule {
    /// Create a builder with name and pattern. Defaults: Block, Filesystem, empty message.
    #[must_use]
    pub fn builder(name: impl Into<String>, pattern: impl Into<String>) -> RuleBuilder {
        RuleBuilder {
            name: name.into(),
            pattern: pattern.into(),
            severity: Severity::Block,
            message: String::new(),
            category: Category::Filesystem,
            test_block: None,
            test_allow: None,
        }
    }
}

/// User config file (shikumi convention: ~/.config/guardrail/guardrail.yaml).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GuardrailConfig {
    /// Toggle entire categories. Missing = enabled.
    #[serde(default)]
    pub categories: BTreeMap<Category, bool>,
    /// Additional rules merged with compiled-in defaults.
    #[serde(default)]
    pub extra_rules: Vec<Rule>,
    /// Compiled-in rule names to disable.
    #[serde(default)]
    pub disabled_rules: Vec<String>,
}

impl GuardrailConfig {
    /// Whether a given category is enabled. Defaults to `true` if not configured.
    #[must_use]
    pub fn is_category_enabled(&self, cat: Category) -> bool {
        self.categories.get(&cat).copied().unwrap_or(true)
    }

    /// Whether a rule name is disabled in this config.
    #[must_use]
    pub fn is_rule_disabled(&self, name: &str) -> bool {
        self.disabled_rules.iter().any(|n| n == name)
    }
}

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

    // ── Severity ────────────────────────────────────────────────

    #[test]
    fn severity_display_all_variants() {
        assert_eq!(Severity::Block.to_string(), "block");
        assert_eq!(Severity::Warn.to_string(), "warn");
    }

    #[test]
    fn severity_serde_round_trip() {
        let json = serde_json::to_string(&Severity::Block).unwrap();
        assert_eq!(json, r#""block""#);
        let back: Severity = serde_json::from_str(&json).unwrap();
        assert_eq!(back, Severity::Block);

        let json = serde_json::to_string(&Severity::Warn).unwrap();
        assert_eq!(json, r#""warn""#);
        let back: Severity = serde_json::from_str(&json).unwrap();
        assert_eq!(back, Severity::Warn);
    }

    #[test]
    fn severity_yaml_round_trip() {
        let yaml = serde_yaml::to_string(&Severity::Block).unwrap();
        let back: Severity = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(back, Severity::Block);
    }

    #[test]
    fn severity_invalid_deserialize() {
        let result: Result<Severity, _> = serde_json::from_str(r#""invalid""#);
        assert!(result.is_err(), "invalid severity should fail to deserialize");
    }

    #[test]
    fn severity_ordering() {
        assert!(Severity::Block < Severity::Warn);
    }

    #[test]
    fn severity_is_blocking() {
        assert!(Severity::Block.is_blocking());
        assert!(!Severity::Warn.is_blocking());
    }

    #[test]
    fn severity_fromstr_round_trip() {
        for sev in [Severity::Block, Severity::Warn] {
            let s = sev.to_string();
            let parsed: Severity = s.parse().unwrap();
            assert_eq!(parsed, sev);
        }
    }

    #[test]
    fn severity_fromstr_invalid() {
        let err = "invalid".parse::<Severity>().unwrap_err();
        assert_eq!(err.type_name, "Severity");
        assert_eq!(err.value, "invalid");
        assert!(err.to_string().contains("Severity"));
    }

    // ── Category ────────────────────────────────────────────────

    #[test]
    fn category_display_all_variants() {
        let expected = [
            (Category::Filesystem, "filesystem"),
            (Category::Git, "git"),
            (Category::Database, "database"),
            (Category::Kubernetes, "kubernetes"),
            (Category::Nix, "nix"),
            (Category::Docker, "docker"),
            (Category::Secrets, "secrets"),
            (Category::Terraform, "terraform"),
            (Category::Cloud, "cloud"),
            (Category::Flux, "flux"),
            (Category::Akeyless, "akeyless"),
            (Category::Process, "process"),
            (Category::Network, "network"),
            (Category::Nosql, "nosql"),
        ];
        for (cat, name) in expected {
            assert_eq!(cat.to_string(), name, "Display mismatch for {cat:?}");
        }
    }

    #[test]
    fn category_serde_round_trip_all_variants() {
        for cat in Category::all().iter().copied() {
            let json = serde_json::to_string(&cat).unwrap();
            let back: Category = serde_json::from_str(&json).unwrap();
            assert_eq!(back, cat, "serde round-trip failed for {cat:?}");
        }
    }

    #[test]
    fn category_invalid_deserialize() {
        let result: Result<Category, _> = serde_json::from_str(r#""bogus""#);
        assert!(result.is_err());
    }

    #[test]
    fn category_ordering() {
        assert!(Category::Filesystem < Category::Git);
        assert!(Category::Network < Category::Nosql);
    }

    #[test]
    fn category_all_returns_14_variants() {
        assert_eq!(Category::all().len(), 14);
    }

    #[test]
    fn category_fromstr_round_trip() {
        for cat in Category::all().iter().copied() {
            let s = cat.to_string();
            let parsed: Category = s.parse().unwrap();
            assert_eq!(parsed, cat, "FromStr round-trip failed for {cat:?}");
        }
    }

    #[test]
    fn category_fromstr_invalid() {
        let err = "bogus".parse::<Category>().unwrap_err();
        assert_eq!(err.type_name, "Category");
        assert!(err.to_string().contains("bogus"));
    }

    // ── Decision ────────────────────────────────────────────────

    #[test]
    fn decision_display_all_variants() {
        assert_eq!(Decision::Allow.to_string(), "allow");
        assert_eq!(
            Decision::Block { rule: "r".into(), message: "m".into() }.to_string(),
            "block [r]: m"
        );
        assert_eq!(
            Decision::Warn { rule: "r".into(), message: "m".into() }.to_string(),
            "warn [r]: m"
        );
    }

    #[test]
    fn decision_equality() {
        assert_eq!(Decision::Allow, Decision::Allow);
        assert_ne!(Decision::Allow, Decision::Block { rule: "r".into(), message: "m".into() });
        assert_ne!(
            Decision::Block { rule: "a".into(), message: "m".into() },
            Decision::Block { rule: "b".into(), message: "m".into() },
        );
    }

    #[test]
    fn decision_debug() {
        let d = Decision::Block { rule: "test".into(), message: "msg".into() };
        let debug = format!("{d:?}");
        assert!(debug.contains("Block"));
        assert!(debug.contains("test"));
    }

    #[test]
    fn decision_clone() {
        let d = Decision::Warn { rule: "r".into(), message: "m".into() };
        let cloned = d.clone();
        assert_eq!(d, cloned);
    }

    #[test]
    fn decision_is_allowed() {
        assert!(Decision::Allow.is_allowed());
        assert!(!Decision::Block { rule: "r".into(), message: "m".into() }.is_allowed());
        assert!(!Decision::Warn { rule: "r".into(), message: "m".into() }.is_allowed());
    }

    #[test]
    fn decision_is_blocked() {
        assert!(!Decision::Allow.is_blocked());
        assert!(Decision::Block { rule: "r".into(), message: "m".into() }.is_blocked());
        assert!(!Decision::Warn { rule: "r".into(), message: "m".into() }.is_blocked());
    }

    #[test]
    fn decision_from_rule_block() {
        let rule = Rule::builder("test", "pat")
            .severity(Severity::Block)
            .message("danger")
            .build();
        let d = Decision::from_rule(&rule);
        assert!(d.is_blocked());
        assert_eq!(
            d,
            Decision::Block { rule: "test".into(), message: "danger".into() }
        );
    }

    #[test]
    fn decision_from_rule_warn() {
        let rule = Rule::builder("test", "pat")
            .severity(Severity::Warn)
            .message("careful")
            .build();
        let d = Decision::from_rule(&rule);
        assert!(!d.is_blocked());
        assert!(!d.is_allowed());
    }

    // ── Rule ────────────────────────────────────────────────────

    #[test]
    fn rule_serde_json_round_trip() {
        let rule = Rule::builder("test-rule", r"rm\s+-rf")
            .severity(Severity::Block)
            .message("danger")
            .category(Category::Filesystem)
            .test_block("rm -rf /")
            .test_allow("rm file.txt")
            .build();

        let json = serde_json::to_string(&rule).unwrap();
        let back: Rule = serde_json::from_str(&json).unwrap();
        assert_eq!(back.name, "test-rule");
        assert_eq!(back.pattern, r"rm\s+-rf");
        assert_eq!(back.severity, Severity::Block);
        assert_eq!(back.message, "danger");
        assert_eq!(back.category, Category::Filesystem);
        assert_eq!(back.test_block.as_deref(), Some("rm -rf /"));
        assert_eq!(back.test_allow.as_deref(), Some("rm file.txt"));
    }

    #[test]
    fn rule_serde_yaml_round_trip() {
        let rule = Rule::builder("yaml-rule", "pattern")
            .severity(Severity::Warn)
            .message("warning")
            .category(Category::Git)
            .build();

        let yaml = serde_yaml::to_string(&rule).unwrap();
        let back: Rule = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(back.name, "yaml-rule");
        assert_eq!(back.severity, Severity::Warn);
        assert!(back.test_block.is_none());
        assert!(back.test_allow.is_none());
    }

    #[test]
    fn rule_optional_test_fields_skip_serializing() {
        let rule = Rule::builder("no-test", "pat").build();
        let json = serde_json::to_string(&rule).unwrap();
        assert!(!json.contains("test_block"), "test_block should be skipped when None");
        assert!(!json.contains("test_allow"), "test_allow should be skipped when None");
    }

    #[test]
    fn rule_deserialize_missing_optional_fields() {
        let json = r#"{"name":"min","pattern":"p","severity":"block","message":"m","category":"git"}"#;
        let rule: Rule = serde_json::from_str(json).unwrap();
        assert!(rule.test_block.is_none());
        assert!(rule.test_allow.is_none());
    }

    #[test]
    fn rule_display() {
        let rule = Rule::builder("rm-rf-root", r"rm\s+-rf")
            .severity(Severity::Block)
            .message("Recursive force-delete from root")
            .build();
        assert_eq!(rule.to_string(), "[block] rm-rf-root: Recursive force-delete from root");
    }

    #[test]
    fn rule_equality() {
        let r1 = Rule::builder("a", "p").build();
        let r2 = Rule::builder("a", "p").build();
        assert_eq!(r1, r2);
    }

    // ── RuleBuilder ─────────────────────────────────────────────

    #[test]
    fn builder_defaults() {
        let rule = Rule::builder("name", "pattern").build();
        assert_eq!(rule.name, "name");
        assert_eq!(rule.pattern, "pattern");
        assert_eq!(rule.severity, Severity::Block);
        assert_eq!(rule.category, Category::Filesystem);
        assert!(rule.message.is_empty());
        assert!(rule.test_block.is_none());
        assert!(rule.test_allow.is_none());
    }

    #[test]
    fn builder_all_setters() {
        let rule = Rule::builder("n", "p")
            .severity(Severity::Warn)
            .message("msg")
            .category(Category::Docker)
            .test_block("block cmd")
            .test_allow("allow cmd")
            .build();
        assert_eq!(rule.severity, Severity::Warn);
        assert_eq!(rule.message, "msg");
        assert_eq!(rule.category, Category::Docker);
        assert_eq!(rule.test_block.as_deref(), Some("block cmd"));
        assert_eq!(rule.test_allow.as_deref(), Some("allow cmd"));
    }

    #[test]
    fn builder_accepts_string_types() {
        let name = String::from("owned-name");
        let pattern = String::from("owned-pattern");
        let rule = Rule::builder(name, pattern)
            .message(String::from("owned-message"))
            .test_block(String::from("owned-block"))
            .test_allow(String::from("owned-allow"))
            .build();
        assert_eq!(rule.name, "owned-name");
    }

    // ── GuardrailConfig ─────────────────────────────────────────

    #[test]
    fn config_default_is_empty() {
        let config = GuardrailConfig::default();
        assert!(config.categories.is_empty());
        assert!(config.extra_rules.is_empty());
        assert!(config.disabled_rules.is_empty());
    }

    #[test]
    fn config_serde_round_trip() {
        let mut config = GuardrailConfig::default();
        config.categories.insert(Category::Git, false);
        config.disabled_rules.push("rm-rf-root".into());
        config.extra_rules.push(Rule::builder("custom", "pat").build());

        let yaml = serde_yaml::to_string(&config).unwrap();
        let back: GuardrailConfig = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(back.categories.get(&Category::Git), Some(&false));
        assert_eq!(back.disabled_rules, vec!["rm-rf-root"]);
        assert_eq!(back.extra_rules.len(), 1);
    }

    #[test]
    fn config_deserialize_empty_yaml() {
        let config: GuardrailConfig = serde_yaml::from_str("{}").unwrap();
        assert!(config.categories.is_empty());
        assert!(config.extra_rules.is_empty());
        assert!(config.disabled_rules.is_empty());
    }

    #[test]
    fn config_is_category_enabled_default_true() {
        let config = GuardrailConfig::default();
        assert!(config.is_category_enabled(Category::Git));
        assert!(config.is_category_enabled(Category::Filesystem));
    }

    #[test]
    fn config_is_category_enabled_explicit_false() {
        let mut config = GuardrailConfig::default();
        config.categories.insert(Category::Git, false);
        assert!(!config.is_category_enabled(Category::Git));
        assert!(config.is_category_enabled(Category::Filesystem));
    }

    #[test]
    fn config_is_rule_disabled() {
        let mut config = GuardrailConfig::default();
        config.disabled_rules.push("rm-rf-root".into());
        assert!(config.is_rule_disabled("rm-rf-root"));
        assert!(!config.is_rule_disabled("other-rule"));
    }

    #[test]
    fn config_camel_case_field_names() {
        let yaml = r#"
disabledRules:
  - some-rule
extraRules: []
"#;
        let config: GuardrailConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.disabled_rules, vec!["some-rule"]);
    }

    #[test]
    fn rule_vec_serde_yaml() {
        let rules = vec![
            Rule::builder("r1", "p1").severity(Severity::Block).build(),
            Rule::builder("r2", "p2").severity(Severity::Warn).build(),
        ];
        let yaml = serde_yaml::to_string(&rules).unwrap();
        let back: Vec<Rule> = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(back.len(), 2);
        assert_eq!(back[0].name, "r1");
        assert_eq!(back[1].name, "r2");
    }

    // ── Invalid YAML deserialization ─────────────────────────────

    #[test]
    fn rule_invalid_severity_yaml() {
        let yaml = r#"
- name: bad
  pattern: "x"
  severity: panic
  message: "nope"
  category: git
"#;
        let result: Result<Vec<Rule>, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "invalid severity should fail deserialization");
    }

    #[test]
    fn rule_invalid_category_yaml() {
        let yaml = r#"
- name: bad
  pattern: "x"
  severity: block
  message: "nope"
  category: nonexistent
"#;
        let result: Result<Vec<Rule>, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "invalid category should fail deserialization");
    }

    #[test]
    fn rule_missing_required_field_yaml() {
        let yaml = r#"
- name: incomplete
  severity: block
"#;
        let result: Result<Vec<Rule>, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "missing required fields should fail");
    }

    #[test]
    fn config_invalid_category_key_yaml() {
        let yaml = r#"
categories:
  nonexistent: false
"#;
        let result: Result<GuardrailConfig, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "invalid category key should fail");
    }

    #[test]
    fn config_nested_invalid_extra_rule() {
        let yaml = r#"
extraRules:
  - name: bad
    pattern: "x"
    severity: invalid_severity
    message: "nope"
    category: git
"#;
        let result: Result<GuardrailConfig, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "invalid nested rule should fail");
    }
}