codewhale-execpolicy 0.8.66

Execution policy and approval model for CodeWhale
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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
pub mod bash_arity;

use std::collections::HashSet;

use anyhow::Result;
use bash_arity::BashArityDict;
use codewhale_protocol::{NetworkPolicyAmendment, NetworkPolicyRuleAction};
use serde::{Deserialize, Serialize};

/// Priority layer for a permission ruleset. Higher ordinal = higher priority.
/// On conflict, the highest-priority layer's longest matching prefix wins.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RulesetLayer {
    BuiltinDefault = 0,
    Agent = 1,
    User = 2,
}

/// A named set of allow/deny prefix rules at a given priority layer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Ruleset {
    /// Priority layer this ruleset belongs to.
    pub layer: RulesetLayer,
    /// Command prefixes that are allowed without requiring approval.
    pub trusted_prefixes: Vec<String>,
    /// Command prefixes that are always blocked, regardless of trust rules.
    pub denied_prefixes: Vec<String>,
    /// Typed rules that mark specific tool invocations as requiring approval.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ask_rules: Vec<ToolAskRule>,
}

impl Ruleset {
    /// Creates an empty ruleset at the builtin default priority layer.
    pub fn builtin_default() -> Self {
        Self {
            layer: RulesetLayer::BuiltinDefault,
            trusted_prefixes: vec![],
            denied_prefixes: vec![],
            ask_rules: vec![],
        }
    }

    /// Creates an agent-layer ruleset with the given trusted and denied prefixes.
    pub fn agent(trusted: Vec<String>, denied: Vec<String>) -> Self {
        Self {
            layer: RulesetLayer::Agent,
            trusted_prefixes: trusted,
            denied_prefixes: denied,
            ask_rules: vec![],
        }
    }

    /// Creates a user-layer ruleset with the given trusted and denied prefixes.
    pub fn user(trusted: Vec<String>, denied: Vec<String>) -> Self {
        Self {
            layer: RulesetLayer::User,
            trusted_prefixes: trusted,
            denied_prefixes: denied,
            ask_rules: vec![],
        }
    }

    /// Attaches typed ask rules to this ruleset and returns it.
    pub fn with_ask_rules(mut self, ask_rules: Vec<ToolAskRule>) -> Self {
        self.ask_rules = ask_rules;
        self
    }
}

/// Permission action for a tool invocation rule.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum PermissionAction {
    /// Allow the invocation without asking.
    Allow,
    /// Ask the user before allowing — the approval prompt is forced.
    Ask,
    /// Deny the invocation — the tool call is blocked.
    Deny,
}

fn default_rule_action() -> PermissionAction {
    PermissionAction::Ask
}

/// Typed rule that controls whether a tool invocation is denied, allowed, or requires approval.
///
/// The `action` field governs what happens when this rule matches:
/// - `"deny"` — the tool call is blocked outright (highest priority).
/// - `"ask"` — the approval prompt is forced (default, backward compatible).
/// - `"allow"` — the tool call proceeds without asking.
///
/// Deny always wins over ask, which wins over allow.  Command-prefix-based
/// deny and allow rules are promoted into the execution-policy engine's
/// `denied_prefixes` / `trusted_prefixes` for arity-aware matching;
/// path-only rules are evaluated separately.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ToolAskRule {
    /// Name of the tool this rule applies to (e.g. `"exec_shell"`, `"edit_file"`).
    pub tool: String,
    /// Optional command prefix to match against (uses arity-aware matching).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// Optional file path pattern to match against.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// Action when this rule matches. Default: `"ask"` (backward compatible).
    #[serde(default = "default_rule_action")]
    pub action: PermissionAction,
}

impl ToolAskRule {
    /// Creates a new ask rule matching any invocation of the given tool.
    pub fn new(tool: impl Into<String>) -> Self {
        Self {
            tool: tool.into(),
            command: None,
            path: None,
            action: PermissionAction::Ask,
        }
    }

    /// Creates an ask rule for `exec_shell` matching a specific command prefix.
    pub fn exec_shell(command: impl Into<String>) -> Self {
        Self {
            tool: "exec_shell".to_string(),
            command: Some(command.into()),
            path: None,
            action: PermissionAction::Ask,
        }
    }

    /// Creates an ask rule for a file-tool matching a specific path pattern.
    pub fn file_path(tool: impl Into<String>, path: impl Into<String>) -> Self {
        Self {
            tool: tool.into(),
            command: None,
            path: Some(path.into()),
            action: PermissionAction::Ask,
        }
    }

    fn label(&self) -> String {
        let mut parts = vec![format!("tool={}", self.tool)];
        if let Some(command) = &self.command {
            parts.push(format!("command={command}"));
        }
        if let Some(path) = &self.path {
            parts.push(format!("path={path}"));
        }
        parts.join(" ")
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
/// Policy mode controlling when tool invocations require human approval.
pub enum AskForApproval {
    /// Skip approval if the command matches a trusted prefix; otherwise require it.
    UnlessTrusted,
    /// Allow execution and only request approval after a failure occurs.
    OnFailure,
    /// Always require approval before execution.
    OnRequest,
    /// Reject invocations outright based on specific criteria.
    Reject {
        /// Whether sandbox approval requests are rejected.
        sandbox_approval: bool,
        /// Whether rule-exception requests are rejected.
        rules: bool,
        /// Whether MCP elicitation requests are rejected.
        mcp_elicitations: bool,
    },
    /// Never require approval; forbid commands that would need it.
    Never,
}

/// A proposed amendment to the execution policy, suggesting new trusted prefixes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ExecPolicyAmendment {
    /// Command prefixes to add to the trusted list.
    pub prefixes: Vec<String>,
}

/// The approval requirement determined by the execution policy engine.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ExecApprovalRequirement {
    /// Execution is allowed without approval.
    Skip {
        /// Whether the sandbox should be bypassed for this execution.
        bypass_sandbox: bool,
        /// Optional proposed policy amendment (e.g., to persist the allowed prefix).
        proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
    },
    /// Execution is allowed but requires human approval first.
    NeedsApproval {
        /// Human-readable reason explaining why approval is needed.
        reason: String,
        /// Optional proposed policy amendment that would be applied on approval.
        proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
        /// Proposed network policy amendments that would be applied on approval.
        proposed_network_policy_amendments: Vec<NetworkPolicyAmendment>,
    },
    /// Execution is forbidden by policy.
    Forbidden {
        /// Human-readable reason explaining why execution is forbidden.
        reason: String,
    },
}

impl ExecApprovalRequirement {
    /// Returns the human-readable reason for this approval requirement.
    pub fn reason(&self) -> &str {
        match self {
            ExecApprovalRequirement::Skip { .. } => "Execution allowed by policy.",
            ExecApprovalRequirement::NeedsApproval { reason, .. } => reason,
            ExecApprovalRequirement::Forbidden { reason } => reason,
        }
    }

    /// Returns a short phase label: `"allowed"`, `"needs_approval"`, or `"forbidden"`.
    pub fn phase(&self) -> &'static str {
        match self {
            ExecApprovalRequirement::Skip { .. } => "allowed",
            ExecApprovalRequirement::NeedsApproval { .. } => "needs_approval",
            ExecApprovalRequirement::Forbidden { .. } => "forbidden",
        }
    }
}

/// The result of evaluating a command against the execution policy.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ExecPolicyDecision {
    /// Whether the command is allowed to execute.
    pub allow: bool,
    /// Whether human approval is required before execution.
    pub requires_approval: bool,
    /// The detailed approval requirement, including any proposed amendments.
    pub requirement: ExecApprovalRequirement,
    /// The rule that matched, if any (e.g. a trusted prefix or ask rule label).
    pub matched_rule: Option<String>,
    /// The action of the matched ask-rule, if the match came from a
    /// `ToolAskRule` rather than a prefix.  `None` for prefix matches.
    pub matched_action: Option<PermissionAction>,
}

impl ExecPolicyDecision {
    /// Returns the human-readable reason for this decision.
    pub fn reason(&self) -> &str {
        self.requirement.reason()
    }
}

/// Input context provided to the execution policy engine for a single check.
#[derive(Debug, Clone)]
pub struct ExecPolicyContext<'a> {
    /// The shell command string being evaluated.
    pub command: &'a str,
    /// The current working directory at invocation time.
    pub cwd: &'a str,
    /// The tool name (e.g. `"exec_shell"`, `"edit_file"`). Defaults to `"exec_shell"` when `None`.
    pub tool: Option<&'a str>,
    /// An optional file path relevant to the invocation (used for path-based ask rules).
    pub path: Option<&'a str>,
    /// The current approval policy mode.
    pub ask_for_approval: AskForApproval,
    /// The sandbox mode in effect, if any (e.g. `"workspace-write"`).
    pub sandbox_mode: Option<&'a str>,
}

#[derive(Debug, Clone, Default)]
pub struct ExecPolicyEngine {
    /// Layered rulesets (builtin → agent → user). When non-empty, takes precedence
    /// over the legacy flat lists below.
    rulesets: Vec<Ruleset>,
    /// Legacy flat lists kept for backward compatibility with `new()`.
    trusted_prefixes: Vec<String>,
    denied_prefixes: Vec<String>,
    approved_for_session: HashSet<String>,
    /// Arity dictionary for command-prefix allow-rule matching.
    arity_dict: BashArityDict,
}

impl ExecPolicyEngine {
    /// Legacy constructor: wraps the two vecs into a User-layer ruleset.
    pub fn new(trusted_prefixes: Vec<String>, denied_prefixes: Vec<String>) -> Self {
        Self {
            rulesets: vec![],
            trusted_prefixes,
            denied_prefixes,
            approved_for_session: HashSet::new(),
            arity_dict: BashArityDict::new(),
        }
    }

    /// Build an engine from explicit layered rulesets.
    /// Rulesets are sorted by layer priority on construction.
    pub fn with_rulesets(mut rulesets: Vec<Ruleset>) -> Self {
        rulesets.sort_by_key(|r| r.layer);
        Self {
            rulesets,
            trusted_prefixes: vec![],
            denied_prefixes: vec![],
            approved_for_session: HashSet::new(),
            arity_dict: BashArityDict::new(),
        }
    }

    /// Add a ruleset layer (re-sorts internally).
    pub fn add_ruleset(&mut self, ruleset: Ruleset) {
        self.rulesets.push(ruleset);
        self.rulesets.sort_by_key(|r| r.layer);
    }

    /// Resolve the effective trusted/denied prefix sets by merging all rulesets.
    ///
    /// Collects all prefixes from every layer (builtin → agent → user) into flat
    /// trusted/denied lists. The `check()` method then applies deny-always-wins
    /// semantics: any matching deny prefix blocks the command regardless of layer.
    /// Trusted rules are only consulted after deny checks pass.
    fn resolve_prefixes(&self) -> (Vec<String>, Vec<String>) {
        if self.rulesets.is_empty() {
            return (self.trusted_prefixes.clone(), self.denied_prefixes.clone());
        }
        // Collect all trusted/denied across all layers, highest-priority last so they
        // shadow lower-priority entries with the same prefix.
        let mut trusted: Vec<String> = vec![];
        let mut denied: Vec<String> = vec![];
        for rs in &self.rulesets {
            trusted.extend(rs.trusted_prefixes.iter().cloned());
            denied.extend(rs.denied_prefixes.iter().cloned());
        }
        // Also merge legacy flat lists as user-layer.
        trusted.extend(self.trusted_prefixes.iter().cloned());
        denied.extend(self.denied_prefixes.iter().cloned());
        (trusted, denied)
    }

    fn matching_ask_rule(&self, ctx: &ExecPolicyContext<'_>) -> Option<ToolAskRule> {
        let tool = ctx.tool.unwrap_or("exec_shell");
        let normalized_path = ctx
            .path
            .and_then(|path| normalize_workspace_relative_path(path, ctx.cwd));

        self.rulesets
            .iter()
            .flat_map(|ruleset| {
                ruleset
                    .ask_rules
                    .iter()
                    .map(move |rule| (ruleset.layer, rule))
            })
            .filter(|(_, rule)| rule.tool == tool)
            .filter(|(_, rule)| match rule.command.as_deref() {
                Some(command) => self.arity_dict.allow_rule_matches(command, ctx.command),
                None => true,
            })
            .filter(|(_, rule)| match (rule.path.as_deref(), ctx.path) {
                (Some(pattern), Some(_)) => match (
                    normalize_workspace_relative_path(pattern, ctx.cwd),
                    normalized_path.as_deref(),
                ) {
                    (Some(pattern), Some(path)) => pattern == path,
                    _ => false,
                },
                (Some(_), None) => false,
                (None, _) => true,
            })
            .max_by_key(|(layer, rule)| (rule.action, *layer, ask_rule_specificity(rule)))
            .map(|(_, rule)| rule.clone())
    }

    /// Records an approval key for the current session so subsequent checks skip approval.
    pub fn remember_session_approval(&mut self, approval_key: String) {
        self.approved_for_session.insert(approval_key);
    }

    /// Returns whether the given approval key has been recorded for this session.
    pub fn is_session_approved(&self, approval_key: &str) -> bool {
        self.approved_for_session.contains(approval_key)
    }

    /// Evaluates a command against the policy and returns a decision.
    ///
    /// The evaluation order is: deny rules first (always win), then trusted prefix
    /// matching (arity-aware), then typed ask rules, and finally the approval mode.
    pub fn check(&self, ctx: ExecPolicyContext<'_>) -> Result<ExecPolicyDecision> {
        let normalized = normalize_command(ctx.command);
        let (trusted_prefixes, denied_prefixes) = self.resolve_prefixes();
        // Deny rules use word-boundary prefix matching: the command must either
        // equal the rule or start with the rule followed by a space, so "rm"
        // blocks "rm -rf /" but NOT "rmdir" or "rmview".
        if let Some(rule) = denied_prefixes.iter().find(|rule| {
            let norm_rule = normalize_command(rule);
            normalized == norm_rule
                || (normalized.starts_with(&norm_rule)
                    && normalized.as_bytes().get(norm_rule.len()) == Some(&b' '))
        }) {
            return Ok(ExecPolicyDecision {
                allow: false,
                requires_approval: false,
                matched_rule: Some(rule.clone()),
                matched_action: None,
                requirement: ExecApprovalRequirement::Forbidden {
                    reason: format!("Command blocked by denied prefix rule '{rule}'"),
                },
            });
        }

        // Allow (trusted) rules use arity-aware prefix matching so that
        // `auto_allow = ["git status"]` matches `git status -s` but NOT
        // `git push origin main`.
        let trusted_rule = trusted_prefixes
            .iter()
            .find(|rule| self.arity_dict.allow_rule_matches(rule, ctx.command))
            .cloned();
        let is_trusted = trusted_rule.is_some();

        let ask_rule = self.matching_ask_rule(&ctx);

        // Handle explicit deny/allow actions before mode-based resolution.
        // Deny wins over everything; allow skips approval regardless of mode.
        if let Some(rule) = &ask_rule {
            match rule.action {
                PermissionAction::Deny => {
                    return Ok(ExecPolicyDecision {
                        allow: false,
                        requires_approval: false,
                        matched_rule: Some(rule.label()),
                        matched_action: Some(PermissionAction::Deny),
                        requirement: ExecApprovalRequirement::Forbidden {
                            reason: format!(
                                "Permission rule '{}' explicitly denies this invocation.",
                                rule.label()
                            ),
                        },
                    });
                }
                PermissionAction::Allow => {
                    return Ok(ExecPolicyDecision {
                        allow: true,
                        requires_approval: false,
                        matched_rule: Some(rule.label()),
                        matched_action: Some(PermissionAction::Allow),
                        requirement: ExecApprovalRequirement::Skip {
                            bypass_sandbox: false,
                            proposed_execpolicy_amendment: None,
                        },
                    });
                }
                PermissionAction::Ask => {
                    // Fall through to existing mode-based logic below.
                }
            }
        }

        let mut matched_ask_rule = None;
        // Resolve a matching typed ask-rule first. Ask-rules take precedence over
        // mode-based handling for everything except `Never` (which forbids,
        // because no prompt can be shown) and `Reject { rules: true }` (which
        // explicitly rejects rule-exceptions). This ordering is checked against
        // the experimental `if let` match-guard the original PR used; it is
        // reproduced here with plain control flow for edition-2024 stable.
        let ask_rule_requirement = match &ctx.ask_for_approval {
            AskForApproval::Never | AskForApproval::Reject { rules: true, .. } => None,
            _ => ask_rule.as_ref().map(|rule| {
                matched_ask_rule = Some(rule.label());
                ExecApprovalRequirement::NeedsApproval {
                    reason: format!("Typed ask rule '{}' requires approval.", rule.label()),
                    proposed_execpolicy_amendment: None,
                    // A typed ask-rule approval (exec/fn/MCP) must not touch
                    // network policy. The original PR allow-listed `ctx.cwd` as a
                    // network host here, which is incorrect and security-relevant:
                    // approving e.g. an exec rule should never create a network
                    // allow-entry. Emit no network amendments for ask-rule prompts.
                    proposed_network_policy_amendments: Vec::new(),
                }
            }),
        };

        let requirement = if let Some(req) = ask_rule_requirement {
            req
        } else {
            match &ctx.ask_for_approval {
                AskForApproval::Never => {
                    if let Some(rule) = &ask_rule {
                        matched_ask_rule = Some(rule.label());
                        ExecApprovalRequirement::Forbidden {
                            reason: format!(
                                "Typed ask rule '{}' requires approval, but approval policy is never.",
                                rule.label()
                            ),
                        }
                    } else {
                        ExecApprovalRequirement::Skip {
                            bypass_sandbox: false,
                            proposed_execpolicy_amendment: None,
                        }
                    }
                }
                AskForApproval::Reject { rules, .. } if *rules => {
                    ExecApprovalRequirement::Forbidden {
                        reason: "Policy is configured to reject rule-exceptions.".to_string(),
                    }
                }
                AskForApproval::UnlessTrusted if is_trusted => ExecApprovalRequirement::Skip {
                    bypass_sandbox: false,
                    proposed_execpolicy_amendment: None,
                },
                AskForApproval::OnFailure => ExecApprovalRequirement::Skip {
                    bypass_sandbox: false,
                    proposed_execpolicy_amendment: None,
                },
                _ => ExecApprovalRequirement::NeedsApproval {
                    reason: if is_trusted {
                        "Approval requested by policy mode.".to_string()
                    } else {
                        "Unmatched command prefix requires approval.".to_string()
                    },
                    proposed_execpolicy_amendment: if is_trusted {
                        None
                    } else {
                        Some(ExecPolicyAmendment {
                            prefixes: vec![first_token(ctx.command)],
                        })
                    },
                    proposed_network_policy_amendments: vec![NetworkPolicyAmendment {
                        host: ctx.cwd.to_string(),
                        action: NetworkPolicyRuleAction::Allow,
                    }],
                },
            }
        };

        let (allow, requires_approval) = match requirement {
            ExecApprovalRequirement::Skip { .. } => (true, false),
            ExecApprovalRequirement::NeedsApproval { .. } => (true, true),
            ExecApprovalRequirement::Forbidden { .. } => (false, false),
        };

        Ok(ExecPolicyDecision {
            allow,
            requires_approval,
            matched_rule: matched_ask_rule.or(trusted_rule),
            matched_action: ask_rule.as_ref().map(|r| r.action),
            requirement,
        })
    }
}

fn normalize_command(value: &str) -> String {
    // Normalize: lowercase, collapse internal whitespace to single spaces.
    // This prevents bypass via "git  status" (double space) vs "git status".
    value
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_ascii_lowercase()
}

fn first_token(command: &str) -> String {
    command
        .split_whitespace()
        .next()
        .unwrap_or_default()
        .to_string()
}

/// Returns a slash-separated path relative to `workspace_root` when `value` is
/// a safe path within that workspace.
///
/// Paths are normalized lexically so matching does not depend on the host OS
/// or require the path to exist. A `..` segment is rejected rather than
/// collapsed, preventing traversal from becoming matchable. Absolute paths
/// must have the workspace as a whole-component prefix; relative paths are
/// interpreted as workspace-relative. Backslashes are accepted so persisted
/// rules and tool inputs behave consistently on Windows.
///
/// This is the canonical normalization shared by ask-rule matching and rule
/// persistence: callers that save a file ask rule should store the value this
/// returns so the saved path matches the same invocation later. `None` means
/// the path is empty, traversing, drive-relative, or outside the workspace and
/// must not be turned into a rule.
pub fn normalize_workspace_relative_path(value: &str, workspace_root: &str) -> Option<String> {
    let path = parse_path_for_matching(value)?;
    let workspace = parse_path_for_matching(workspace_root)?;
    let workspace_root = workspace.root.as_ref()?;

    let relative_components = match path.root.as_ref() {
        Some(path_root) => {
            if path_root != workspace_root {
                return None;
            }
            path.components.strip_prefix(&workspace.components[..])?
        }
        None => path.components.as_slice(),
    };

    Some(relative_components.join("/"))
}

#[derive(Debug)]
struct PathForMatching {
    root: Option<String>,
    components: Vec<String>,
}

fn parse_path_for_matching(value: &str) -> Option<PathForMatching> {
    let value = value.trim().replace('\\', "/").to_ascii_lowercase();
    if value.is_empty() {
        return None;
    }

    let (root, components) = if let Some(path) = value.strip_prefix('/') {
        (Some("/".to_string()), path)
    } else if is_windows_absolute_path(&value) {
        (Some(value[..2].to_string()), &value[3..])
    } else if has_windows_drive_prefix(&value) {
        // `C:foo` is drive-relative on Windows. Treating it as a
        // workspace-relative path could match outside the workspace.
        return None;
    } else {
        (None, value.as_str())
    };

    let mut normalized_components = Vec::new();
    for component in components.split('/') {
        match component {
            "" | "." => {}
            ".." => return None,
            component => normalized_components.push(component.to_string()),
        }
    }

    Some(PathForMatching {
        root,
        components: normalized_components,
    })
}

fn is_windows_absolute_path(value: &str) -> bool {
    let bytes = value.as_bytes();
    bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'/'
}

fn has_windows_drive_prefix(value: &str) -> bool {
    let bytes = value.as_bytes();
    bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'
}

fn ask_rule_specificity(rule: &ToolAskRule) -> usize {
    rule.tool.len()
        + rule
            .command
            .as_ref()
            .map_or(0, |command| command.len() + 1000)
        + rule.path.as_ref().map_or(0, |path| path.len() + 1000)
}

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

    fn ctx(command: &str, ask_for_approval: AskForApproval) -> ExecPolicyContext<'_> {
        ExecPolicyContext {
            command,
            cwd: "/workspace",
            tool: Some("exec_shell"),
            path: None,
            ask_for_approval,
            sandbox_mode: Some("workspace-write"),
        }
    }

    #[test]
    fn trusted_prefix_skips_approval_when_policy_is_unless_trusted() {
        let engine = ExecPolicyEngine::new(vec!["git status".to_string()], vec![]);

        let decision = engine
            .check(ctx("git status --porcelain", AskForApproval::UnlessTrusted))
            .unwrap();

        assert!(decision.allow);
        assert!(!decision.requires_approval);
        assert_eq!(decision.matched_rule.as_deref(), Some("git status"));
        assert!(matches!(
            decision.requirement,
            ExecApprovalRequirement::Skip {
                bypass_sandbox: false,
                proposed_execpolicy_amendment: None,
            }
        ));
    }

    #[test]
    fn denied_prefix_blocks_even_when_command_is_also_trusted() {
        let engine = ExecPolicyEngine::new(
            vec!["git status".to_string()],
            vec!["git status".to_string()],
        );

        let decision = engine
            .check(ctx("git status --porcelain", AskForApproval::UnlessTrusted))
            .unwrap();

        assert!(!decision.allow);
        assert!(!decision.requires_approval);
        assert_eq!(decision.matched_rule.as_deref(), Some("git status"));
        assert!(matches!(
            decision.requirement,
            ExecApprovalRequirement::Forbidden { .. }
        ));
        assert_eq!(
            decision.reason(),
            "Command blocked by denied prefix rule 'git status'"
        );
    }

    #[test]
    fn unmatched_command_requires_approval_and_proposes_first_token_rule() {
        let engine = ExecPolicyEngine::new(vec![], vec![]);

        let decision = engine
            .check(ctx("cargo test --workspace", AskForApproval::UnlessTrusted))
            .unwrap();

        assert!(decision.allow);
        assert!(decision.requires_approval);
        assert_eq!(decision.matched_rule, None);
        match decision.requirement {
            ExecApprovalRequirement::NeedsApproval {
                proposed_execpolicy_amendment: Some(amendment),
                proposed_network_policy_amendments,
                ..
            } => {
                assert_eq!(amendment.prefixes, vec!["cargo"]);
                assert_eq!(
                    proposed_network_policy_amendments,
                    vec![NetworkPolicyAmendment {
                        host: "/workspace".to_string(),
                        action: NetworkPolicyRuleAction::Allow,
                    }]
                );
            }
            other => panic!("expected approval with proposed amendment, got {other:?}"),
        }
    }

    #[test]
    fn trusted_command_in_on_request_mode_still_requires_approval_without_new_rule() {
        let engine = ExecPolicyEngine::new(vec!["cargo test".to_string()], vec![]);

        let decision = engine
            .check(ctx("cargo test --workspace", AskForApproval::OnRequest))
            .unwrap();

        assert!(decision.allow);
        assert!(decision.requires_approval);
        assert_eq!(decision.matched_rule.as_deref(), Some("cargo test"));
        match decision.requirement {
            ExecApprovalRequirement::NeedsApproval {
                proposed_execpolicy_amendment,
                ..
            } => assert_eq!(proposed_execpolicy_amendment, None),
            other => panic!("expected approval without amendment, got {other:?}"),
        }
    }

    #[test]
    fn reject_rules_mode_forbids_unmatched_command() {
        let engine = ExecPolicyEngine::new(vec![], vec![]);

        let decision = engine
            .check(ctx(
                "npm install",
                AskForApproval::Reject {
                    sandbox_approval: false,
                    rules: true,
                    mcp_elicitations: false,
                },
            ))
            .unwrap();

        assert!(!decision.allow);
        assert!(!decision.requires_approval);
        assert_eq!(decision.matched_rule, None);
        assert_eq!(decision.requirement.phase(), "forbidden");
        assert_eq!(
            decision.reason(),
            "Policy is configured to reject rule-exceptions."
        );
    }

    #[test]
    fn typed_ask_rule_forbids_matching_command_when_policy_is_never() {
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(vec![], vec![])
                .with_ask_rules(vec![ToolAskRule::exec_shell("cargo test")]),
        ]);

        let decision = engine
            .check(ctx("cargo test --workspace", AskForApproval::Never))
            .unwrap();

        assert!(!decision.allow);
        assert!(!decision.requires_approval);
        assert_eq!(
            decision.matched_rule.as_deref(),
            Some("tool=exec_shell command=cargo test")
        );
        assert_eq!(decision.requirement.phase(), "forbidden");
        assert_eq!(
            decision.reason(),
            "Typed ask rule 'tool=exec_shell command=cargo test' requires approval, but approval policy is never."
        );
    }

    #[test]
    fn typed_ask_rule_requires_approval_under_unless_trusted() {
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(vec![], vec![])
                .with_ask_rules(vec![ToolAskRule::exec_shell("cargo test")]),
        ]);

        let decision = engine
            .check(ctx("cargo test --workspace", AskForApproval::UnlessTrusted))
            .unwrap();

        assert!(decision.allow);
        assert!(decision.requires_approval);
        assert_eq!(
            decision.matched_rule.as_deref(),
            Some("tool=exec_shell command=cargo test")
        );
        match decision.requirement {
            ExecApprovalRequirement::NeedsApproval {
                proposed_execpolicy_amendment,
                proposed_network_policy_amendments,
                ..
            } => {
                assert_eq!(proposed_execpolicy_amendment, None);
                // A typed ask-rule approval must not allow-list the cwd (or
                // anything else) as a network host. See the NeedsApproval arm.
                assert!(
                    proposed_network_policy_amendments.is_empty(),
                    "ask-rule approval must not propose network amendments, got {proposed_network_policy_amendments:?}"
                );
            }
            other => panic!("expected typed ask approval, got {other:?}"),
        }
    }

    #[test]
    fn typed_ask_rule_requires_approval_under_on_failure() {
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(vec![], vec![])
                .with_ask_rules(vec![ToolAskRule::exec_shell("cargo test")]),
        ]);

        let decision = engine
            .check(ctx("cargo test --workspace", AskForApproval::OnFailure))
            .unwrap();

        assert!(decision.allow);
        assert!(decision.requires_approval);
        assert_eq!(
            decision.reason(),
            "Typed ask rule 'tool=exec_shell command=cargo test' requires approval."
        );
    }

    #[test]
    fn typed_ask_rule_overrides_trusted_but_not_deny() {
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(
                vec!["cargo test".to_string()],
                vec!["cargo test --danger".to_string()],
            )
            .with_ask_rules(vec![ToolAskRule::exec_shell("cargo test")]),
        ]);

        let trusted = engine
            .check(ctx("cargo test --workspace", AskForApproval::UnlessTrusted))
            .unwrap();
        assert!(trusted.allow);
        assert!(trusted.requires_approval);
        assert_eq!(
            trusted.matched_rule.as_deref(),
            Some("tool=exec_shell command=cargo test")
        );

        let denied = engine
            .check(ctx("cargo test --danger", AskForApproval::Never))
            .unwrap();
        assert!(!denied.allow);
        assert!(!denied.requires_approval);
        assert_eq!(denied.matched_rule.as_deref(), Some("cargo test --danger"));
        assert_eq!(
            denied.reason(),
            "Command blocked by denied prefix rule 'cargo test --danger'"
        );
    }

    #[test]
    fn typed_ask_rule_prefers_higher_layer_before_specificity() {
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::agent(vec![], vec![])
                .with_ask_rules(vec![ToolAskRule::exec_shell("cargo test --workspace")]),
            Ruleset::user(vec![], vec![])
                .with_ask_rules(vec![ToolAskRule::exec_shell("cargo test")]),
        ]);

        let decision = engine
            .check(ctx(
                "cargo test --workspace --all-features",
                AskForApproval::UnlessTrusted,
            ))
            .unwrap();

        assert!(decision.requires_approval);
        assert_eq!(
            decision.matched_rule.as_deref(),
            Some("tool=exec_shell command=cargo test")
        );
    }

    #[test]
    fn reject_rules_mode_still_forbids_matching_ask_rule() {
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(vec![], vec![])
                .with_ask_rules(vec![ToolAskRule::exec_shell("cargo test")]),
        ]);

        let decision = engine
            .check(ctx(
                "cargo test --workspace",
                AskForApproval::Reject {
                    sandbox_approval: false,
                    rules: true,
                    mcp_elicitations: false,
                },
            ))
            .unwrap();

        assert!(!decision.allow);
        assert!(!decision.requires_approval);
        assert_eq!(decision.matched_rule, None);
        assert_eq!(
            decision.reason(),
            "Policy is configured to reject rule-exceptions."
        );
    }

    #[test]
    fn typed_ask_rule_label_wins_when_never_blocks_trusted_command() {
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(vec!["cargo test".to_string()], vec![])
                .with_ask_rules(vec![ToolAskRule::exec_shell("cargo test")]),
        ]);

        let decision = engine
            .check(ctx("cargo test --workspace", AskForApproval::Never))
            .unwrap();

        assert!(!decision.allow);
        assert_eq!(
            decision.matched_rule.as_deref(),
            Some("tool=exec_shell command=cargo test")
        );
        assert_eq!(
            decision.reason(),
            "Typed ask rule 'tool=exec_shell command=cargo test' requires approval, but approval policy is never."
        );
    }

    #[test]
    fn typed_ask_path_matching_trims_spaces_before_workspace_normalization() {
        let engine =
            ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(
                vec![ToolAskRule::file_path(
                    "edit_file",
                    " /workspace/tmp/project/ ",
                )],
            )]);

        let decision = engine
            .check(ExecPolicyContext {
                command: "",
                cwd: "/workspace",
                tool: Some("edit_file"),
                path: Some("tmp/project"),
                ask_for_approval: AskForApproval::Never,
                sandbox_mode: Some("workspace-write"),
            })
            .unwrap();

        assert!(!decision.allow);
        assert_eq!(
            decision.matched_rule.as_deref(),
            Some("tool=edit_file path= /workspace/tmp/project/ ")
        );
    }

    #[test]
    fn typed_ask_path_matching_normalizes_relative_and_absolute_workspace_paths() {
        let relative_rule = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(vec![], vec![])
                .with_ask_rules(vec![ToolAskRule::file_path("edit_file", "src/a.rs")]),
        ]);
        let absolute_path = relative_rule
            .check(ExecPolicyContext {
                command: "",
                cwd: "/workspace",
                tool: Some("edit_file"),
                path: Some("/workspace/src/a.rs"),
                ask_for_approval: AskForApproval::OnFailure,
                sandbox_mode: Some("workspace-write"),
            })
            .unwrap();
        assert!(absolute_path.requires_approval);

        let absolute_rule =
            ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(
                vec![ToolAskRule::file_path("edit_file", "/workspace/src/a.rs")],
            )]);
        let relative_path = absolute_rule
            .check(ExecPolicyContext {
                command: "",
                cwd: "/workspace",
                tool: Some("edit_file"),
                path: Some("src/a.rs"),
                ask_for_approval: AskForApproval::OnFailure,
                sandbox_mode: Some("workspace-write"),
            })
            .unwrap();
        assert!(relative_path.requires_approval);
    }

    #[test]
    fn typed_ask_path_matching_rejects_traversal_and_external_paths() {
        for (rule_path, path) in [
            ("src/a.rs", "../src/a.rs"),
            ("src/a.rs", "/workspace/src/../src/a.rs"),
            ("src/a.rs", "/src/a.rs"),
            ("../src/a.rs", "src/a.rs"),
            ("/src/a.rs", "src/a.rs"),
        ] {
            let engine = ExecPolicyEngine::with_rulesets(vec![
                Ruleset::user(vec![], vec![])
                    .with_ask_rules(vec![ToolAskRule::file_path("edit_file", rule_path)]),
            ]);
            let decision = engine
                .check(ExecPolicyContext {
                    command: "",
                    cwd: "/workspace",
                    tool: Some("edit_file"),
                    path: Some(path),
                    ask_for_approval: AskForApproval::OnFailure,
                    sandbox_mode: Some("workspace-write"),
                })
                .unwrap();
            assert_eq!(
                decision.matched_rule, None,
                "rule {rule_path:?} and path {path:?} must not match"
            );
        }
    }

    #[test]
    fn typed_ask_path_matching_accepts_windows_separators() {
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(vec![], vec![])
                .with_ask_rules(vec![ToolAskRule::file_path("edit_file", r"src\a.rs")]),
        ]);

        let decision = engine
            .check(ExecPolicyContext {
                command: "",
                cwd: r"C:\workspace",
                tool: Some("edit_file"),
                path: Some(r"C:\workspace\src\a.rs"),
                ask_for_approval: AskForApproval::OnFailure,
                sandbox_mode: Some("workspace-write"),
            })
            .unwrap();

        assert!(decision.requires_approval);
    }

    // ── deny / allow action tests ──────────────────────────────────────────

    #[test]
    fn deny_action_blocks_regardless_of_mode() {
        let engine =
            ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(
                vec![ToolAskRule {
                    tool: "exec_shell".into(),
                    command: Some("sed".into()),
                    path: None,
                    action: PermissionAction::Deny,
                }],
            )]);

        // sed should be blocked even under UnlessTrusted
        let decision = engine
            .check(ExecPolicyContext {
                command: "sed -i 's/foo/bar/' file.txt",
                cwd: "/tmp",
                tool: Some("exec_shell"),
                path: None,
                ask_for_approval: AskForApproval::UnlessTrusted,
                sandbox_mode: None,
            })
            .unwrap();

        assert!(!decision.allow);
        assert!(!decision.requires_approval);
        assert_eq!(decision.matched_action, Some(PermissionAction::Deny));
        assert_eq!(decision.requirement.phase(), "forbidden");
        assert!(
            decision.reason().contains("explicitly denies"),
            "expected deny reason, got: {}",
            decision.reason()
        );
    }

    #[test]
    fn allow_action_skips_approval_regardless_of_mode() {
        let engine =
            ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(
                vec![ToolAskRule {
                    tool: "exec_shell".into(),
                    command: Some("git status".into()),
                    path: None,
                    action: PermissionAction::Allow,
                }],
            )]);

        // git status should be allowed even under OnRequest
        let decision = engine
            .check(ExecPolicyContext {
                command: "git status",
                cwd: "/tmp",
                tool: Some("exec_shell"),
                path: None,
                ask_for_approval: AskForApproval::OnRequest,
                sandbox_mode: None,
            })
            .unwrap();

        assert!(decision.allow);
        assert!(!decision.requires_approval);
        assert_eq!(decision.matched_action, Some(PermissionAction::Allow));
    }

    #[test]
    fn deny_wins_over_allow_when_both_match() {
        // Deny "sed" rule at user layer, allow "sed" at agent layer.
        // Higher-layer (user) deny should win.
        let engine = ExecPolicyEngine::with_rulesets(vec![
            Ruleset::agent(vec!["sed".into()], vec![]).with_ask_rules(vec![]),
            Ruleset::user(vec![], vec!["sed".into()]).with_ask_rules(vec![]),
        ]);

        let decision = engine
            .check(ExecPolicyContext {
                command: "sed -i 's/a/b/' x.txt",
                cwd: "/tmp",
                tool: Some("exec_shell"),
                path: None,
                ask_for_approval: AskForApproval::UnlessTrusted,
                sandbox_mode: None,
            })
            .unwrap();

        assert!(!decision.allow);
        assert_eq!(decision.requirement.phase(), "forbidden");
    }

    #[test]
    fn ask_action_default_backward_compatible() {
        // Without explicit action, rules default to Ask via serde default.
        let rule = ToolAskRule::exec_shell("cargo test");
        assert_eq!(rule.action, PermissionAction::Ask);
    }

    #[test]
    fn deny_action_constructors_produce_ask_by_default() {
        assert_eq!(ToolAskRule::new("exec_shell").action, PermissionAction::Ask);
        assert_eq!(
            ToolAskRule::exec_shell("cargo test").action,
            PermissionAction::Ask
        );
        assert_eq!(
            ToolAskRule::file_path("read_file", "secrets.txt").action,
            PermissionAction::Ask
        );
    }

    // ── deny: single-word commands ────────────────────────────────────────

    #[test]
    fn deny_single_word_blocks_exact_and_subcommands() {
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("sed".into()),
            path: None,
            action: PermissionAction::Deny,
        });

        // exact match
        let d = engine.check(ctx("sed", UnlessTrusted)).unwrap();
        assert!(!d.allow, "deny must block exact 'sed'");

        // subcommand
        let d = engine
            .check(ctx("sed -i 's/a/b/' file.txt", UnlessTrusted))
            .unwrap();
        assert!(!d.allow, "deny must block 'sed -i …'");
    }

    #[test]
    fn deny_single_word_does_not_block_unrelated() {
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("sed".into()),
            path: None,
            action: PermissionAction::Deny,
        });

        // unrelated command passes through
        let d = engine
            .check(ctx("awk '{print $1}'", UnlessTrusted))
            .unwrap();
        assert!(d.allow, "deny 'sed' must not block 'awk'");
    }

    #[test]
    fn deny_word_boundary_prevents_false_positives() {
        // "rm" must block "rm -rf /" but NOT "rmdir"
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("rm".into()),
            path: None,
            action: PermissionAction::Deny,
        });

        assert!(!engine.check(ctx("rm -rf /", UnlessTrusted)).unwrap().allow);
        assert!(
            engine
                .check(ctx("rmdir empty-dir", UnlessTrusted))
                .unwrap()
                .allow
        );
    }

    // ── deny: multi-word commands ─────────────────────────────────────────

    #[test]
    fn deny_multi_word_blocks_subcommands() {
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("git push".into()),
            path: None,
            action: PermissionAction::Deny,
        });

        assert!(!engine.check(ctx("git push", UnlessTrusted)).unwrap().allow);
        assert!(
            !engine
                .check(ctx("git push origin main", UnlessTrusted))
                .unwrap()
                .allow
        );
        assert!(
            !engine
                .check(ctx("git push --force", UnlessTrusted))
                .unwrap()
                .allow
        );
    }

    #[test]
    fn deny_multi_word_distinguishes_from_sibling_subcommands() {
        // "git push" must NOT block "git pull"
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("git push".into()),
            path: None,
            action: PermissionAction::Deny,
        });

        assert!(engine.check(ctx("git pull", UnlessTrusted)).unwrap().allow);
        assert!(
            engine
                .check(ctx("git pull origin main", UnlessTrusted))
                .unwrap()
                .allow
        );
        assert!(
            engine
                .check(ctx("git status", UnlessTrusted))
                .unwrap()
                .allow
        );
    }

    #[test]
    fn deny_multi_word_via_denied_prefixes_path() {
        // When ruleset() promotes deny→denied_prefixes, the word-boundary
        // path in check() handles it identically.
        let engine = ExecPolicyEngine::new(vec![], vec!["git push".into()]);

        assert!(
            !engine
                .check(ctx("git push --force", UnlessTrusted))
                .unwrap()
                .allow
        );
        assert!(engine.check(ctx("git pull", UnlessTrusted)).unwrap().allow);
    }

    // ── deny: priority ────────────────────────────────────────────────────

    #[test]
    fn deny_wins_over_allow_via_ask_rules() {
        let engine =
            ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(
                vec![
                    ToolAskRule {
                        tool: "exec_shell".into(),
                        command: Some("sed".into()),
                        path: None,
                        action: PermissionAction::Allow,
                    },
                    ToolAskRule {
                        tool: "exec_shell".into(),
                        command: Some("sed".into()),
                        path: None,
                        action: PermissionAction::Deny,
                    },
                ],
            )]);

        // Both match; deny should win (execpolicy early-return for deny
        // fires before allow).
        let d = engine
            .check(ctx("sed -i 's/a/b/' x.txt", UnlessTrusted))
            .unwrap();
        assert!(!d.allow, "deny must win over allow");
    }

    #[test]
    fn deny_wins_over_allow_via_ask_rules_regardless_of_order() {
        let engine =
            ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(
                vec![
                    ToolAskRule {
                        tool: "exec_shell".into(),
                        command: Some("sed".into()),
                        path: None,
                        action: PermissionAction::Deny,
                    },
                    ToolAskRule {
                        tool: "exec_shell".into(),
                        command: Some("sed".into()),
                        path: None,
                        action: PermissionAction::Allow,
                    },
                ],
            )]);

        let d = engine
            .check(ctx("sed -i 's/a/b/' x.txt", UnlessTrusted))
            .unwrap();
        assert!(!d.allow, "deny must win even if allow appears later");
        assert_eq!(d.matched_action, Some(PermissionAction::Deny));
    }

    #[test]
    fn path_deny_wins_over_path_allow_regardless_of_order() {
        let engine =
            ExecPolicyEngine::with_rulesets(vec![Ruleset::user(vec![], vec![]).with_ask_rules(
                vec![
                    ToolAskRule {
                        tool: "write_file".into(),
                        command: None,
                        path: Some("src/secrets.rs".into()),
                        action: PermissionAction::Deny,
                    },
                    ToolAskRule {
                        tool: "write_file".into(),
                        command: None,
                        path: Some("src/secrets.rs".into()),
                        action: PermissionAction::Allow,
                    },
                ],
            )]);

        let d = engine
            .check(ExecPolicyContext {
                command: "",
                cwd: "/workspace",
                tool: Some("write_file"),
                path: Some("/workspace/src/secrets.rs"),
                ask_for_approval: UnlessTrusted,
                sandbox_mode: None,
            })
            .unwrap();

        assert!(!d.allow, "path deny must win even if allow appears later");
        assert_eq!(d.matched_action, Some(PermissionAction::Deny));
    }

    #[test]
    fn deny_via_prefixes_wins_over_allow_via_prefixes() {
        // denied_prefixes checked first, before trusted_prefixes.
        let engine = ExecPolicyEngine::new(vec!["sed".into()], vec!["sed".into()]);

        let d = engine
            .check(ctx("sed -i 's/a/b/' x.txt", UnlessTrusted))
            .unwrap();
        assert!(!d.allow, "denied prefix must win over trusted prefix");
    }

    #[test]
    fn deny_tool_only_without_command_blocks_every_invocation() {
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: None,
            path: None,
            action: PermissionAction::Deny,
        });

        // any exec_shell command should be blocked
        assert!(
            !engine
                .check(ctx("git status", UnlessTrusted))
                .unwrap()
                .allow
        );
        assert!(
            !engine
                .check(ctx("cargo build", UnlessTrusted))
                .unwrap()
                .allow
        );
        assert!(
            !engine
                .check(ctx("echo hello", UnlessTrusted))
                .unwrap()
                .allow
        );
    }

    // ── allow: single / multi-word ────────────────────────────────────────

    #[test]
    fn allow_single_word_skips_approval() {
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("cargo".into()),
            path: None,
            action: PermissionAction::Allow,
        });

        let d = engine
            .check(ctx("cargo build --release", OnRequest))
            .unwrap();
        assert!(d.allow);
        assert!(!d.requires_approval);
        assert_eq!(d.matched_action, Some(PermissionAction::Allow));
    }

    #[test]
    fn allow_multi_word_skips_approval() {
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("git status".into()),
            path: None,
            action: PermissionAction::Allow,
        });

        let d = engine.check(ctx("git status --short", OnRequest)).unwrap();
        assert!(d.allow);
        assert!(!d.requires_approval);
    }

    #[test]
    fn allow_does_not_leak_to_unmatched_commands() {
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("git status".into()),
            path: None,
            action: PermissionAction::Allow,
        });

        // Unrelated command: normal approval flow applies.
        let d = engine
            .check(ctx("git push origin main", UnlessTrusted))
            .unwrap();
        // UnlessTrusted without a trusted prefix: requires approval
        assert!(d.requires_approval);
    }

    #[test]
    fn allow_under_never_mode_still_allows() {
        // allow action must bypass even strict Never mode.
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("cargo".into()),
            path: None,
            action: PermissionAction::Allow,
        });

        let d = engine.check(ctx("cargo check", Never)).unwrap();
        assert!(d.allow);
        assert!(!d.requires_approval);
    }

    // ── ask: default / backward compat ────────────────────────────────────

    #[test]
    fn ask_action_behaves_like_before_action_field_existed() {
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("cargo test".into()),
            path: None,
            action: PermissionAction::Ask,
        });

        // Under UnlessTrusted: ask rule forces approval
        let d = engine
            .check(ctx("cargo test --workspace", UnlessTrusted))
            .unwrap();
        assert!(d.allow);
        assert!(d.requires_approval);

        // Under Never: ask rule is forbidden
        let d = engine.check(ctx("cargo test --workspace", Never)).unwrap();
        assert!(!d.allow);
        assert_eq!(d.requirement.phase(), "forbidden");
    }

    #[test]
    fn ask_is_default_when_action_omitted() {
        let rule = ToolAskRule::exec_shell("cargo test");
        assert_eq!(rule.action, PermissionAction::Ask);
    }

    // ── cross-cutting ─────────────────────────────────────────────────────

    #[test]
    fn deny_blocks_tool_only_even_for_different_tool() {
        // deny on "exec_shell" must not affect "write_file"
        let engine = engine_with_ask_rule(ToolAskRule {
            tool: "exec_shell".into(),
            command: Some("sed".into()),
            path: None,
            action: PermissionAction::Deny,
        });

        let d = engine
            .check(ExecPolicyContext {
                command: "",
                cwd: "/workspace",
                tool: Some("write_file"),
                path: Some("/workspace/src/main.rs"),
                ask_for_approval: UnlessTrusted,
                sandbox_mode: None,
            })
            .unwrap();
        // write_file should not be affected by exec_shell deny
        assert!(d.allow);
    }

    #[test]
    fn normalize_handles_extra_whitespace_in_command() {
        // "git  status" (double space) normalizes to "git status"
        let engine = ExecPolicyEngine::new(vec![], vec!["git push".into()]);

        let d = engine
            .check(ctx("git   push   --force", UnlessTrusted))
            .unwrap();
        assert!(!d.allow, "extra whitespace must not bypass deny");
    }

    #[test]
    fn normalize_handles_case_insensitivity() {
        // normalize_command lowercases — "SED" matches "sed"
        let engine = ExecPolicyEngine::new(vec![], vec!["sed".into()]);

        let d = engine
            .check(ctx("SED -i 's/a/b/' file.txt", UnlessTrusted))
            .unwrap();
        assert!(!d.allow, "case must not bypass deny");
    }

    #[test]
    fn allow_falls_back_to_mode_when_no_rule_matches() {
        let engine = ExecPolicyEngine::new(vec![], vec![]); // no rules

        let d = engine.check(ctx("cargo build", UnlessTrusted)).unwrap();
        assert!(d.allow);
        assert!(d.requires_approval, "untrusted cmd needs approval");
    }

    // ── helpers ───────────────────────────────────────────────────────────

    fn engine_with_ask_rule(rule: ToolAskRule) -> ExecPolicyEngine {
        ExecPolicyEngine::with_rulesets(vec![
            Ruleset::user(vec![], vec![]).with_ask_rules(vec![rule]),
        ])
    }
}