car-policy 0.52.1

Policy engine for Common Agent Runtime
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
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
//! Declarative, project-authored deny rules for the [`PolicyEngine`]
//! (EPIC A / task A2).
//!
//! Historically `PolicyEngine` rules were only ever registered in code —
//! the hardcoded coder prohibitions, a handful of test closures — so an
//! operator had no way to forbid a tool or parameter for *their* project
//! without patching CAR. This module adds a TOML rule format, auto-loaded
//! from a project's `.car/policies/` directory (the same `.car/`
//! convention the engine already discovers by walking up from cwd), and
//! lowers each declarative rule into a [`PolicyCheck`] closure registered
//! on a `PolicyEngine`.
//!
//! ```toml
//! # .car/policies/security.toml
//! deny_tool    = ["deploy", "rm"]
//! deny_keyword = ["DROP TABLE", "rm -rf /"]
//!
//! [[deny_tool_param]]
//! tool     = "http_request"
//! param    = "url"
//! contains = "169.254.169.254"   # block cloud metadata exfiltration
//!
//! [[deny_tool_param]]
//! tool   = "shell"
//! param  = "command"
//! equals = "shutdown"
//!
//! [[allow_tool_param]]
//! tool  = "deploy"
//! param = "target"
//! allow = ["staging", "preview"]   # any other target — or none at all — is denied
//!
//! [[deny_tool_param_matching]]
//! tool    = "http_request"
//! param   = "body"
//! matches = "sk-[A-Za-z0-9]{20,}"  # never let an API key leave in a request body
//!
//! [[rate_limit_tool]]
//! tool          = "http_request"
//! max_calls     = 10
//! interval_secs = 60.0
//! ```
//!
//! Every rule is a *prohibition*: matching an action produces a violation,
//! which — once A9 makes `PolicyEngine` violations blocking at admission —
//! refuses the proposal. Most rules say what is forbidden; `allow_tool_param`
//! inverts that and says what is *permitted*, denying everything else about
//! its tool. Loading is strict: a malformed file is a loud error, not a
//! silently-skipped rule (a dropped security rule is worse than a failed
//! boot).

use crate::{PolicyCheck, PolicyEngine};
use car_ir::Action;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::VecDeque;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// The string form of a parameter value, as every string-comparison rule in
/// this module sees it: a JSON string is compared bare, anything else by its
/// JSON rendering (`42`, `true`, `["a"]`).
fn param_string(val: &Value) -> String {
    match val {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// A single `deny_tool_param` rule: forbid calling `tool` when its `param`
/// matches a condition. Exactly one of `equals` / `contains` should be set;
/// if both are set both must match, if neither is set the rule matches any
/// call to `tool` that carries `param` at all (presence-deny).
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct DenyToolParam {
    /// Tool name the rule applies to.
    pub tool: String,
    /// Parameter key inspected on the action.
    pub param: String,
    /// Forbid when the parameter equals this JSON value exactly.
    #[serde(default)]
    pub equals: Option<Value>,
    /// Forbid when the parameter's string form contains this substring
    /// (case-sensitive).
    #[serde(default)]
    pub contains: Option<String>,
}

impl DenyToolParam {
    /// Does this rule forbid the given action?
    fn matches(&self, action: &Action) -> bool {
        if action.tool.as_deref() != Some(self.tool.as_str()) {
            return false;
        }
        let Some(val) = action.parameters.get(&self.param) else {
            return false; // param absent → nothing to forbid
        };
        // Presence-deny when no condition is given.
        if self.equals.is_none() && self.contains.is_none() {
            return true;
        }
        let mut ok = true;
        if let Some(expected) = &self.equals {
            ok &= val == expected;
        }
        if let Some(needle) = &self.contains {
            ok &= param_string(val).contains(needle);
        }
        ok
    }
}

/// A single `allow_tool_param` rule: the module's only *allowlist*, and the
/// only rule that denies an action for what it does **not** say.
///
/// When an action calls `tool`, it is denied unless it carries `param` and
/// that parameter's string form is exactly one of the entries in `allow`.
/// Being a whitelist, it fails closed in all three ways it can fail:
///
/// - the parameter is absent → denied (nothing proves the call is permitted)
/// - `allow` is empty → every call to `tool` is denied
/// - the value is present but unlisted → denied
///
/// Comparison is exact and case-sensitive. Actions for any other tool are
/// untouched — one rule governs one tool.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct AllowToolParam {
    /// Tool name the rule applies to.
    pub tool: String,
    /// Parameter key inspected on the action.
    pub param: String,
    /// The permitted values. Anything else — including nothing — is denied.
    #[serde(default)]
    pub allow: Vec<String>,
}

impl AllowToolParam {
    /// Does this rule forbid the given action?
    ///
    /// Inverted relative to [`DenyToolParam::matches`]: there, a match is the
    /// exception that forbids; here, a match is the exception that permits.
    fn denies(&self, action: &Action) -> bool {
        if action.tool.as_deref() != Some(self.tool.as_str()) {
            return false; // a different tool — this rule has no opinion
        }
        let Some(val) = action.parameters.get(&self.param) else {
            return true; // param absent → nothing to allowlist against → deny
        };
        !self.allow.contains(&param_string(val))
    }
}

/// A single `deny_tool_param_matching` rule: forbid calling `tool` when its
/// `param` matches a regex.
///
/// The content counterpart to [`DenyToolParam`], for prohibitions that no
/// fixed substring expresses — credential shapes, account numbers, an
/// address family. The match is unanchored (`Regex::is_match`), so the
/// pattern fires anywhere in the value; anchor it with `^`/`$` when that
/// matters.
///
/// Like `deny_tool_param`, an absent parameter is not a violation: this is a
/// deny rule, and it only fires on what it can see. Use `allow_tool_param`
/// when absence itself must be refused.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct DenyToolParamMatching {
    /// Tool name the rule applies to.
    pub tool: String,
    /// Parameter key inspected on the action.
    pub param: String,
    /// Regex source. Compiled once when the rule is applied — an invalid
    /// pattern denies every call to `tool` rather than vanishing.
    pub matches: String,
}

/// A single `rate_limit_tool` rule: cap how often `tool` may be called.
///
/// A sliding window — the call is denied when admitting it would make it the
/// `max_calls + 1`-th call to `tool` within the trailing `interval_secs`.
/// `max_calls = 0` denies every call.
///
/// Two behaviours are load-bearing for anyone reasoning about the cap:
///
/// - **Budget is consumed at admission, not at delivery.** A call this rule
///   admits that later fails at dispatch still occupies its slot in the
///   window. The cap bounds *attempts*, not confirmed successes — which is
///   the conservative direction for a rule whose job is to bound blast
///   radius.
/// - **A call denied *by this rule* consumes no budget.** Being refused for
///   being over the cap does not push the window further out, so a caller
///   that keeps retrying into a full window is admitted again as soon as the
///   oldest admitted call ages out.
///
/// Note the precision in that second point. [`crate::PolicyEngine::check`]
/// runs every registered check and collects all of them — it does not stop at
/// the first violation — so a call that some *other* rule refuses has already
/// passed through this one and taken its slot. An agent hammering a recipient
/// its allowlist forbids therefore burns the same budget as one sending
/// legitimately. That is the conservative direction and consistent with the
/// point above (the cap bounds attempts), but it is the opposite of what
/// "denied calls are free" suggests if you read it too broadly.
///
/// The window is per rule and per [`PolicyEngine`], starts empty, and is not
/// persisted. **On the daemon that means per WebSocket connection, not per
/// machine**: `create_session` builds a fresh `Runtime` — and so a fresh
/// engine — for every accepted connection, so two concurrent agents each get
/// their own full budget, and an agent that reconnects starts a new window
/// immediately. Size a cap for one agent-session's blast radius; it is not a
/// machine-wide quota. The `car do` assistant builds one runtime per run, so
/// there the window is the run.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct RateLimitTool {
    /// Tool name the rule applies to.
    pub tool: String,
    /// Calls permitted within the window. `0` denies every call.
    pub max_calls: u32,
    /// Window length in seconds.
    pub interval_secs: f64,
}

/// A project's declarative policy rule set — the deserialized union of
/// every `.car/policies/*.toml` file.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]
pub struct PolicyRules {
    /// Tool names that may never be invoked.
    #[serde(default)]
    pub deny_tool: Vec<String>,
    /// Substrings that, if present in any string-valued parameter of any
    /// action, forbid that action. The coarse "never let this text near a
    /// tool" guard (e.g. `rm -rf /`, SQL drops).
    #[serde(default)]
    pub deny_keyword: Vec<String>,
    /// Per-tool parameter conditions.
    #[serde(default)]
    pub deny_tool_param: Vec<DenyToolParam>,
    /// Per-tool parameter allowlists — the inverse of `deny_tool_param`.
    /// The tool is denied except for the enumerated parameter values, so a
    /// call that omits the parameter is denied too. For governed side effects
    /// where the safe set is small and enumerable, and an unrecognised value
    /// must never be attempted.
    #[serde(default)]
    pub allow_tool_param: Vec<AllowToolParam>,
    /// Per-tool parameter conditions expressed as regexes, for content
    /// prohibitions no fixed substring captures (credential shapes, account
    /// numbers).
    #[serde(default)]
    pub deny_tool_param_matching: Vec<DenyToolParamMatching>,
    /// Per-tool sliding-window call caps. Bounds how much of a side effect
    /// an agent can produce in a stretch of wall-clock time, independently of
    /// whether any single call is legitimate.
    #[serde(default)]
    pub rate_limit_tool: Vec<RateLimitTool>,
    /// Temporal rules over the run's execution trace (car#704).
    ///
    /// Authored alongside `deny_tool` deliberately, rather than in a separate
    /// spec file. They answer the same question an operator is already asking
    /// here — "what may this agent do?" — and splitting them would mean a
    /// reader has to know which of two files governs a given prohibition.
    /// `deny_tool` says *never*; a trace rule says *not yet*, *not without*, or
    /// *not until*.
    ///
    /// Unlike the other kinds, these are **stateful**: they are evaluated
    /// against what has already run, so they cannot be registered as a
    /// `PolicyCheck`, which sees one action in isolation. They would have to be
    /// enforced at dispatch by a [`car_verify::trace_policy::TraceGate`].
    ///
    /// **Nothing constructs that gate outside tests, so a trace rule loaded
    /// from a file would be enforced by nobody.** [`load_policy_dir`]
    /// therefore *rejects* a policy file carrying `[[trace_rule]]` rather than
    /// admitting a rule the runtime will silently ignore — the whole point of
    /// moving governance into declarative files is that a rule an operator
    /// writes is a rule the runtime keeps. The field stays so the type still
    /// round-trips a rule set built in memory; wire the dispatch gate and the
    /// rejection in `load_policy_dir` comes out.
    #[serde(default)]
    pub trace_rule: Vec<car_verify::trace_policy::TraceRule>,
}

impl PolicyRules {
    /// Fold another rule set into this one (used to merge multiple files).
    pub fn merge(&mut self, other: PolicyRules) {
        self.deny_tool.extend(other.deny_tool);
        self.deny_keyword.extend(other.deny_keyword);
        self.deny_tool_param.extend(other.deny_tool_param);
        self.allow_tool_param.extend(other.allow_tool_param);
        self.deny_tool_param_matching
            .extend(other.deny_tool_param_matching);
        self.rate_limit_tool.extend(other.rate_limit_tool);
        self.trace_rule.extend(other.trace_rule);
    }

    /// True when no rules are defined.
    pub fn is_empty(&self) -> bool {
        self.deny_tool.is_empty()
            && self.deny_keyword.is_empty()
            && self.deny_tool_param.is_empty()
            && self.allow_tool_param.is_empty()
            && self.deny_tool_param_matching.is_empty()
            && self.rate_limit_tool.is_empty()
            && self.trace_rule.is_empty()
    }

    /// How many rules this set holds, across every kind.
    ///
    /// Callers report this as "N project policy rules loaded", so it has to
    /// count every kind or it quietly lies. It lives here, next to
    /// [`Self::is_empty`] and [`Self::merge`], because those two already
    /// enumerate the fields by hand and a caller summing a subset from the
    /// outside is exactly how the count drifted before: the original sum in
    /// `load_project_policies` covered the first three kinds and was never
    /// revisited when more landed. Adding a field means touching these three
    /// methods together.
    pub fn len(&self) -> usize {
        self.deny_tool.len()
            + self.deny_keyword.len()
            + self.deny_tool_param.len()
            + self.allow_tool_param.len()
            + self.deny_tool_param_matching.len()
            + self.rate_limit_tool.len()
            + self.trace_rule.len()
    }

    /// Parse a single TOML document into a rule set.
    pub fn from_toml(src: &str) -> Result<PolicyRules, PolicyLoadError> {
        toml::from_str(src).map_err(|e| PolicyLoadError::Parse {
            path: None,
            message: e.to_string(),
        })
    }

    /// Register every rule in this set as a [`PolicyCheck`] on `engine`.
    ///
    /// Rule names are stable and descriptive so a violation report names
    /// the offending rule (`deny_tool:deploy`, `deny_keyword:rm -rf /`,
    /// `deny_tool_param:http_request.url`, `allow_tool_param:deploy.target`,
    /// `deny_tool_param_matching:http_request.body`,
    /// `rate_limit_tool:http_request`).
    pub fn apply(&self, engine: &mut PolicyEngine) {
        for tool in &self.deny_tool {
            let tool = tool.clone();
            let name = format!("deny_tool:{tool}");
            let desc = format!("project .car/policies deny_tool: {tool}");
            let check: PolicyCheck = Box::new(move |action: &Action, _state| {
                if action.tool.as_deref() == Some(tool.as_str()) {
                    Some(format!("tool '{tool}' is denied by project policy"))
                } else {
                    None
                }
            });
            engine.register(&name, check, &desc);
        }

        for kw in &self.deny_keyword {
            let kw = kw.clone();
            let name = format!("deny_keyword:{kw}");
            let desc = format!("project .car/policies deny_keyword: {kw}");
            let check: PolicyCheck = Box::new(move |action: &Action, _state| {
                for (k, v) in &action.parameters {
                    if param_string(v).contains(&kw) {
                        return Some(format!("parameter '{k}' contains denied keyword '{kw}'"));
                    }
                }
                None
            });
            engine.register(&name, check, &desc);
        }

        for rule in &self.deny_tool_param {
            let rule = rule.clone();
            let name = format!("deny_tool_param:{}.{}", rule.tool, rule.param);
            let desc = format!(
                "project .car/policies deny_tool_param on {}.{}",
                rule.tool, rule.param
            );
            let check: PolicyCheck = Box::new(move |action: &Action, _state| {
                if rule.matches(action) {
                    Some(format!(
                        "tool '{}' parameter '{}' is denied by project policy",
                        rule.tool, rule.param
                    ))
                } else {
                    None
                }
            });
            engine.register(&name, check, &desc);
        }

        for rule in &self.allow_tool_param {
            let rule = rule.clone();
            let name = format!("allow_tool_param:{}.{}", rule.tool, rule.param);
            let desc = format!(
                "project .car/policies allow_tool_param on {}.{}",
                rule.tool, rule.param
            );
            let check: PolicyCheck = Box::new(move |action: &Action, _state| {
                if rule.denies(action) {
                    // The offending value is deliberately absent from the
                    // message: allowlisted parameters identify people and
                    // places, and this string lands in the event log.
                    Some(format!(
                        "tool '{}' parameter '{}' is not allowlisted by project policy",
                        rule.tool, rule.param
                    ))
                } else {
                    None
                }
            });
            engine.register(&name, check, &desc);
        }

        for rule in &self.deny_tool_param_matching {
            let tool = rule.tool.clone();
            let param = rule.param.clone();
            let name = format!("deny_tool_param_matching:{tool}.{param}");
            let desc = format!("project .car/policies deny_tool_param_matching on {tool}.{param}");
            // Compiled once, here — not once per action evaluated.
            let check: PolicyCheck = match Regex::new(&rule.matches) {
                Ok(re) => Box::new(move |action: &Action, _state| {
                    if action.tool.as_deref() != Some(tool.as_str()) {
                        return None;
                    }
                    let val = action.parameters.get(&param)?;
                    if re.is_match(&param_string(val)) {
                        // Neither the matched text nor the pattern appears
                        // here: the matched text is precisely the secret the
                        // rule exists to catch, and it would be logged.
                        Some(format!(
                            "tool '{tool}' parameter '{param}' matched a denied pattern"
                        ))
                    } else {
                        None
                    }
                }),
                // Fail closed. The loader already treats a malformed rule as a
                // loud error rather than a silently-skipped one, because a
                // dropped security rule is worse than a failed boot. `apply`
                // returns `()` and cannot propagate, so denying the tool
                // outright is the equivalent posture here.
                Err(e) => {
                    let err = e.to_string();
                    Box::new(move |action: &Action, _state| {
                        if action.tool.as_deref() == Some(tool.as_str()) {
                            Some(format!(
                                "tool '{tool}' is denied: the project policy pattern for \
                                 parameter '{param}' failed to compile: {err}"
                            ))
                        } else {
                            None
                        }
                    })
                }
            };
            engine.register(&name, check, &desc);
        }

        for rule in &self.rate_limit_tool {
            let tool = rule.tool.clone();
            let max_calls = rule.max_calls as usize;
            let interval_secs = rule.interval_secs;
            // An interval that is not finite and positive (NaN, negative, or
            // too large for a `Duration`) becomes a zero-length window rather
            // than a panic: nothing is ever retained, so every call is
            // admitted. A nonsense cap is inert, not fatal — and `max_calls
            // = 0` still denies, since that check runs before any retention.
            let window = Duration::try_from_secs_f64(interval_secs).unwrap_or(Duration::ZERO);
            let name = format!("rate_limit_tool:{tool}");
            let desc = format!(
                "project .car/policies rate_limit_tool: {tool} ({max_calls}/{interval_secs}s)"
            );
            // `PolicyCheck` is `Fn`, not `FnMut`, so the window lives behind
            // interior mutability captured by the closure.
            let window_calls: Arc<Mutex<VecDeque<Instant>>> = Arc::new(Mutex::new(VecDeque::new()));
            let check: PolicyCheck = Box::new(move |action: &Action, _state| {
                if action.tool.as_deref() != Some(tool.as_str()) {
                    return None;
                }
                let now = Instant::now();
                // A poisoned mutex means some other check panicked mid-update;
                // the call history is still readable, and refusing to enforce
                // the cap is the worse failure.
                let mut calls = window_calls.lock().unwrap_or_else(|e| e.into_inner());
                while calls
                    .front()
                    .is_some_and(|t| now.duration_since(*t) >= window)
                {
                    calls.pop_front();
                }
                if calls.len() >= max_calls {
                    // Denied calls do not consume budget — nothing is pushed.
                    return Some(format!(
                        "tool '{tool}' exceeds the project rate limit of {max_calls} \
                         call(s) per {interval_secs}s"
                    ));
                }
                // Budget is consumed at admission; a call that later fails at
                // dispatch still occupies this slot.
                calls.push_back(now);
                None
            });
            engine.register(&name, check, &desc);
        }
    }
}

/// Load and merge every `*.toml` file in a `.car/policies/` directory.
///
/// Files are read in sorted order for determinism. A missing directory is
/// not an error — it yields an empty rule set (most projects have none).
/// A present-but-malformed file *is* an error: a security rule that fails
/// to parse must surface, never be silently skipped.
pub fn load_policy_dir(dir: impl AsRef<Path>) -> Result<PolicyRules, PolicyLoadError> {
    let dir = dir.as_ref();
    if !dir.exists() {
        return Ok(PolicyRules::default());
    }
    let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
        .map_err(|e| PolicyLoadError::Io {
            path: dir.to_path_buf(),
            message: e.to_string(),
        })?
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("toml"))
        .collect();
    files.sort();

    let mut merged = PolicyRules::default();
    for path in files {
        let src = std::fs::read_to_string(&path).map_err(|e| PolicyLoadError::Io {
            path: path.clone(),
            message: e.to_string(),
        })?;
        let rules = PolicyRules::from_toml(&src).map_err(|e| match e {
            PolicyLoadError::Parse { message, .. } => PolicyLoadError::Parse {
                path: Some(path.clone()),
                message,
            },
            other => other,
        })?;
        // Refuse a rule kind nothing enforces rather than loading it and
        // counting it as governance. `trace_rule` parses and would need a
        // dispatch-time `car_verify::trace_policy::TraceGate`, which nothing
        // outside tests constructs — so admitting it here would hand an
        // operator a file that reports N rules loaded while one of them is
        // inert. That is the exact failure this loader being wired up was
        // meant to end, so it fails loud and names the file.
        if !rules.trace_rule.is_empty() {
            return Err(PolicyLoadError::Unenforced {
                path: path.clone(),
                key: "trace_rule".to_string(),
            });
        }
        merged.merge(rules);
    }
    Ok(merged)
}

/// Errors raised while loading project policy rules.
#[derive(Debug, Clone)]
pub enum PolicyLoadError {
    /// A file or directory could not be read.
    Io { path: PathBuf, message: String },
    /// A TOML document failed to parse.
    Parse {
        path: Option<PathBuf>,
        message: String,
    },
    /// A file declared a rule kind this build parses but does not enforce.
    /// Loading it would report governance that never fires, so it is refused.
    Unenforced { path: PathBuf, key: String },
}

impl fmt::Display for PolicyLoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PolicyLoadError::Io { path, message } => {
                write!(f, "policy I/O error at {}: {message}", path.display())
            }
            PolicyLoadError::Parse { path, message } => match path {
                Some(p) => write!(f, "policy parse error in {}: {message}", p.display()),
                None => write!(f, "policy parse error: {message}"),
            },
            PolicyLoadError::Unenforced { path, key } => write!(
                f,
                "policy rule kind '{key}' in {} is not enforced by this build — \
                 loading it would report a rule that never fires. Remove it, or \
                 express the prohibition with a rule kind that is enforced.",
                path.display()
            ),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use car_ir::{Action, ActionType};
    use car_state::StateStore;
    use std::collections::HashMap;

    fn tool_action(tool: &str, params: HashMap<String, Value>) -> Action {
        {
            let mut a = Action::new(ActionType::ToolCall);
            a.id = "a1".to_string();
            a.tool = Some(tool.to_string());
            a.parameters = params;
            a.max_retries = 0;
            a
        }
    }

    #[test]
    fn parses_full_document() {
        let src = r#"
            deny_tool = ["deploy", "rm"]
            deny_keyword = ["DROP TABLE"]

            [[deny_tool_param]]
            tool = "http_request"
            param = "url"
            contains = "169.254.169.254"
        "#;
        let rules = PolicyRules::from_toml(src).unwrap();
        assert_eq!(rules.deny_tool, vec!["deploy", "rm"]);
        assert_eq!(rules.deny_keyword, vec!["DROP TABLE"]);
        assert_eq!(rules.deny_tool_param.len(), 1);
        assert_eq!(rules.deny_tool_param[0].tool, "http_request");
    }

    #[test]
    fn deny_tool_blocks_named_tool() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            deny_tool: vec!["deploy".to_string()],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();
        // The denied tool produces a violation...
        let v = engine.check(&tool_action("deploy", HashMap::new()), &state);
        assert_eq!(v.len(), 1);
        assert!(v[0].reason.contains("denied by project policy"));
        // ...an unrelated tool does not.
        assert!(engine
            .check(&tool_action("echo", HashMap::new()), &state)
            .is_empty());
    }

    #[test]
    fn deny_keyword_scans_params() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            deny_keyword: vec!["rm -rf /".to_string()],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();
        let params = [("command".to_string(), Value::from("sudo rm -rf / now"))].into();
        let v = engine.check(&tool_action("shell", params), &state);
        assert_eq!(v.len(), 1);
        assert!(v[0].reason.contains("denied keyword"));
    }

    #[test]
    fn deny_tool_param_contains_and_equals() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            deny_tool_param: vec![
                DenyToolParam {
                    tool: "http_request".to_string(),
                    param: "url".to_string(),
                    equals: None,
                    contains: Some("metadata".to_string()),
                },
                DenyToolParam {
                    tool: "shell".to_string(),
                    param: "command".to_string(),
                    equals: Some(Value::from("shutdown")),
                    contains: None,
                },
            ],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();

        // contains match
        let p1 = [("url".to_string(), Value::from("http://metadata.local"))].into();
        assert_eq!(
            engine.check(&tool_action("http_request", p1), &state).len(),
            1
        );
        // contains miss
        let p2 = [("url".to_string(), Value::from("http://example.com"))].into();
        assert!(engine
            .check(&tool_action("http_request", p2), &state)
            .is_empty());
        // equals match
        let p3 = [("command".to_string(), Value::from("shutdown"))].into();
        assert_eq!(engine.check(&tool_action("shell", p3), &state).len(), 1);
        // equals miss
        let p4 = [("command".to_string(), Value::from("ls"))].into();
        assert!(engine.check(&tool_action("shell", p4), &state).is_empty());
        // right param, wrong tool
        let p5 = [("command".to_string(), Value::from("shutdown"))].into();
        assert!(engine.check(&tool_action("other", p5), &state).is_empty());
    }

    #[test]
    fn allow_tool_param_permits_only_listed_values() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            allow_tool_param: vec![AllowToolParam {
                tool: "deploy".to_string(),
                param: "target".to_string(),
                allow: vec!["staging".to_string(), "preview".to_string()],
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();

        // listed value → admitted
        let p1 = [("target".to_string(), Value::from("staging"))].into();
        assert!(engine.check(&tool_action("deploy", p1), &state).is_empty());
        // unlisted value → denied
        let p2 = [("target".to_string(), Value::from("production"))].into();
        let v = engine.check(&tool_action("deploy", p2), &state);
        assert_eq!(v.len(), 1);
        assert!(v[0].reason.contains("not allowlisted"));
        // case-sensitive: a near miss is still a miss
        let p3 = [("target".to_string(), Value::from("Staging"))].into();
        assert_eq!(engine.check(&tool_action("deploy", p3), &state).len(), 1);
        // param absent → denied (the whitelist fails closed)
        assert_eq!(
            engine
                .check(&tool_action("deploy", HashMap::new()), &state)
                .len(),
            1
        );
        // a different tool is untouched
        let p4 = [("target".to_string(), Value::from("production"))].into();
        assert!(engine.check(&tool_action("echo", p4), &state).is_empty());
    }

    #[test]
    fn allow_tool_param_with_empty_list_denies_the_tool() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            allow_tool_param: vec![AllowToolParam {
                tool: "deploy".to_string(),
                param: "target".to_string(),
                allow: vec![],
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();
        let p1 = [("target".to_string(), Value::from("staging"))].into();
        assert_eq!(engine.check(&tool_action("deploy", p1), &state).len(), 1);
        assert_eq!(
            engine
                .check(&tool_action("deploy", HashMap::new()), &state)
                .len(),
            1
        );
    }

    #[test]
    fn allow_tool_param_never_echoes_the_value() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            allow_tool_param: vec![AllowToolParam {
                tool: "deploy".to_string(),
                param: "target".to_string(),
                allow: vec!["staging".to_string()],
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();
        let p = [("target".to_string(), Value::from("+15555550123"))].into();
        let v = engine.check(&tool_action("deploy", p), &state);
        assert_eq!(v.len(), 1);
        assert!(
            !v[0].reason.contains("+15555550123"),
            "the rejected value identifies a recipient and must not reach the event log"
        );
    }

    #[test]
    fn deny_tool_param_matching_fires_on_a_regex_hit() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            deny_tool_param_matching: vec![DenyToolParamMatching {
                tool: "http_request".to_string(),
                param: "body".to_string(),
                matches: "sk-[A-Za-z0-9]{6,}".to_string(),
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();

        // hit
        let p1 = [(
            "body".to_string(),
            Value::from("token sk-ABCdef123456 here"),
        )]
        .into();
        let v = engine.check(&tool_action("http_request", p1), &state);
        assert_eq!(v.len(), 1);
        assert!(v[0].reason.contains("denied pattern"));
        // miss
        let p2 = [("body".to_string(), Value::from("nothing secret"))].into();
        assert!(engine
            .check(&tool_action("http_request", p2), &state)
            .is_empty());
        // param absent → a deny rule only fires on what it can see
        assert!(engine
            .check(&tool_action("http_request", HashMap::new()), &state)
            .is_empty());
        // right param, wrong tool
        let p3 = [("body".to_string(), Value::from("sk-ABCdef123456"))].into();
        assert!(engine.check(&tool_action("other", p3), &state).is_empty());
    }

    #[test]
    fn deny_tool_param_matching_leaks_neither_match_nor_pattern() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            deny_tool_param_matching: vec![DenyToolParamMatching {
                tool: "http_request".to_string(),
                param: "body".to_string(),
                matches: "sk-[A-Za-z0-9]{6,}".to_string(),
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();
        let p = [("body".to_string(), Value::from("sk-ABCdef123456"))].into();
        let v = engine.check(&tool_action("http_request", p), &state);
        assert_eq!(v.len(), 1);
        assert!(
            !v[0].reason.contains("sk-ABCdef123456"),
            "the matched text is the very secret the rule exists to catch"
        );
        assert!(
            !v[0].reason.contains("sk-[A-Za-z0-9]"),
            "the pattern narrows what the secret looks like"
        );
    }

    #[test]
    fn deny_tool_param_matching_with_an_invalid_regex_fails_closed() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            deny_tool_param_matching: vec![DenyToolParamMatching {
                tool: "http_request".to_string(),
                param: "body".to_string(),
                matches: "(unclosed".to_string(),
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();

        // Every call to the tool is refused, even one that carries no param.
        let p1 = [("body".to_string(), Value::from("harmless"))].into();
        let v = engine.check(&tool_action("http_request", p1), &state);
        assert_eq!(v.len(), 1);
        assert!(v[0].reason.contains("failed to compile"));
        assert_eq!(
            engine
                .check(&tool_action("http_request", HashMap::new()), &state)
                .len(),
            1
        );
        // ...but the blast radius is that tool alone.
        assert!(engine
            .check(&tool_action("echo", HashMap::new()), &state)
            .is_empty());
    }

    #[test]
    fn rate_limit_tool_admits_the_cap_then_denies() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            // A long window so the test never depends on wall-clock timing.
            rate_limit_tool: vec![RateLimitTool {
                tool: "http_request".to_string(),
                max_calls: 3,
                interval_secs: 3600.0,
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();

        for i in 0..3 {
            assert!(
                engine
                    .check(&tool_action("http_request", HashMap::new()), &state)
                    .is_empty(),
                "call {i} is within the cap"
            );
        }
        let v = engine.check(&tool_action("http_request", HashMap::new()), &state);
        assert_eq!(v.len(), 1);
        assert!(v[0].reason.contains("rate limit"));
        // A denied call consumes no budget, so the next one is denied too
        // rather than the window having advanced.
        assert_eq!(
            engine
                .check(&tool_action("http_request", HashMap::new()), &state)
                .len(),
            1
        );
        // A different tool is unaffected.
        assert!(engine
            .check(&tool_action("echo", HashMap::new()), &state)
            .is_empty());
    }

    #[test]
    fn rate_limit_tool_with_zero_max_denies_immediately() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            rate_limit_tool: vec![RateLimitTool {
                tool: "http_request".to_string(),
                max_calls: 0,
                interval_secs: 3600.0,
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();
        assert_eq!(
            engine
                .check(&tool_action("http_request", HashMap::new()), &state)
                .len(),
            1
        );
    }

    #[test]
    fn rate_limit_tool_with_a_nonsense_interval_does_not_panic() {
        let mut engine = PolicyEngine::new();
        PolicyRules {
            rate_limit_tool: vec![RateLimitTool {
                tool: "http_request".to_string(),
                max_calls: 1,
                interval_secs: -5.0,
            }],
            ..Default::default()
        }
        .apply(&mut engine);
        let state = StateStore::new();
        // Zero-length window: nothing is retained, so nothing is ever capped.
        for _ in 0..3 {
            assert!(engine
                .check(&tool_action("http_request", HashMap::new()), &state)
                .is_empty());
        }
    }

    #[test]
    fn parses_all_six_rule_kinds_from_one_document() {
        let src = r#"
            deny_tool = ["deploy"]
            deny_keyword = ["DROP TABLE"]

            [[deny_tool_param]]
            tool = "http_request"
            param = "url"
            contains = "169.254.169.254"

            [[allow_tool_param]]
            tool = "deploy"
            param = "target"
            allow = ["staging", "preview"]

            [[deny_tool_param_matching]]
            tool = "http_request"
            param = "body"
            matches = "sk-[A-Za-z0-9]{20,}"

            [[rate_limit_tool]]
            tool = "http_request"
            max_calls = 10
            interval_secs = 60.0
        "#;
        let rules = PolicyRules::from_toml(src).unwrap();
        assert_eq!(rules.deny_tool, vec!["deploy"]);
        assert_eq!(rules.deny_keyword, vec!["DROP TABLE"]);
        assert_eq!(rules.deny_tool_param.len(), 1);
        assert_eq!(rules.allow_tool_param.len(), 1);
        assert_eq!(
            rules.allow_tool_param[0].allow,
            vec!["staging".to_string(), "preview".to_string()]
        );
        assert_eq!(rules.deny_tool_param_matching.len(), 1);
        assert_eq!(rules.deny_tool_param_matching[0].param, "body");
        assert_eq!(rules.rate_limit_tool.len(), 1);
        assert_eq!(rules.rate_limit_tool[0].max_calls, 10);
        assert_eq!(rules.rate_limit_tool[0].interval_secs, 60.0);
    }

    #[test]
    fn a_rule_set_with_only_a_new_kind_is_not_empty_and_merges() {
        // `merge` and `is_empty` enumerate every field by hand, so a new kind
        // that either one forgets is a silent correctness bug.
        let mut a = PolicyRules::from_toml(
            r#"
            [[allow_tool_param]]
            tool = "deploy"
            param = "target"
            allow = ["staging"]
            "#,
        )
        .unwrap();
        assert!(!a.is_empty(), "is_empty must account for allow_tool_param");

        let b = PolicyRules::from_toml(
            r#"
            [[deny_tool_param_matching]]
            tool = "http_request"
            param = "body"
            matches = "secret"

            [[rate_limit_tool]]
            tool = "http_request"
            max_calls = 1
            interval_secs = 1.0
            "#,
        )
        .unwrap();
        assert!(!b.is_empty(), "is_empty must account for the other two");

        a.merge(b);
        assert_eq!(a.allow_tool_param.len(), 1);
        assert_eq!(a.deny_tool_param_matching.len(), 1);
        assert_eq!(a.rate_limit_tool.len(), 1);
    }

    #[test]
    fn missing_dir_is_empty_not_error() {
        let rules = load_policy_dir("/nonexistent/.car/policies").unwrap();
        assert!(rules.is_empty());
    }

    #[test]
    fn malformed_file_is_loud_error() {
        let dir = std::env::temp_dir().join(format!("car_pol_test_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("bad.toml"), "deny_tool = [unclosed").unwrap();
        let err = load_policy_dir(&dir).unwrap_err();
        assert!(matches!(err, PolicyLoadError::Parse { .. }));
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A rule kind nothing enforces must not load quietly. `trace_rule` parses
    /// and needs a dispatch-time `TraceGate` that no production path builds, so
    /// admitting it would report a rule to the operator that never fires — the
    /// silent-dead-config failure wiring this loader up was meant to end.
    #[test]
    fn an_unenforced_rule_kind_is_refused_rather_than_silently_loaded() {
        let dir = std::env::temp_dir().join(format!("car_pol_unenf_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("trace.toml"),
            "deny_tool = [\"rm\"]\n\n[[trace_rule]]\nkind = \"never\"\ntool = \"deploy\"\n",
        )
        .unwrap();

        let err = load_policy_dir(&dir).unwrap_err();
        match &err {
            PolicyLoadError::Unenforced { path, key } => {
                assert_eq!(key, "trace_rule");
                assert!(path.ends_with("trace.toml"), "names the offending file");
            }
            other => panic!("expected Unenforced, got {other:?}"),
        }
        // The message has to tell the operator what to do about it, not just
        // that something is wrong.
        let msg = err.to_string();
        assert!(msg.contains("not enforced"), "{msg}");
        assert!(msg.contains("trace.toml"), "{msg}");

        // And the whole file is refused — the enforced `deny_tool` beside it
        // does not get loaded as a partial rule set, because a caller that saw
        // Ok would have no way to know half its file was dropped.
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn loads_and_merges_multiple_files() {
        let dir = std::env::temp_dir().join(format!("car_pol_merge_{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("a.toml"), "deny_tool = [\"x\"]").unwrap();
        std::fs::write(dir.join("b.toml"), "deny_tool = [\"y\"]").unwrap();
        let rules = load_policy_dir(&dir).unwrap();
        assert!(rules.deny_tool.contains(&"x".to_string()));
        assert!(rules.deny_tool.contains(&"y".to_string()));
        std::fs::remove_dir_all(&dir).ok();
    }
}

#[cfg(test)]
mod trace_rule_tests {
    use super::*;
    use car_verify::trace_policy::{TraceGate, TraceRule};

    /// Trace rules are authored in the same `.car/policies/*.toml` files as
    /// `deny_tool` (car#704) — one file answers "what may this agent do?".
    #[test]
    fn trace_rules_parse_from_a_policy_file() {
        let src = r#"
deny_tool = ["rm_rf"]

[[trace_rule]]
kind = "precedes"
earlier = "test"
later = "deploy"

[[trace_rule]]
kind = "until"
start = "fetch_url"
forbidden = "write_file"
release = "approval"
name = "no_write_after_fetch_without_approval"
"#;
        let rules = PolicyRules::from_toml(src).expect("parses");
        assert_eq!(rules.deny_tool, vec!["rm_rf"]);
        assert_eq!(rules.trace_rule.len(), 2);
        assert!(matches!(rules.trace_rule[0], TraceRule::Precedes { .. }));
        assert_eq!(
            rules.trace_rule[1].label(),
            "no_write_after_fetch_without_approval"
        );
    }

    /// A file with only stateless rules must still parse — trace rules are
    /// additive, and every existing `.car/policies` file predates them.
    #[test]
    fn a_file_without_trace_rules_still_parses() {
        let rules = PolicyRules::from_toml(r#"deny_tool = ["x"]"#).unwrap();
        assert!(rules.trace_rule.is_empty());
        assert!(!rules.is_empty(), "it still has a deny_tool");
    }

    #[test]
    fn a_rule_set_with_only_trace_rules_is_not_empty() {
        let src = r#"
[[trace_rule]]
kind = "never"
tool = "rm_rf"
"#;
        let rules = PolicyRules::from_toml(src).unwrap();
        assert!(
            !rules.is_empty(),
            "is_empty must account for trace rules, or a project governed only \
             by them would be treated as having no policy at all"
        );
    }

    #[test]
    fn merging_two_files_unions_their_trace_rules() {
        let mut a = PolicyRules::from_toml(
            r#"
[[trace_rule]]
kind = "never"
tool = "a"
"#,
        )
        .unwrap();
        let b = PolicyRules::from_toml(
            r#"
[[trace_rule]]
kind = "never"
tool = "b"
"#,
        )
        .unwrap();
        a.merge(b);
        assert_eq!(a.trace_rule.len(), 2);
    }

    /// End to end: author a rule, build the gate, and watch it refuse the call.
    #[test]
    fn an_authored_rule_gates_a_live_call() {
        let rules = PolicyRules::from_toml(
            r#"
[[trace_rule]]
kind = "precedes"
earlier = "test"
later = "deploy"
"#,
        )
        .unwrap();

        let mut gate = TraceGate::new(rules.trace_rule);
        assert_eq!(gate.check("deploy").len(), 1, "no test has run");
        gate.record("test", true);
        assert!(gate.check("deploy").is_empty());
    }
}