termaxa 0.18.6

A cooperative gate for the shell commands AI coding agents run — command previews, automatic backups, allow/ask/deny policy, and audit logging.
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
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Action {
    Allow,
    Ask,
    Deny,
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Action::Allow => write!(f, "allow"),
            Action::Ask => write!(f, "ask"),
            Action::Deny => write!(f, "deny"),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rule {
    /// Wildcard pattern matched against the normalized command STRING.
    /// `*` matches any run of characters. First matching rule wins.
    ///
    /// Optional since v0.16, because a rule that matches on resolved paths
    /// should not have to carry a string pattern it does not mean. Forcing
    /// one produced a live over-blocking bug: the shipped `.env` path rule
    /// carried `match: "*.env*"` purely to satisfy the schema, and that
    /// pattern fired on its own - `cat .env`, `grep KEY .env`,
    /// `git diff .env` and even `vim .env.sample` were all DENIED. Reading a
    /// file is ordinary work, and a gate that denies ordinary work gets
    /// uninstalled (#48).
    ///
    /// See `validate` for the invariant that replaced "always present".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#match: Option<String>,
    pub action: Action,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Match this rule as written instead of case-insensitively.
    ///
    /// EXPLICIT, defaulting to false, and never inferred from the pattern's
    /// spelling. The first draft inferred it from the presence of an
    /// uppercase letter, which silently made `*Remove-Item*-Recurse*`
    /// case-sensitive and let `remove-item -recurse` walk past a deny that
    /// has shipped since v0.11 — the release's own bug class (reading intent
    /// out of spelling) applied to the rule text itself.
    #[serde(default, skip_serializing_if = "is_false")]
    pub case_sensitive: bool,
    /// Match this rule against the command's RESOLVED targets rather than
    /// against the command string.
    ///
    /// Roadmap 2.4. `> ./.env` and `> .env` are the same file and different
    /// strings, so a `match:` rule naming one misses the other - the gap
    /// pinned in known-limitations 0.2. A `match_path:` rule is matched
    /// against each target after resolution, so both spellings reach it.
    ///
    /// A rule may carry both fields. `match:` is required by the schema and
    /// stays the rule's identity in reason lines and audit entries; when
    /// `match_path:` is present, the rule fires if EITHER matches - the string
    /// reading can only add matches, never remove them, which is the same
    /// promise the extra readings make.
    ///
    /// ANY target matching fires the rule, and the reason names WHICH one. A
    /// command with several targets is one command, and a human deciding
    /// whether to approve it needs to know which path tripped the gate.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub match_path: Option<String>,
}

fn is_false(b: &bool) -> bool {
    !*b
}

impl Rule {
    /// Does this rule match one reading of a command?
    ///
    /// A rule matches case-insensitively, as it always has: `drop table`
    /// still catches `DROP TABLE`, and an uppercase SPELLING changes nothing
    /// (`*Remove-Item*` still catches `remove-item`). A rule that opted in
    /// with `case_sensitive: true` is matched as written against the
    /// case-preserved reading, so `git branch*-D*` can mean `-D` and not
    /// `-d`. The field decides; the spelling never does.
    /// Does this rule's `match_path` pattern match a resolved target?
    ///
    /// Matched COMPONENT BY COMPONENT, not as a string glob. `*/.env` means
    /// "a path whose last component is `.env`", and it matches
    /// `/tmp/proj/.env`, `C:\\proj\\.env` and a bare `.env` alike.
    ///
    /// This is deliberately NOT `wildcard_match` over the path string, which
    /// is what the first draft did and which was wrong three ways at once:
    /// `*/.env` missed a target that resolved to a bare `.env` (no separator
    /// to match), missed `C:\\proj\\.env` (backslashes are not `/`), and
    /// would have matched `prod.env` if the pattern were loosened to `*.env`
    /// to compensate. A path is a sequence of components, and a glob over its
    /// printed form is still string thinking - the exact confusion this whole
    /// change exists to end.
    ///
    /// Splitting reuses `protect::segments`, so the command path and the
    /// write path cannot come to disagree about what a component is (#37).
    /// Each component is matched with the same wildcard engine, so
    /// `*/node_modules/*` and `*/.ssh/id_*` read as expected.
    ///
    /// A leading `*` component means "at any depth", so `*/.env` matches
    /// `.env` at the root as well as nested. Without that, a policy author
    /// would have to write two rules for one file.
    pub fn matches_path(&self, path: &str) -> bool {
        let Some(pattern) = &self.match_path else {
            return false;
        };
        let pat: Vec<String> = crate::protect::segments(pattern);
        let seg: Vec<String> = crate::protect::segments(path);
        match_components(&pat, &seg)
    }

    /// Does this rule's STRING pattern match a reading? A rule with no
    /// `match:` matches no string - it speaks only about paths, and saying
    /// otherwise is how the over-blocking bug happened.
    pub fn matches(&self, reading: &str) -> bool {
        let Some(pattern) = &self.r#match else {
            return false;
        };
        if self.case_sensitive {
            wildcard_match(&collapse(pattern), reading)
        } else {
            wildcard_match(&normalize(pattern), reading)
        }
    }

    /// How this rule is named in reason lines and audit entries. A rule
    /// always has at least one matcher (see `Policy::validate`), so there is
    /// always something to name.
    pub fn label(&self) -> String {
        match (&self.r#match, &self.match_path) {
            (Some(m), _) => m.clone(),
            (None, Some(p)) => format!("path:{p}"),
            // Unreachable: validation rejects a rule with neither.
            (None, None) => "<no matcher>".to_string(),
        }
    }
}

/// Collapse whitespace without touching case.
pub fn collapse(s: &str) -> String {
    s.split_whitespace().collect::<Vec<_>>().join(" ")
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Notify {
    /// Slack-compatible incoming webhook URL (any endpoint accepting {"text": ...}).
    pub webhook: String,
    /// Which decisions trigger a notification. Default: deny only.
    #[serde(default = "default_notify_on")]
    pub on: Vec<String>,
}

fn default_notify_on() -> Vec<String> {
    vec!["deny".to_string()]
}

/// Policy for a hook payload the reader cannot parse. See `Policy::unrecognised`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Unrecognised {
    #[default]
    Allow,
    Deny,
}

impl Unrecognised {
    fn is_default(v: &Self) -> bool {
        *v == Self::Allow
    }
}

/// Policy for a backup that could not be taken. See `Policy::backup_failure`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum BackupFailure {
    #[default]
    Proceed,
    Deny,
}

impl BackupFailure {
    fn is_default(v: &Self) -> bool {
        *v == Self::Proceed
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Policy {
    #[serde(default = "default_version")]
    pub version: u32,
    /// Action when no rule matches.
    #[serde(default = "default_action")]
    pub default: Action,
    #[serde(default)]
    pub rules: Vec<Rule>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notify: Option<Notify>,
    /// What the hook does with a payload it does not recognise as a shell
    /// tool call it can read. `allow` (the default) passes it through
    /// untouched - the cooperative gate's founding choice: a hook that fails
    /// closed on every harness update becomes the outage the day an event is
    /// renamed. `deny` refuses any event that looks like a shell tool call
    /// (a tool named like a shell, or a `command` field) the reader could
    /// not parse - for unattended runs, where a stopped agent is cheaper than
    /// an ungated one. Known-limitation 4 records the two incidents behind
    /// this knob.
    #[serde(default, skip_serializing_if = "Unrecognised::is_default")]
    pub unrecognised: Unrecognised,
    /// What happens when the insurance cannot be taken for a command the gate
    /// would otherwise let run. `proceed` (the default) reports the failure
    /// and runs the approved command - insurance failing to bind must not
    /// cancel the flight for a person at a terminal. `deny` refuses instead:
    /// the choice for unattended runs, where nobody sees the warning and the
    /// uninsured delete is the whole risk. #61 is the receipt: a copy that
    /// failed on `/dev/null` and a directory deleted with no backup behind it.
    #[serde(default, skip_serializing_if = "BackupFailure::is_default")]
    pub backup_failure: BackupFailure,
}

fn default_version() -> u32 {
    1
}
fn default_action() -> Action {
    Action::Ask
}

fn severity(a: Action) -> u8 {
    match a {
        Action::Allow => 0,
        Action::Ask => 1,
        Action::Deny => 2,
    }
}

#[derive(Debug, Clone)]
pub struct Decision {
    pub action: Action,
    pub matched_rule: Option<String>,
    pub reason: String,
    /// WHY this verdict, not just what it is.
    ///
    /// Roadmap 2.5. `Ask` from an explicit rule and `Ask` from an unmatched
    /// command are not different strengths of the same thing - they are
    /// different statements. The first says "stop and think about this"; the
    /// second says "I have no opinion". Treating them alike made the
    /// insurance amplifier fire on every unmatched command under a
    /// `default: ask` policy, which is `uninsurable -> deny` wearing a
    /// different name.
    pub source: DecisionSource,
}

/// Where a verdict came from.
///
/// Carried rather than collapsed, for the same reason `ResolvedTarget` keeps
/// its role: a downstream layer reasoning about a decision needs to know what
/// kind of statement it is, and re-deriving that from the reason string would
/// be parsing prose.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DecisionSource {
    /// No rule matched; this is the policy's default, i.e. the absence of an
    /// opinion about this command.
    #[default]
    Default,
    /// A rule matched and chose this action deliberately.
    ExplicitRule,
    /// A context signal raised the verdict - a production marker, a user
    /// profile target, command substitution.
    Context,
}

impl DecisionSource {
    /// Stable name for the audit record. Same wire-format caution as
    /// `Dialect::actor`: these strings are written to disk and a reader
    /// comparing across versions depends on them not moving.
    pub fn as_str(self) -> &'static str {
        match self {
            DecisionSource::Default => "default",
            DecisionSource::ExplicitRule => "rule",
            DecisionSource::Context => "context",
        }
    }
}

/// Every path this segment touches, resolved once: the redirect targets the
/// splitter already found, plus whatever the delete extractor recognises.
///
/// Two sources rather than one because they answer different questions -
/// `> .env` names a file the command WRITES, `rm .env` names one it DELETES -
/// and a gate that reads only one of them has a hole shaped like the other.
fn resolved_targets(
    segment: &str,
    ctx: &crate::resolve::EvalContext,
) -> Vec<crate::resolve::ResolvedTarget> {
    crate::resolve::command_targets(segment, ctx)
}

impl Policy {
    pub fn load(path: &Path) -> Result<Self> {
        let raw = std::fs::read_to_string(path)
            .with_context(|| format!("cannot read policy file {}", path.display()))?;
        let policy: Policy = serde_yaml::from_str(&raw)
            .with_context(|| format!("invalid policy YAML in {}", path.display()))?;
        policy
            .validate()
            .with_context(|| format!("invalid policy in {}", path.display()))?;
        Ok(policy)
    }

    /// THE MATCHER INVARIANT: a rule must carry at least one matcher, and
    /// neither is individually mandatory.
    ///
    ///     match: "git rm *"                        valid
    ///     match_path: "*/.ssh/*"                   valid
    ///     match: "git *" + match_path: "*/.ssh/*"  valid, both apply
    ///     neither                                  INVALID
    ///
    /// This replaces "`match` is always present", which was enforced by the
    /// type system and was the wrong rule: it forced path rules to invent a
    /// string pattern, and an invented pattern still fires. A rule with no
    /// matcher at all would silently never fire, which is worse than a parse
    /// error - a policy author would believe they were protected.
    ///
    /// Checked at both parse entry points rather than at evaluation, so an
    /// unfirable rule cannot reach a decision.
    pub fn validate(&self) -> Result<()> {
        for (i, rule) in self.rules.iter().enumerate() {
            if rule.r#match.is_none() && rule.match_path.is_none() {
                anyhow::bail!(
                    "rule {} has neither `match:` nor `match_path:` - a rule with no \
                     matcher can never fire, so it is a policy that says nothing while \
                     looking like it says something (action: {:?})",
                    i + 1,
                    rule.action
                );
            }
        }
        Ok(())
    }

    /// The built-in starter policy, parsed from the embedded template that
    /// `init` writes. Used by `check` when no project `.termaxa/policy.yaml`
    /// exists, so evaluation works with zero setup. Read-only surfaces only —
    /// `run` and `hook` require an explicit project policy (decision #19).
    pub fn builtin() -> Result<Self> {
        let policy: Policy = serde_yaml::from_str(crate::init::STARTER_POLICY)
            .context("failed to parse built-in starter policy")?;
        policy
            .validate()
            .context("built-in starter policy violates the matcher invariant")?;
        Ok(policy)
    }

    /// Walk up from `start` looking for `.termaxa/policy.yaml`.
    pub fn find_policy_file(start: &Path) -> Option<PathBuf> {
        let mut dir = Some(start.to_path_buf());
        while let Some(d) = dir {
            let candidate = d.join(".termaxa").join("policy.yaml");
            if candidate.is_file() {
                return Some(candidate);
            }
            dir = d.parent().map(|p| p.to_path_buf());
        }
        None
    }

    /// Shell-aware evaluation: split into segments, judge each, and let the
    /// MOST DANGEROUS segment govern the combined verdict (deny > ask > allow).
    /// Closes the v0.6.1 field-report bypass where `git status && <anything>`
    /// rode the `git status*` wildcard.
    pub fn evaluate_command(&self, command: &str, ctx: &crate::resolve::EvalContext) -> Decision {
        let segments = crate::shell::split_segments_deep(command);
        if segments.len() <= 1 {
            return self.evaluate(command, ctx);
        }
        let total = segments.len();
        let mut worst: Option<(usize, Decision)> = None;
        for (i, seg) in segments.iter().enumerate() {
            let d = self.evaluate(seg, ctx);
            // A shell wrapper whose string was read is transparent unless a
            // rule names it. Under a policy with no rule for `sh`, the
            // wrapper segment fell to the default and outranked the allow
            // its own string had earned - every command through the `wrap`
            // shim was asked. The string decides; `deny sh *` still counts,
            // because that rule names the wrapper. Decision of 2026-09-03.
            // Harness scaffolding is transparent on the same terms: Claude
            // Code's `shopt -u extglob … && eval '<cmd>' …` fell to the
            // default on `shopt` and outranked the verdict on `<cmd>`, so
            // routed through `wrap` every command it ran was refused
            // (Sep 10, 2026). The command inside the eval decides.
            if (seg.wraps || seg.scaffold) && d.matched_rule.is_none() {
                continue;
            }
            let replace = match &worst {
                None => true,
                // higher severity wins; on ties, an explicitly-matched rule
                // out-ranks a default fallthrough — name the real threat.
                Some((_, w)) => {
                    severity(d.action) > severity(w.action)
                        || (severity(d.action) == severity(w.action)
                            && w.matched_rule.is_none()
                            && d.matched_rule.is_some())
                }
            };
            if replace {
                worst = Some((i, d));
            }
        }
        let Some((i, d)) = worst else {
            // Every segment was an unnamed wrapper or scaffolding with no
            // command inside - a `-c` string that is all preamble, or the
            // depth limit cutting the reading off. Judge the whole line as
            // typed, which is the default for a line nobody named.
            return self.evaluate(command, ctx);
        };
        Decision {
            action: d.action,
            // The compound's verdict is the worst segment's verdict, so it
            // inherits that segment's source too - a compound denied because
            // one segment matched a rule is still an explicit-rule decision.
            source: d.source,
            matched_rule: d.matched_rule,
            reason: format!(
                "segment {}/{} `{}`{} — {}",
                i + 1,
                total,
                segments[i],
                segments[i]
                    .via
                    .as_deref()
                    .map(|v| format!(" (inside {v})"))
                    .unwrap_or_default(),
                d.reason
            ),
        }
    }

    pub fn evaluate(&self, command: &str, ctx: &crate::resolve::EvalContext) -> Decision {
        // First-match PER READING, MOST SEVERE across readings, earliest rule
        // on ties. See `readings` for what the readings are.
        //
        // Not "first rule matching any reading": post-#16 the policy pattern
        // for exceptions is an anchored allow ABOVE the deny it excepts, and
        // under any-reading matching a quoted spelling could reach the
        // exception through the tokenized reading while the raw reading sat
        // on the deny below it. Severity-across-readings makes that case fail
        // CLOSED instead: a spelling only some readings recognise as the
        // excepted command gets the deny, loudly — the same call #16 made for
        // unlisted reads. The cost, stated: quoted spellings of excepted
        // commands (`"cat" .termaxa/policy.yaml`) now deny where the plain
        // spelling still allows.
        let views = readings(command);
        let mut best: Option<(usize, &Rule)> = None;
        for v in &views {
            if let Some((idx, rule)) = self.rules.iter().enumerate().find(|(_, r)| r.matches(v)) {
                best = Some(match best {
                    None => (idx, rule),
                    Some((bi, br)) => {
                        if severity(rule.action) > severity(br.action)
                            || (severity(rule.action) == severity(br.action) && idx < bi)
                        {
                            (idx, rule)
                        } else {
                            (bi, br)
                        }
                    }
                });
            }
        }
        // Roadmap 2.4: the same rules, matched against what the command
        // actually TOUCHES rather than how it was spelled. Resolution happens
        // once per segment and is reused by both checks below.
        let targets = resolved_targets(command, ctx);

        // A `match_path` rule fires if ANY target matches, and the reason
        // names which one: a command with several targets is one command, and
        // the human approving it needs to know which path tripped the gate.
        let mut path_hit: Option<(usize, &Rule, String, crate::resolve::TargetRole)> = None;
        for (idx, rule) in self.rules.iter().enumerate() {
            if rule.match_path.is_none() {
                continue;
            }
            for t in &targets {
                // A path rule protects a file from being CHANGED, so it looks
                // only at roles that change one. `cp .env backup.txt` reads
                // .env and leaves it exactly as it was; denying that is the
                // same false positive the `*.env*` string pattern produced,
                // arriving through a new door (PR #27). `mv .env dst` DOES
                // fire, because a move removes its source - which is the
                // whole reason the extractor reports roles rather than a
                // flat list of paths.
                if !t.role.is_destructive() {
                    continue;
                }
                let Some(p) = &t.resolved else { continue };
                if rule.matches_path(&p.display().to_string()) {
                    let better = match &path_hit {
                        None => true,
                        Some((bi, br, _, _)) => {
                            severity(rule.action) > severity(br.action)
                                || (severity(rule.action) == severity(br.action) && idx < *bi)
                        }
                    };
                    if better {
                        path_hit = Some((idx, rule, t.display(), t.role));
                    }
                    break;
                }
            }
        }

        // An unresolved target carrying a sensitive shape fails closed. NOT a
        // short-circuit: it enters the same most-severe-wins tournament as
        // everything else, so an explicit allow above it still wins, which is
        // the escape hatch every other rule already has. One decision path,
        // not two.
        let shape_deny = targets
            .iter()
            .find(|t| t.is_unresolved() && !t.shapes.is_empty());

        match (path_hit, shape_deny) {
            (Some((_, rule, target, role)), _) if rule.action == Action::Deny => {
                return Decision {
                    action: rule.action,
                    source: DecisionSource::ExplicitRule,
                    matched_rule: Some(rule.label()),
                    // The role is in the sentence, not just in the type. A
                    // move that reported "overwriting .env" was correct in
                    // its verdict and wrong in its explanation: `mv` does not
                    // overwrite the source, it REMOVES it. The rule's reason
                    // is written for one case; the role says which case this
                    // actually is, and a human approving a prompt should not
                    // have to know that the two can differ.
                    reason: format!(
                        "target `{}` ({}) — {}",
                        target,
                        role.effect(),
                        rule.reason.clone().unwrap_or_else(|| format!(
                            "matched path rule `{}`",
                            rule.match_path.clone().unwrap_or_default()
                        ))
                    ),
                };
            }
            (_, Some(t)) => {
                let why = t
                    .shapes
                    .iter()
                    .map(|s| s.label())
                    .collect::<Vec<_>>()
                    .join(", ");
                // Only fails closed when it is WORSE than what the string
                // rules concluded - an explicit allow is still an allow.
                let base_sev = best
                    .map(|(_, r)| severity(r.action))
                    .unwrap_or_else(|| severity(self.default));
                if base_sev < severity(Action::Deny) && base_sev > severity(Action::Allow) {
                    return Decision {
                        action: Action::Deny,
                        source: DecisionSource::Context,
                        matched_rule: None,
                        reason: format!(
                            "target `{}` cannot be resolved and {} — refusing rather than \
                             guessing what it points at",
                            t.as_written, why
                        ),
                    };
                }
            }
            _ => {}
        }

        match best {
            Some((_, rule)) => Decision {
                action: rule.action,
                source: DecisionSource::ExplicitRule,
                matched_rule: Some(rule.label()),
                reason: rule
                    .reason
                    .clone()
                    .unwrap_or_else(|| format!("matched rule `{}`", rule.label())),
            },
            None => Decision {
                action: self.default,
                matched_rule: None,
                source: DecisionSource::Default,
                reason: format!("no rule matched; policy default is `{}`", self.default),
            },
        }
    }
}

/// The forms of a command a rule is matched against.
///
/// v0.15. Until now there was one: whitespace-collapsed and lowercased. Two
/// separate bugs came out of that single reading.
///
/// **Quotes.** `normalize` leaves them in, so `"rm" -rf /` missed the
/// `rm -rf /*` deny rule while the intent classifier — which tokenizes, and so
/// strips them — correctly called it a file delete. The layer that understood
/// the command was not the layer that blocked it. Same for `rm -r''f /`.
///
/// **Case.** `evaluate` lowercased the RULE as well as the command, so
/// `git branch -D` and `git branch -d` were both `git branch -d` before
/// `wildcard_match` ever ran. The distinction was destroyed at parse time, and
/// no amount of comparing forms at the match site could recover it. A rule
/// could not mean `-D` even if it spelled it.
///
/// So: three readings, and a rule matching ANY of them applies.
///
/// 1. `normalize` — whitespace-collapsed, lowercased. What we always had.
/// 2. tokenized-and-rejoined, lowercased — quotes gone, so disguises fail.
/// 3. tokenized-and-rejoined, CASE PRESERVED — so a rule that spells `-D`
///    in capitals means it.
///
/// This is strictly a widening: every rule that matched before still matches,
/// because reading 1 is unchanged. It can only make the gate more severe.
///
/// Reported by Tim Schipper.
pub fn readings(command: &str) -> Vec<String> {
    let base = normalize(powershell_command_of(command));
    let toks = crate::intent::tokens(command).join(" ");
    let cased = toks.split_whitespace().collect::<Vec<_>>().join(" ");
    let lowered = cased.to_lowercase();

    let mut out = vec![base];
    if !out.contains(&lowered) {
        out.push(lowered);
    }
    if !out.contains(&cased) {
        out.push(cased);
    }
    out
}

/// The command inside a PowerShell assignment or a leading parenthesis.
///
/// Codex on Windows writes `$target = Resolve-Path -LiteralPath .\scratch`
/// and `(Resolve-Path .\x).Path` (captured live, Sep 5, 2026). The command
/// is the cmdlet, not the variable it lands in: a head rule like
/// `Resolve-Path*` should read it, and a hard stop like `rm -rf /*` should
/// read `$x = rm -rf /` - which fell to the default before this. Only the
/// first reading is stripped; the other readings keep the spelling as
/// written, and a deny any reading matches still outranks an allow.
pub fn powershell_command_of(s: &str) -> &str {
    let t = s.trim_start();
    let mut rest = t;
    if let Some(after_dollar) = t.strip_prefix('$') {
        let ident_len = after_dollar
            .char_indices()
            .take_while(|(_, c)| c.is_ascii_alphanumeric() || *c == '_')
            .count();
        if ident_len > 0 {
            let after_ident = after_dollar[ident_len..].trim_start();
            if let Some(after_eq) = after_ident.strip_prefix('=') {
                if !after_eq.starts_with('=') {
                    rest = after_eq.trim_start();
                }
            }
        }
    }
    while let Some(inner) = rest.strip_prefix('(') {
        rest = inner.trim_start();
    }
    rest
}

/// Collapse whitespace runs to single spaces, trim, and lowercase.
/// Lowercasing makes matching case-insensitive: `DROP TABLE` must not
/// bypass a `drop table` rule.
pub fn normalize(s: &str) -> String {
    s.split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_lowercase()
}

/// Iterative wildcard match where `*` matches any (possibly empty) run of chars.
/// Case-sensitive. Linear-ish, no recursion, no regex dependency.
/// Match a component pattern against a component path.
///
/// `*` as a WHOLE component means "any run of components, including none" -
/// the `**` of most glob languages, spelled `*` because a path rule is always
/// about paths and the two-star distinction buys nothing here. A `*` INSIDE a
/// component (`id_*`, `*.log`) matches within that component only, and never
/// across a separator.
fn match_components(pat: &[String], seg: &[String]) -> bool {
    match pat.split_first() {
        // Pattern exhausted: matches only if the path is too.
        None => seg.is_empty(),
        Some((head, rest)) if head == "*" => {
            // Try consuming zero, one, two ... components here.
            (0..=seg.len()).any(|skip| match_components(rest, &seg[skip..]))
        }
        Some((head, rest)) => match seg.split_first() {
            None => false,
            Some((s, srest)) => wildcard_match(head, s) && match_components(rest, srest),
        },
    }
}

pub fn wildcard_match(pattern: &str, text: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let t: Vec<char> = text.chars().collect();
    let (mut pi, mut ti) = (0usize, 0usize);
    let (mut star, mut mark) = (usize::MAX, 0usize);

    while ti < t.len() {
        if pi < p.len() && (p[pi] == t[ti]) {
            pi += 1;
            ti += 1;
        } else if pi < p.len() && p[pi] == '*' {
            star = pi;
            mark = ti;
            pi += 1;
        } else if star != usize::MAX {
            pi = star + 1;
            mark += 1;
            ti = mark;
        } else {
            return false;
        }
    }
    while pi < p.len() && p[pi] == '*' {
        pi += 1;
    }
    pi == p.len()
}

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

    /// Evaluation context for tests: the current directory as both cwd and
    /// root. No test here depends on resolution, which is the point - this
    /// commit changed no verdicts.
    fn here() -> crate::resolve::EvalContext {
        crate::resolve::EvalContext::at(std::path::Path::new("."))
    }

    fn policy_from(yaml: &str) -> Policy {
        serde_yaml::from_str(yaml).expect("policy must parse")
    }

    #[test]
    fn an_omitted_field_gets_the_documented_default() {
        let minimal = policy_from("default: ask\nrules: []\n");
        assert_eq!(minimal.version, 1, "version 1 is the current schema");

        let notifying = policy_from(
            "default: ask\nrules: []\nnotify:\n  webhook: https://example.invalid/hook\n",
        );
        assert_eq!(
            notifying.notify.expect("the notify block must parse").on,
            ["deny"],
            "notifying on every decision trains the reader to ignore them"
        );
    }

    #[test]
    fn case_sensitivity_is_written_out_only_when_it_was_asked_for() {
        let plain = Rule {
            r#match: Some("ls*".into()),
            action: Action::Allow,
            reason: None,
            case_sensitive: false,
            match_path: None,
        };
        let json = serde_json::to_string(&plain).expect("a rule must serialize");
        assert!(
            !json.contains("case_sensitive"),
            "the default must not clutter every rule: {json}"
        );

        let strict = Rule {
            r#match: Some("git branch -D*".into()),
            action: Action::Deny,
            reason: None,
            case_sensitive: true,
            match_path: None,
        };
        let json = serde_json::to_string(&strict).expect("a rule must serialize");
        assert!(
            json.contains("case_sensitive"),
            "an opt-in has to survive the round trip: {json}"
        );
    }

    #[test]
    fn the_readings_include_the_tokenized_form_a_quote_would_hide() {
        let views = readings(r#""rm" -rf /"#);
        assert!(
            views.contains(&r#""rm" -rf /"#.to_string()),
            "the raw reading is still there: {views:?}"
        );
        assert!(
            views.contains(&"rm -rf /".to_string()),
            "quotes must not hide a command from its rule: {views:?}"
        );
    }

    #[test]
    fn an_ordinary_command_is_not_read_twice() {
        // Nothing to strip and nothing to lower: one reading is enough, and a
        // duplicate would just be work.
        assert_eq!(readings("git status"), ["git status"]);
    }

    #[test]
    fn the_earliest_of_two_equally_severe_rules_is_the_one_reported() {
        // The quoted spelling matches rule 1; the tokenized reading matches
        // rule 2. Same severity, so first-match-wins has to survive there
        // being several readings.
        let p = policy_from(
            "default: allow\nrules:\n  - match: '\"rm\"*'\n    action: deny\n  \
             - match: \"rm -rf*\"\n    action: deny\n",
        );
        let d = p.evaluate(r#""rm" -rf /"#, &here());
        assert_eq!(d.action, Action::Deny);
        assert_eq!(d.matched_rule.as_deref(), Some("\"rm\"*"));
    }

    #[test]
    fn the_earliest_rule_still_wins_when_the_order_is_reversed() {
        // The mirror image, so "earliest" cannot be satisfied by accident of
        // which reading happens to be examined first.
        let p = policy_from(
            "default: allow\nrules:\n  - match: \"rm -rf*\"\n    action: deny\n  \
             - match: '\"rm\"*'\n    action: deny\n",
        );
        let d = p.evaluate(r#""rm" -rf /"#, &here());
        assert_eq!(d.matched_rule.as_deref(), Some("rm -rf*"));
    }

    #[test]
    fn a_spelling_only_one_reading_recognises_gets_the_worse_verdict() {
        // The documented cost of severity-across-readings: the raw reading
        // matches the allow, the tokenized reading matches the deny, and the
        // deny governs. This case fails CLOSED on purpose.
        let p = policy_from(
            "default: allow\nrules:\n  - match: '\"cat\"*'\n    action: allow\n  \
             - match: \"cat .termaxa*\"\n    action: deny\n",
        );
        let d = p.evaluate(r#""cat" .termaxa/policy.yaml"#, &here());
        assert_eq!(
            d.action,
            Action::Deny,
            "a spelling only some readings recognise must not reach the exception: {}",
            d.reason
        );
    }

    #[test]
    fn the_first_of_two_equally_dangerous_segments_is_the_one_named() {
        // Naming the later one would point the reader at the second-worst
        // thing in the command.
        let p = policy_from(
            "default: allow\nrules:\n  - match: \"rm -rf*\"\n    action: deny\n  \
             - match: \"drop table*\"\n    action: deny\n",
        );
        let d = p.evaluate_command("rm -rf /tmp/x && drop table users", &here());
        assert_eq!(d.action, Action::Deny);
        assert_eq!(d.matched_rule.as_deref(), Some("rm -rf*"));
        assert!(d.reason.contains("segment 1/2"), "{}", d.reason);
    }

    #[test]
    fn an_explicit_allow_never_outranks_a_more_dangerous_default() {
        // Segment 1 falls through to the `ask` default; segment 2 matches an
        // explicit allow. A matched rule breaks TIES between equally severe
        // segments — it does not lower the verdict.
        let p = policy_from("default: ask\nrules:\n  - match: \"ls*\"\n    action: allow\n");
        let d = p.evaluate_command("curl https://example.invalid/x | ls", &here());
        assert_eq!(
            d.action,
            Action::Ask,
            "the most dangerous segment governs: {}",
            d.reason
        );
    }
}

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

    /// Evaluation context for tests: the current directory as both cwd and
    /// root. No test here depends on resolution, which is the point - this
    /// commit changed no verdicts.
    fn here() -> crate::resolve::EvalContext {
        crate::resolve::EvalContext::at(std::path::Path::new("."))
    }

    /// Schipper review round 2, finding 2. `intent::tokens` strips quotes and
    /// `policy::normalize` does not, so the classifier saw through disguises
    /// the gate could not. The layer that understood the command was not the
    /// layer that blocked it.
    #[test]
    fn quoting_cannot_disguise_a_command_from_a_rule() {
        let p = Policy::builtin().unwrap();
        for cmd in [
            r#""rm" -rf /"#,
            r#"rm -r''f /"#,
            r#""rm" "-rf" "/""#,
            r#"'rm' -rf /"#,
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "{cmd} must not slip past the deny rule by quoting"
            );
        }
    }

    /// The case-preservation half. A lowercase rule stays case-insensitive; a
    /// rule with an uppercase letter is matched as written.
    #[test]
    fn a_lowercase_rule_still_matches_either_case() {
        let p = Policy::builtin().unwrap();
        // `*drop table*` is written lowercase, so it must catch both.
        assert_eq!(
            p.evaluate_command("psql -c \"DROP TABLE users\"", &here())
                .action,
            Action::Deny
        );
        assert_eq!(
            p.evaluate_command("psql -c \"drop table users\"", &here())
                .action,
            Action::Deny
        );
        // `*rm -rf*` likewise.
        assert_eq!(
            p.evaluate_command("rm -RF /tmp/x", &here()).action,
            Action::Deny
        );
    }

    /// Until v0.15 this was impossible: `evaluate` lowercased the rule as well
    /// as the command, so `-D` and `-d` were the same string before matching.
    /// The distinction is opted into with `case_sensitive: true`.
    #[test]
    fn a_case_sensitive_rule_means_the_case_it_spells() {
        let rule = Rule {
            r#match: Some("git branch*-D*".into()),
            action: Action::Deny,
            reason: None,
            case_sensitive: true,
            match_path: None,
        };
        let views_upper = readings("git branch -D main");
        let views_lower = readings("git branch -d main");

        assert!(
            views_upper.iter().any(|v| rule.matches(v)),
            "a case-sensitive rule spelling -D must match -D"
        );
        assert!(
            !views_lower.iter().any(|v| rule.matches(v)),
            "a case-sensitive rule spelling -D must NOT match -d — that was the bug"
        );
    }

    /// The collateral the first draft shipped, kept impossible: an uppercase
    /// SPELLING without the field changes nothing. `*Remove-Item*-Recurse*`
    /// has shipped case-insensitive since v0.11, PowerShell accepts any
    /// casing, and agents emit it.
    #[test]
    fn uppercase_spelled_rules_stay_case_insensitive_without_the_field() {
        let p = Policy::builtin().unwrap();
        for cmd in [
            "remove-item -recurse -force c:\\temp\\x",
            "REMOVE-ITEM -Recurse c:\\x",
            // NOTE: *Get-ChildItem*Remove-Item* is NOT here — it was already
            // unreachable in v0.14.2 (split_segments cuts pipelines at `|`,
            // so both words never share a segment). Reported separately.
            "remove-item -force c:\\x",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "{cmd} matched a deny in v0.14.2 and must keep matching"
            );
        }
        // And the starter policy opts in exactly once, on purpose.
        let cs: Vec<String> = p
            .rules
            .iter()
            .filter(|r| r.case_sensitive)
            .map(|r| r.label())
            .collect();
        assert_eq!(
            cs,
            vec!["git branch*-D*"],
            "case sensitivity is a deliberate, rare opt-in"
        );
    }

    /// Severity across readings, against the #16 exception block. A quoted
    /// spelling only the tokenized reading recognises as the excepted command
    /// fails CLOSED — the raw reading hits the `*.termaxa*` deny below the
    /// exception, and the more severe verdict governs. The plain spelling is
    /// untouched. Stated behavior change to the exception block, not a slip.
    #[test]
    fn a_quoted_spelling_of_an_excepted_command_fails_closed() {
        let p = Policy::builtin().unwrap();
        assert_eq!(
            p.evaluate_command("cat .termaxa/policy.yaml", &here())
                .action,
            Action::Allow,
            "the plain excepted read stays allowed"
        );
        assert_eq!(
            p.evaluate_command(r#""cat" .termaxa/policy.yaml"#, &here())
                .action,
            Action::Deny,
            "a disguised spelling of a .termaxa read fails closed, loudly"
        );
    }

    /// The whole change is a widening. Reading 1 is unchanged, so nothing that
    /// matched before can stop matching.
    #[test]
    fn the_extra_readings_can_only_add_matches() {
        for cmd in [
            "git status",
            "ls -la",
            "cargo build",
            "echo hello world",
            "git push --force origin main",
        ] {
            let base = normalize(cmd);
            assert!(
                readings(cmd).contains(&base),
                "the original normalized reading must always be present"
            );
        }
    }

    #[test]
    fn wildcard_basics() {
        assert!(wildcard_match("git push*", "git push"));
        assert!(wildcard_match("git push*", "git push origin main"));
        assert!(!wildcard_match("git push*", "git pull"));
        assert!(wildcard_match("*--force*", "git push --force origin"));
        assert!(wildcard_match("git status", "git status"));
        assert!(!wildcard_match("git status", "git status -s"));
        assert!(wildcard_match("*", "anything at all"));
    }

    #[test]
    fn first_match_wins() {
        let policy: Policy = serde_yaml::from_str(
            r#"
version: 1
default: ask
rules:
  - match: "git push*--force*"
    action: deny
  - match: "git push*"
    action: allow
"#,
        )
        .unwrap();
        assert_eq!(
            policy.evaluate("git push origin main", &here()).action,
            Action::Allow
        );
        assert_eq!(
            policy
                .evaluate("git push --force origin main", &here())
                .action,
            Action::Deny
        );
        assert_eq!(
            policy.evaluate("terraform apply", &here()).action,
            Action::Ask
        );
    }

    #[test]
    fn normalization() {
        let policy: Policy = serde_yaml::from_str(
            r#"
rules:
  - match: "kubectl delete*"
    action: deny
"#,
        )
        .unwrap();
        assert_eq!(
            policy.evaluate("kubectl   delete   pod x", &here()).action,
            Action::Deny
        );
    }

    #[test]
    fn case_insensitive() {
        let policy: Policy = serde_yaml::from_str(
            r#"
rules:
  - match: "*drop table*"
    action: deny
"#,
        )
        .unwrap();
        assert_eq!(
            policy
                .evaluate("psql -c 'DROP TABLE users'", &here())
                .action,
            Action::Deny
        );
    }

    /// #62: a rule that allows the shell does not allow what the shell is
    /// told to run. The string's own segments are judged, and the reason
    /// says which wrapper the losing segment was read through.
    #[test]
    fn a_shell_c_string_is_judged_by_what_it_runs() {
        let policy: Policy = serde_yaml::from_str(
            r#"
default: ask
rules:
  - match: "sh *"
    action: allow
  - match: "rm -rf *"
    action: deny
"#,
        )
        .unwrap();
        let d = policy.evaluate_command(r#"sh -c "rm -rf ./dist""#, &here());
        assert_eq!(d.action, Action::Deny);
        assert!(d.reason.contains("segment 2/2"), "{}", d.reason);
        assert!(d.reason.contains("(inside sh -c)"), "{}", d.reason);
        assert!(d.reason.contains("rm -rf ./dist"), "{}", d.reason);
        // The wrapper rule still applies to what it names; the string is
        // judged on its own, so an unmatched command inside falls to the
        // default exactly as it would typed at the top level.
        assert_eq!(
            policy.evaluate_command("sh clean.sh", &here()).action,
            Action::Allow
        );
        let d = policy.evaluate_command(r#"sh -c "ls -la""#, &here());
        assert_eq!(d.action, Action::Ask, "{}", d.reason);
        assert!(d.reason.contains("(inside sh -c)"), "{}", d.reason);
    }

    /// Claude Code's Bash tool call as it arrives through `wrap` (Sep 10,
    /// 2026, verbatim from the audit log): the starter judges the command
    /// inside the `eval`, not the `shopt`/`setopt` preamble that used to
    /// fall to the default and refuse every command the agent ran. A read
    /// is allowed and the reason names it; a delete is denied; the zsh form
    /// and the form that sources a snapshot read the same; and a preamble
    /// that is not the measured one falls back to the default - closed.
    #[test]
    fn claude_codes_tool_call_is_judged_by_the_command_inside_the_eval() {
        let starter = Policy::builtin().unwrap();
        let bash = |cmd: &str| {
            format!(
                r#"bash -c -l "shopt -u extglob 2>/dev/null || true && {{ \\builtin unalias -- 'unsetenv'; \\builtin unset -f -- 'unsetenv'; }} >/dev/null 2>&1 || true && eval '{cmd}' < /dev/null && pwd -P >| /tmp/claude-c32c-cwd""#
            )
        };
        let d = starter.evaluate_command(&bash("ls -la /home/dev/proj/"), &here());
        assert_eq!(d.action, Action::Allow, "{}", d.reason);
        assert!(
            d.reason.contains("`ls -la /home/dev/proj/` (inside eval)"),
            "the reason names the agent's command: {}",
            d.reason
        );
        let d = starter.evaluate_command(&bash("rm -rf ./scratch"), &here());
        assert_eq!(d.action, Action::Deny, "{}", d.reason);
        assert!(d.reason.contains("Recursive force delete"), "{}", d.reason);
        let d = starter.evaluate_command(&bash("env"), &here());
        assert_eq!(
            d.action,
            Action::Allow,
            "Claude Code's first act: {}",
            d.reason
        );
        // Refused on `cd` under `wrap`, Sep 11, 2026: a read-only command
        // with one word in it that had no rule.
        let d = starter.evaluate_command(
            &bash(
                r#"ls -la /home/dev/proj/scratch; echo "---git-tracked---"; cd /home/dev/proj && git ls-files scratch"#,
            ),
            &here(),
        );
        assert_eq!(d.action, Action::Allow, "{}", d.reason);
        let d = starter.evaluate_command("git tag -d v1.0", &here());
        assert_eq!(
            d.action,
            Action::Ask,
            "a tag delete stays on the default: {}",
            d.reason
        );
        let d = starter.evaluate_command(&bash("no-such-command-tmx"), &here());
        assert_eq!(
            d.action,
            Action::Ask,
            "an unknown command still asks: {}",
            d.reason
        );

        let zsh = r#"zsh -c -l "setopt NO_EXTENDED_GLOB NO_BARE_GLOB_QUAL 2>/dev/null || true && { \\builtin unalias -- 'unsetenv'; \\builtin unset -f -- 'unsetenv'; } >/dev/null 2>&1 || true && eval 'git status' < /dev/null && pwd -P >| /tmp/claude-b1de-cwd""#;
        let d = starter.evaluate_command(zsh, &here());
        assert_eq!(d.action, Action::Allow, "{}", d.reason);
        assert!(
            d.reason.contains("`git status` (inside eval)"),
            "{}",
            d.reason
        );

        let sourced = r#"bash -c "source /home/dev/.claude/shell-snapshots/snapshot-bash-1789077199590-d2kylp.sh 2>/dev/null || true && shopt -u extglob 2>/dev/null || true && { \\builtin unalias -- 'unsetenv'; \\builtin unset -f -- 'unsetenv'; } >/dev/null 2>&1 || true && eval 'cat README.md' < /dev/null && pwd -P >| /tmp/claude-0a1b-cwd""#;
        let d = starter.evaluate_command(sourced, &here());
        assert_eq!(d.action, Action::Allow, "{}", d.reason);

        // Drift fails closed: a preamble the reading does not know is a
        // segment the default applies to, and the refusal names it.
        let drifted =
            r#"bash -c "shopt -u extglob nullglob 2>/dev/null || true && eval 'ls' < /dev/null""#;
        let d = starter.evaluate_command(drifted, &here());
        assert_eq!(d.action, Action::Ask, "{}", d.reason);
        assert!(
            d.reason.contains("`shopt -u extglob nullglob"),
            "{}",
            d.reason
        );
        // And a `source` of anything but the harness's own snapshot is judged.
        let foreign = r#"bash -c "source /home/dev/.claude/shell-snapshots/../../.bashrc 2>/dev/null || true && eval 'ls' < /dev/null""#;
        let d = starter.evaluate_command(foreign, &here());
        assert_eq!(d.action, Action::Ask, "{}", d.reason);
    }

    /// A wrapper no rule names is transparent: `sh -c "echo hi"` is allowed
    /// by the starter policy's `echo *`, where the `sh` segment used to fall
    /// to the default and outrank it. A rule that names the wrapper still
    /// counts, and a script file - not read, so not a wrapper - still falls
    /// to the default.
    #[test]
    fn an_unnamed_wrapper_is_transparent_and_a_named_one_is_not() {
        let starter = Policy::builtin().unwrap();
        let d = starter.evaluate_command(r#"sh -c "echo hi""#, &here());
        assert_eq!(d.action, Action::Allow, "{}", d.reason);
        assert!(d.reason.contains("(inside sh -c)"), "{}", d.reason);
        assert_eq!(
            starter
                .evaluate_command(r#"sh -c "no-such-command-tmx""#, &here())
                .action,
            Action::Ask,
            "an unmatched command inside still falls to the default"
        );
        assert_eq!(
            starter.evaluate_command("sh script.sh", &here()).action,
            Action::Ask,
            "a script file is not read, so it is not transparent"
        );
        let names_the_shell: Policy = serde_yaml::from_str(
            r#"
default: ask
rules:
  - match: "sh *"
    action: deny
  - match: "echo *"
    action: allow
"#,
        )
        .unwrap();
        let d = names_the_shell.evaluate_command(r#"sh -c "echo hi""#, &here());
        assert_eq!(d.action, Action::Deny, "{}", d.reason);
        assert!(d.reason.contains("segment 1/2"), "{}", d.reason);
    }

    #[test]
    fn compound_commands_cannot_hide_behind_prefixes() {
        // v0.6.1 field report: `git status && <anything>` rode `git status*`.
        let policy: Policy = serde_yaml::from_str(
            r#"
default: ask
rules:
  - match: "git status*"
    action: allow
  - match: "rm -rf /*"
    action: deny
"#,
        )
        .unwrap();
        // the trench-coat attack: worst segment governs
        let d = policy.evaluate_command("git status && rm -rf /", &here());
        assert_eq!(d.action, Action::Deny);
        assert!(d.reason.contains("rm -rf /"));
        // benign compound with an unmatched segment falls to default (ask)
        assert_eq!(
            policy
                .evaluate_command("git status && echo hi", &here())
                .action,
            Action::Ask
        );
        // single commands behave exactly as before
        assert_eq!(
            policy.evaluate_command("git status", &here()).action,
            Action::Allow
        );
    }

    /// Field report, Sep 2026: the parent agent sent to recover a wiped
    /// drive deleted the shadow copy it was restoring from. Every spelling of
    /// that delete is a hard stop; listing shadow copies is not.
    #[test]
    fn deleting_a_recovery_point_is_a_hard_stop_in_every_spelling() {
        let p = Policy::builtin().unwrap();
        for cmd in [
            "vssadmin delete shadows /all /quiet",
            "vssadmin Delete Shadows /For=C: /Oldest",
            "wmic shadowcopy delete",
            "wmic shadowcopy delete /nointeractive",
            "(Get-WmiObject Win32_ShadowCopy).Delete()",
            "Get-WmiObject Win32_ShadowCopy | Remove-WmiObject",
            "Get-CimInstance Win32_ShadowCopy | Remove-CimInstance",
            r#"cmd /c "vssadmin delete shadows /all /quiet""#,
        ] {
            let d = p.evaluate_command(cmd, &here());
            assert_eq!(d.action, Action::Deny, "{cmd}: {}", d.reason);
            assert!(d.reason.contains("recover"), "{cmd}: {}", d.reason);
        }
        // Known gap, stated rather than hidden: the pipeline form is split at
        // the pipe, and `$_.Delete()` on its own names nothing. It falls to
        // the default, which asks - not an allow, and not yet a hard stop.
        let d = p.evaluate_command(
            "Get-WmiObject Win32_ShadowCopy | ForEach-Object { $_.Delete() }",
            &here(),
        );
        assert_eq!(d.action, Action::Ask, "{}", d.reason);
        // diskshadow runs a script file the gate cannot read: the default, not an allow.
        assert_ne!(
            p.evaluate_command("diskshadow /s wipe.txt", &here()).action,
            Action::Allow
        );
        assert_ne!(
            p.evaluate_command("vssadmin list shadows", &here()).action,
            Action::Deny,
            "listing recovery points is not deleting them"
        );
    }

    /// Codex on Windows speaks PowerShell (captured live, Sep 5, 2026): a
    /// read-only probe is `$target = Resolve-Path -LiteralPath .\scratch`
    /// or `Get-Item -LiteralPath .\scratch -Force | Select-Object FullName`.
    /// Under Codex an ask is a refusal, so the read-only cmdlets are allowed
    /// and the assignment is read as the command it assigns - which also
    /// means a hard stop behind an assignment is now a hard stop.
    #[test]
    fn a_powershell_assignment_is_judged_by_the_command_it_assigns() {
        let p = Policy::builtin().unwrap();
        for cmd in [
            "$target = Resolve-Path -LiteralPath .\\scratch -ErrorAction Stop",
            "$t = (Resolve-Path -LiteralPath .\\scratch -ErrorAction Stop).Path",
            "Get-Item -LiteralPath .\\scratch -Force | Select-Object FullName, PSIsContainer",
            "Get-ChildItem -Recurse -File | Measure-Object",
            "Test-Path -LiteralPath .\\scratch -PathType Container",
        ] {
            let d = p.evaluate_command(cmd, &here());
            assert_eq!(d.action, Action::Allow, "{cmd}: {}", d.reason);
        }
        for cmd in [
            "$x = Remove-Item -LiteralPath .\\dist -Recurse -Force",
            "$x = rm -rf /",
            "(Get-WmiObject Win32_ShadowCopy).Delete()",
        ] {
            let d = p.evaluate_command(cmd, &here());
            assert_eq!(d.action, Action::Deny, "{cmd}: {}", d.reason);
        }
        // A cmdlet whose purpose is to run a script block is not read-only,
        // and the block can hide a delete: the pipeline is judged by its
        // most dangerous segment, and `Where-Object` itself is not allowed.
        assert_eq!(
            p.evaluate_command(
                "Get-ChildItem | ForEach-Object { Remove-Item $_ -Recurse }",
                &here()
            )
            .action,
            Action::Deny
        );
        assert_eq!(
            p.evaluate_command("Get-ChildItem | Where-Object { $_.Length -gt 0 }", &here())
                .action,
            Action::Ask
        );
        // Codex's first probe also carried `$target.Path` and an `if` block;
        // those segments are expressions the starter does not name, so the
        // compound still asks. Stated, not hidden.
        let d = p.evaluate_command(
            "$target = Resolve-Path -LiteralPath .\\scratch -ErrorAction Stop; $target.Path; if (-not (Test-Path -LiteralPath $target.Path -PathType Container)) { throw 'no' }",
            &here(),
        );
        assert_eq!(d.action, Action::Ask, "{}", d.reason);
    }

    #[test]
    fn builtin_policy_parses_and_gates() {
        // The embedded starter policy must always parse (it backs `check`'s
        // zero-setup demo mode) and must classify the headline cases.
        let p = Policy::builtin().expect("built-in starter policy must parse");
        assert_eq!(p.evaluate_command("rm -rf /", &here()).action, Action::Deny);
        assert_eq!(
            p.evaluate_command("psql -c 'DROP TABLE users'", &here())
                .action,
            Action::Deny
        );
        assert_eq!(
            p.evaluate_command("git status", &here()).action,
            Action::Allow
        );
        assert_eq!(
            p.evaluate_command("git push --force origin main", &here())
                .action,
            Action::Deny
        );
    }

    /// A rule that cannot be reached is not a rule. `*Get-ChildItem*Remove-Item*`
    /// shipped from v0.11 and could never fire: `split_segments` cuts at the
    /// `|`, so no segment ever contains both names. It was removed in v0.16
    /// rather than reworked, and this test records what the policy does with
    /// the pipeline instead, so its removal stays deliberate.
    ///
    /// A bare `Remove-Item` with no destructive flag is `ask`, exactly as
    /// `rm x` and `del x` are: deleting one named path is ordinary work, and a
    /// gate that denies it gets uninstalled (#48). The flagged spellings are
    /// still denied by the sibling rules, which DO fire, because each name and
    /// its flag live in the same segment.
    #[test]
    fn the_powershell_pipeline_is_asked_and_its_flagged_forms_denied() {
        let p = Policy::builtin().unwrap();
        for cmd in ["Get-ChildItem | Remove-Item", "Remove-Item x"] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Ask,
                "{cmd}: an unflagged delete is ordinary work"
            );
        }
        for cmd in [
            "Get-ChildItem . | Remove-Item -Force",
            "Get-ChildItem -Path x | Remove-Item -Recurse -Force",
            "Remove-Item -Recurse x",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "{cmd}: the flag is in the same segment as the name, so it fires"
            );
        }
    }

    #[test]
    fn the_starter_policy_defends_its_own_configuration() {
        let p = Policy::builtin().expect("built-in starter policy must parse");

        // The command from the review: `echo *` sat below the denies and
        // allowed this outright, and everything after it was judged by a
        // policy the agent had written.
        let d = p.evaluate_command("echo 'default: allow' > .termaxa/policy.yaml", &here());
        assert_eq!(d.action, Action::Deny);
        assert_eq!(d.matched_rule.as_deref(), Some("*.termaxa*policy*"));

        for cmd in [
            "cat /tmp/mine.yaml > .termaxa/policy.yaml",
            "rm -f .termaxa/policy.yaml",
            "sed -i 's/deny/allow/g' .termaxa/policy.yaml",
            "mv /tmp/mine.yaml .termaxa/policy.yaml",
            "copy C:\\tmp\\mine.yaml .termaxa\\policy.yaml",
            "echo '{}' > .claude/settings.json",
            "rm .cursor/hooks.json",
            "mv .codex/hooks.json /tmp/",
            "rm .github/hooks/hooks.json",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "must not be able to edit the gate: {cmd}"
            );
        }

        // The self-defence block has to sit ABOVE the read-only allows, or
        // first-match-wins hands it back. Prove the ordering, not just the
        // verdict, by checking a command that both blocks match.
        let idx_self = p
            .rules
            .iter()
            .position(|r| r.label() == "*.termaxa*policy*")
            .expect("self-defence rule must exist");
        let idx_echo = p
            .rules
            .iter()
            .position(|r| r.label() == "echo *")
            .expect("echo rule must exist");
        assert!(
            idx_self < idx_echo,
            "self-defence must be reachable: it sits at {idx_self}, `echo *` at {idx_echo}"
        );
    }

    #[test]
    fn reviewing_the_policy_in_a_pr_still_works() {
        let p = Policy::builtin().expect("built-in starter policy must parse");
        // The README calls the policy an in-repo artifact, "reviewable in
        // PRs". These are the commands that workflow is made of; a blanket
        // deny on `*.termaxa*` made every one of them impossible.
        for cmd in [
            "git add .termaxa/policy.yaml",
            "git diff .termaxa/policy.yaml",
            "git diff --cached .termaxa/policy.yaml",
            "git status .termaxa/",
            "git log --oneline .termaxa/policy.yaml",
            "git show HEAD:.termaxa/policy.yaml",
            "git commit -m \"tighten the policy\" .termaxa/policy.yaml",
            "cat .termaxa/policy.yaml",
            "cp .termaxa/policy.yaml backup.yaml",
            // One pattern covers both separators, same as the deny it excepts.
            "git diff .termaxa\\policy.yaml",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Allow,
                "the documented review workflow must not be blocked: {cmd}"
            );
        }
    }

    #[test]
    fn the_review_exceptions_only_go_one_direction() {
        let p = Policy::builtin().expect("built-in starter policy must parse");
        // Every exception above the deny is a read. Anything that can put
        // bytes INTO the policy stays denied, including the git verbs whose
        // job is to overwrite the working tree from a ref.
        for cmd in [
            "git checkout .termaxa/policy.yaml",
            "git checkout evil-branch -- .termaxa/policy.yaml",
            "git restore .termaxa/policy.yaml",
            "git config core.hooksPath .termaxa/evil",
            "cp backup.yaml .termaxa/policy.yaml",
            "cat backup.yaml > .termaxa/policy.yaml",
            "tee .termaxa/policy.yaml",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "writes into the gate's config must stay denied: {cmd}"
            );
        }
    }

    #[test]
    fn a_review_exception_cannot_shadow_the_hook_config_denies() {
        let p = Policy::builtin().expect("built-in starter policy must parse");
        // A trailing `*` swallows a redirect, so `cat .termaxa*` matches
        // `cat .termaxa/policy.yaml > .claude/settings.json` as well. At the
        // top of the file these allows would shadow the denies that exist to
        // stop exactly that. They sit below them instead.
        for cmd in [
            "cat .termaxa/policy.yaml > .claude/settings.json",
            "git diff .termaxa/policy.yaml > .claude/settings.json",
            "git add .termaxa/policy.yaml > .cursor/hooks.json",
            "cp .termaxa/policy.yaml .codex/hooks.json",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "an exception must not become a way through: {cmd}"
            );
        }

        // Prove the ordering, not just the verdict.
        let idx = |pat: &str| {
            p.rules
                .iter()
                .position(|r| r.label() == pat)
                .unwrap_or_else(|| panic!("rule `{pat}` must exist"))
        };
        assert!(
            idx("*.claude*settings*") < idx("cat .termaxa*"),
            "the hook-config denies must outrank the review exceptions"
        );
        assert!(
            idx("cat .termaxa*") < idx("*.termaxa*policy*"),
            "the review exceptions must outrank the deny they except"
        );
    }

    #[test]
    fn no_preserve_root_is_denied_by_name() {
        let p = Policy::builtin().expect("built-in starter policy must parse");
        // GNU rm refuses a bare `rm -rf /`. This is the spelling it obeys,
        // and it does not contain the substring `rm -rf` that the famous
        // rule matches on.
        assert!(!"rm --no-preserve-root -rf /".contains("rm -rf"));
        for cmd in [
            "rm --no-preserve-root -rf /",
            "sudo rm --no-preserve-root -rf /",
            "rm -r --no-preserve-root /",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "{cmd}"
            );
        }
    }

    #[test]
    fn read_only_prefixes_do_not_swallow_neighbouring_commands() {
        let p = Policy::builtin().expect("built-in starter policy must parse");

        // Still allowed — including bare `ls`, which needs its own rule
        // because `ls *` requires the space.
        for cmd in ["ls", "ls -la src", "grep -rn fn src", "cat Cargo.toml"] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Allow,
                "{cmd}"
            );
        }

        // Different programs that merely start with the same letters. `ls*`
        // and `grep*` used to allow all of these.
        for cmd in ["lsof -i :5432", "lsblk", "lsattr -R /", "grepdiff --help"] {
            assert_ne!(
                p.evaluate_command(cmd, &here()).action,
                Action::Allow,
                "a prefix is not a command: {cmd}"
            );
        }
    }
}

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

    /// Evaluation context for tests: the current directory as both cwd and
    /// root. No test here depends on resolution, which is the point - this
    /// commit changed no verdicts.
    fn here() -> crate::resolve::EvalContext {
        crate::resolve::EvalContext::at(std::path::Path::new("."))
    }

    /// Roadmap 2.4, the point of the whole change: a rule matched against the
    /// RESOLVED target catches every spelling of one path, which no number of
    /// added string patterns could do. The reason names WHICH target tripped
    /// it, because a command may touch several and the human approving it
    /// needs to know which one.
    #[test]
    fn a_path_rule_catches_every_spelling_and_names_the_target() {
        let p = Policy::builtin().unwrap();
        let d = p.evaluate_command("cat /dev/null > ./.env", &here());
        assert_eq!(d.action, Action::Deny);
        assert!(
            d.reason.contains(".env"),
            "the reason must name the target that tripped the gate: {}",
            d.reason
        );
        // Control leg: the path rule does not fire on a path it does not
        // match. `cat *` allows this one, which is exactly the point - the
        // ordinary file reaches its ordinary verdict, and only the protected
        // path is pulled out of it.
        let ordinary = p.evaluate_command("cat /dev/null > ./notes.md", &here());
        assert_eq!(ordinary.action, Action::Allow);
        assert_eq!(ordinary.matched_rule.as_deref(), Some("cat *"));
    }

    /// An explicit `allow` still wins over an unresolved sensitive target, and
    /// that is the DECIDED behaviour, not an oversight.
    ///
    /// `echo x > $CONFIG` cannot be resolved — the gate does not know what
    /// file that is — and the target carries the UnexpandedVar shape. That
    /// contributes a deny reading, but the reading enters the same
    /// most-severe-wins tournament as everything else and loses to the
    /// explicit `echo *` allow above it. It is not discarded; it is outranked.
    ///
    /// The alternative (unresolved-sensitive outranking an explicit allow)
    /// would introduce a new precedence level above a decision the operator
    /// wrote down deliberately. That is a separate semantic change and needs
    /// its own tests and a migration note, so it is not made here.
    #[test]
    fn an_explicit_allow_outranks_an_unresolved_sensitive_target() {
        let p = Policy::builtin().unwrap();
        assert_eq!(
            p.evaluate_command("echo x > $CONFIG", &here()).action,
            Action::Allow,
            "an explicit allow is an explicit allow"
        );
        // The deny reading exists and is real — the resolver reports the shape
        // — it simply loses the tournament. Asserting this separately is what
        // makes the test about PRECEDENCE rather than about the resolver
        // having failed to notice.
        let t = crate::resolve::target("$CONFIG", crate::resolve::TargetRole::Destination, &here());
        assert!(t.is_unresolved());
        assert!(t.has(crate::resolve::SensitiveShape::UnexpandedVar));

        // And where no explicit allow covers it, the deny reading DOES govern.
        // A REDIRECT to an unresolved target is seen, because redirects are
        // one of the two target sources this commit reads.
        let d = p.evaluate_command("truncate -s 0 x > $CONFIG", &here());
        assert_eq!(
            d.action,
            Action::Deny,
            "unresolved and sensitive, nothing explicit above it: {}",
            d.reason
        );
        assert!(
            d.reason.contains("cannot be resolved"),
            "the reason must say the gate does not know: {}",
            d.reason
        );

        // SCOPE, pinned so it is not mistaken for coverage: targets come from
        // redirects and from the delete extractor. Nothing else has an
        // extractor yet, so `truncate -s 0 $CONFIG` - which destroys a file
        // named by an unresolvable variable - produces NO targets and reaches
        // its ordinary verdict. cp/mv/tee/dd destinations are roadmap 2.1;
        // truncate is covered by nothing. The machinery is only as wide as
        // the extractors feeding it.
        assert!(
            resolved_targets("truncate -s 0 $CONFIG", &here()).is_empty(),
            "if this starts finding targets, an extractor was added and this \
             test should be narrowed rather than deleted"
        );
    }

    /// THE MATCHER INVARIANT: at least one matcher, neither individually
    /// mandatory. Enforced at parse time, because a rule with no matcher can
    /// never fire - it is a policy that says nothing while looking like it
    /// says something, which is worse than a parse error.
    #[test]
    fn a_rule_needs_at_least_one_matcher() {
        let ok = [
            "rules:\n  - match: \"git rm *\"\n    action: deny\n",
            "rules:\n  - match_path: \"*/.ssh/*\"\n    action: deny\n",
            "rules:\n  - match: \"git *\"\n    match_path: \"*/.ssh/*\"\n    action: deny\n",
        ];
        for y in ok {
            let p: Policy = serde_yaml::from_str(y).expect("parses");
            assert!(p.validate().is_ok(), "should be valid:\n{y}");
        }

        let neither = "rules:\n  - action: deny\n    reason: \"says nothing\"\n";
        let p: Policy = serde_yaml::from_str(neither).expect("parses as YAML");
        let err = p.validate().expect_err("a rule with no matcher is invalid");
        assert!(
            err.to_string().contains("neither"),
            "the error must say what is missing: {err}"
        );
    }

    /// The shipped policy obeys its own invariant, and `builtin()` enforces
    /// it rather than trusting the file - the starter policy is the one most
    /// likely to grow a rule by hand.
    #[test]
    fn the_starter_policy_obeys_the_matcher_invariant() {
        let p = Policy::builtin().expect("builtin parses and validates");
        for (i, r) in p.rules.iter().enumerate() {
            assert!(
                r.r#match.is_some() || r.match_path.is_some(),
                "rule {i} has no matcher"
            );
        }
        // And at least one rule now uses match_path WITHOUT a string pattern,
        // which is the shape the schema change exists to allow.
        assert!(
            p.rules
                .iter()
                .any(|r| r.r#match.is_none() && r.match_path.is_some()),
            "the starter policy should exercise the path-only shape it ships"
        );
    }

    /// The reason line names the ROLE, because the verdict and the
    /// explanation were diverging: `mv .env dst` denied with "Overwriting
    /// .env destroys credentials", and `mv` does not overwrite `.env` - it
    /// REMOVES it. The rule's reason text is written for one case; the role
    /// says which case this actually is. A human approving a prompt should
    /// not have to know those can differ.
    #[test]
    fn the_reason_names_what_the_command_does_to_the_target() {
        let p = Policy::builtin().unwrap();

        let moved = p.evaluate_command("mv .env /tmp/archive/", &here());
        assert_eq!(moved.action, Action::Deny);
        assert!(
            moved.reason.contains("(removed)"),
            "a move removes its source, and the sentence should say so: {}",
            moved.reason
        );

        let written = p.evaluate_command("cp backup.txt .env", &here());
        assert_eq!(written.action, Action::Deny);
        assert!(
            written.reason.contains("(written)"),
            "a copy writes its destination: {}",
            written.reason
        );

        // Both still name the target itself - the role is an addition, not a
        // replacement.
        assert!(moved.reason.contains(".env") && written.reason.contains(".env"));
    }

    /// Roadmap 2.1: a path rule fires on roles that CHANGE a file, not on
    /// every path a command mentions.
    ///
    /// Extracting `cp`/`mv`/`tee`/`dd` targets reopened the source-side false
    /// positive from a new direction: `cp .env backup.txt` names `.env`, but
    /// only reads it. Measured before the guard, all four of these denied.
    ///
    /// `mv` is the case the roles exist for. Its source is REMOVED, not read,
    /// so `mv .env /tmp/archive/` must still deny - a move is a delete of
    /// where the file used to be, and reporting only the destination would
    /// miss the destruction entirely.
    #[test]
    fn a_path_rule_fires_on_what_changes_a_file_not_on_what_reads_it() {
        let p = Policy::builtin().unwrap();

        // Destructive roles: the file is written over, or leaves its place.
        for cmd in [
            "cp backup.txt .env",
            "tee .env",
            "dd if=/dev/zero of=.env",
            "mv .env /tmp/archive/",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "{cmd}: this changes the protected file"
            );
        }

        // Read-only roles: the file is exactly as it was afterwards.
        for cmd in ["cp .env backup.txt", "dd if=.env of=copy.txt"] {
            assert_ne!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "{cmd}: reading the protected file changes nothing"
            );
        }
    }

    /// The root rule names the root, and nothing else.
    ///
    /// `match: "rm -rf /*"` is a WILDCARD: it matched every absolute path, so
    /// `rm -rf /home/me/project/.git` was denied with "Recursive delete from
    /// root is blocked". Right verdict, wrong sentence — and a proving run
    /// caught it when a real agent was correctly stopped from deleting a
    /// `.git` directory and told the reason was the filesystem root.
    ///
    /// Both still deny. The difference is what the human is told, which is
    /// the whole product on the occasions it matters.
    #[test]
    fn the_root_rule_explains_itself_only_for_the_root() {
        let p = Policy::builtin().unwrap();

        for cmd in ["rm -rf /", "rm -rf / --no-preserve-root"] {
            let d = p.evaluate_command(cmd, &here());
            assert_eq!(d.action, Action::Deny);
            assert!(
                d.reason.contains("filesystem root"),
                "{cmd}: names the root: {}",
                d.reason
            );
        }

        // An absolute path that is NOT the root still denies, and says why
        // truthfully.
        for cmd in [
            "rm -rf /home/me/project/.git",
            "rm -rf /tmp/build",
            "rm -rf .git",
        ] {
            let d = p.evaluate_command(cmd, &here());
            assert_eq!(d.action, Action::Deny, "{cmd} must still deny");
            assert!(
                !d.reason.contains("filesystem root"),
                "{cmd} is not the root: {}",
                d.reason
            );
        }
    }

    /// REGRESSION, v0.16: the shipped `.env` rule denied ordinary READS.
    ///
    /// The rule carried `match: "*.env*"` purely because the schema demanded
    /// a string pattern, and that pattern fired on its own - a whole-string
    /// substring match on `.env` anywhere in the command. `cat .env`,
    /// `grep KEY .env`, `git diff .env`, `ls -la .env`, `cat
    /// prod.env.example` were all DENIED. Reading a file destroys nothing,
    /// and a gate that denies ordinary work gets uninstalled (#48).
    ///
    /// Both sides are pinned deliberately: a path rule that stops denying
    /// writes is a hole, and one that starts denying reads is the bug this
    /// test exists for.
    #[test]
    fn the_env_rule_denies_writes_and_leaves_reads_alone() {
        let p = Policy::builtin().unwrap();

        // Writes to the protected file, every spelling of one path.
        for cmd in [
            "cat /dev/null > .env",
            "cat /dev/null > ./.env",
            "cat /dev/null > ./sub/../.env",
        ] {
            assert_eq!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "{cmd}: one file, every spelling"
            );
        }

        // Reads are ordinary work and stay out of the way.
        for cmd in [
            "cat .env",
            "grep KEY .env",
            "git diff .env",
            "ls -la .env",
            "cat prod.env.example",
        ] {
            assert_ne!(
                p.evaluate_command(cmd, &here()).action,
                Action::Deny,
                "{cmd}: reading a file destroys nothing"
            );
        }

        // The source-side spelling must not trip the path rule: the resolved
        // TARGET here is config/prod.env, which is not `.env`. Before the
        // fix, the `*.env*` string pattern matched this on the source alone.
        let d = p.evaluate_command("cp new.env config/prod.env", &here());
        assert_ne!(
            d.action,
            Action::Deny,
            "a .env source is not a .env target: {}",
            d.reason
        );
    }

    /// Path patterns are matched COMPONENT BY COMPONENT, not as string globs
    /// over the printed path. The first draft used `wildcard_match` on the
    /// whole string and was wrong three ways: `*/.env` missed a bare `.env`
    /// (no separator), missed `C:\proj\.env` (backslash is not `/`), and
    /// loosening it to `*.env` would have caught `prod.env` as collateral.
    #[test]
    fn a_path_pattern_matches_components_not_strings() {
        let r = Rule {
            r#match: None,
            action: Action::Deny,
            reason: None,
            case_sensitive: false,
            match_path: Some("*/.env".into()),
        };
        for hit in [
            "/tmp/proj/.env",
            "C:\\proj\\.env",
            ".env",
            "./.env",
            "/a/b/c/.env",
        ] {
            assert!(r.matches_path(hit), "{hit} names the protected file");
        }
        // Control legs - a component pattern does not match a substring of a
        // component, which is the whole difference from a string glob.
        for miss in [
            "/tmp/proj/prod.env",
            "/tmp/proj/.env.sample",
            "/tmp/proj/.envrc",
            "/tmp/.env/keep.txt",
        ] {
            assert!(!r.matches_path(miss), "{miss} is a different file");
        }
    }

    /// A `*` component means "at any depth", so one rule covers a file
    /// wherever it sits, and a `*` inside a component stays inside it.
    #[test]
    fn a_star_component_spans_depth_and_a_star_inside_one_does_not() {
        let deep = Rule {
            r#match: None,
            action: Action::Deny,
            reason: None,
            case_sensitive: false,
            match_path: Some("*/.ssh/id_*".into()),
        };
        assert!(deep.matches_path("/home/u/.ssh/id_rsa"));
        assert!(deep.matches_path("/home/u/.ssh/id_ed25519"));
        assert!(!deep.matches_path("/home/u/.ssh/known_hosts"));
        // `id_*` must not reach across a separator into the next component.
        assert!(!deep.matches_path("/home/u/.ssh/id_dir/inner"));
    }

    /// GAP CLOSED, v0.16 — the INVERSION of the pinned known-gap test, not a
    /// replacement, so the history stays visible in the place that proves it
    /// is over. It read: "`cat /dev/null > ./.env` walks past the `*> .env*`
    /// string rules (belt), but the redirect scanner still extracts the
    /// target (suspenders)... the full fix is matching on the RESOLVED target
    /// (v0.16)". That fix is this: the starter policy now carries a
    /// `match_path: "*/.env"` rule, so both spellings of one file deny.
    ///
    /// The suspenders are asserted too, unchanged. Insurance did not become
    /// unnecessary when the string gap closed — it is what covered the four
    /// releases in which the gap was open, and a later policy edit could
    /// remove the rule without removing the net.
    #[test]
    fn the_dot_slash_spelling_was_a_known_gap_and_is_now_closed() {
        let p = Policy::builtin().unwrap();
        for spelling in [
            "cat /dev/null > ./.env",
            "cat /dev/null > .env",
            "cat /dev/null > ./sub/../.env",
        ] {
            assert_eq!(
                p.evaluate_command(spelling, &here()).action,
                Action::Deny,
                "{spelling}: one file, every spelling"
            );
        }
        let segs = crate::shell::split_segments("cat /dev/null > ./.env");
        let r = &segs[0].redirects;
        assert!(
            r.len() == 1 && r[0].truncates && r[0].target == "./.env",
            "the net beneath: insurance sees the spelling the string rules miss"
        );
        // And the write-tool path (Schipper, #20) guards the same files the
        // shell path guards, independent of both.
        assert!(crate::protect::classify(".", ".termaxa/policy.yaml").is_some());
        assert!(crate::protect::classify(".", "src/main.rs").is_none());
    }
}