workpen 0.7.7

Workpen dest-deny and a per-child process jail (Landlock, Seatbelt, Windows).
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
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
//! Dest-deny predicate. Glob match, hardlink sibling, patch dests, argv tokens.

use std::ffi::OsStr;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::agent_lock::{AgentLockError, load_agent_lock};
use crate::guard::{PathGuard, PathGuardError};

/// Portable dest-deny policy. Same globs on every OS.
/// Hosts hold this value. There is no process-wide default slot. Clone is cheap.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DenyPolicy {
    globs: Arc<Vec<String>>,
}

impl Default for DenyPolicy {
    fn default() -> Self {
        Self {
            globs: Arc::new(default_secret_denies()),
        }
    }
}

impl DenyPolicy {
    pub fn new(globs: Vec<String>) -> Self {
        Self {
            globs: Arc::new(globs),
        }
    }

    /// Intern a host-held glob list. Does not copy the strings.
    /// There is still no process-wide deny slot.
    pub fn from_arc(globs: Arc<Vec<String>>) -> Self {
        Self { globs }
    }

    /// Same allocation as [`DenyPolicy::from_arc`] / clone.
    pub fn globs_arc(&self) -> Arc<Vec<String>> {
        Arc::clone(&self.globs)
    }

    /// `default_secret_denies()` plus extras. Extras never replace defaults.
    pub fn with_extra(extra: impl IntoIterator<Item = String>) -> Self {
        let mut globs = default_secret_denies();
        for g in extra {
            if !globs.iter().any(|x| x == &g) {
                globs.push(g);
            }
        }
        Self {
            globs: Arc::new(globs),
        }
    }

    /// Defaults plus workspace `agent.lock` extras. Missing lock equals default.
    /// Extras never replace defaults. Invalid lock is [`AgentLockError`].
    pub fn from_workspace(path: impl AsRef<Path>) -> Result<Self, AgentLockError> {
        Ok(Self::with_extra(load_agent_lock(path.as_ref())?))
    }

    pub fn globs(&self) -> &[String] {
        &self.globs
    }
}

/// Why dest-deny rejected a path. Hosts branch on this; do not parse messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DestDenyKind {
    /// Basename or full path matched a deny glob (raw or canonical).
    DenyGlob,
    /// Another directory entry shares this inode / NTFS file index and is denied.
    HardlinkSibling,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DestDeny {
    pub kind: DestDenyKind,
    pub path: PathBuf,
    pub display: String,
    /// Matching deny glob, or the other hardlink's basename.
    pub matched: Option<String>,
}

impl DestDeny {
    /// Wording distinguishes glob vs hardlink.
    /// Hardlink must not say "matches deny glob".
    pub fn message(&self) -> String {
        match (&self.kind, self.matched.as_deref()) {
            (DestDenyKind::DenyGlob, Some(glob)) => format!(
                "path denied by sandbox profile (matches deny glob {glob}): {}",
                self.display
            ),
            (DestDenyKind::DenyGlob, None) => format!(
                "path denied by sandbox profile (matches deny glob): {}",
                self.display
            ),
            (DestDenyKind::HardlinkSibling, Some(sib)) => format!(
                "path denied by sandbox profile (hardlink of a denied name {sib}): {}",
                self.display
            ),
            (DestDenyKind::HardlinkSibling, None) => format!(
                "path denied by sandbox profile (hardlink of a denied name): {}",
                self.display
            ),
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum DestDenyError {
    #[error("{0}")]
    Denied(DestDeny),
    /// Argv token hit. Distinct wording from [`DestDeny::message`].
    #[error("command references path denied by sandbox profile: {token}")]
    CommandToken { token: String },
    /// PowerShell `-EncodedCommand` payload is not UTF-16LE RFC 4648.
    #[error("invalid -EncodedCommand payload (need UTF-16LE base64); child was not started")]
    EncodedCommand,
    /// PowerShell `-Command -` / `-File -` (and unique prefixes), or positional `-`, read a script from stdin.
    #[error(
        "PowerShell stdin script (-Command - or -File -) cannot be dest-denied; child was not started"
    )]
    StdinScript,
    /// Post-open hardlink hit. Distinct wording from [`DestDeny::message`].
    #[error(
        "path denied: {path} is a hardlink of a denied name; unlink extra names or do not share the inode"
    )]
    LateHardlink { path: String },
    /// Path identity changed between check and open.
    #[error("TOCTOU race detected: {path} changed between check and open")]
    Toctou { path: String },
    #[error("TOCTOU check failed: {0}")]
    ToctouStat(String),
}

/// Host composition error. Dest-deny vs PathGuard; do not parse messages.
#[derive(Debug, thiserror::Error)]
pub enum CheckDestError {
    #[error(transparent)]
    DestDeny(#[from] DestDenyError),
    #[error(transparent)]
    PathGuard(#[from] PathGuardError),
    #[error("path contains a NUL byte")]
    Nul,
    #[error("refuse special file ({kind}): {path}")]
    SpecialFile { path: String, kind: &'static str },
    /// Read helper only. [`check_dest`] still allows directories.
    #[error("refuse directory read: {path}")]
    Directory { path: String },
    #[error("open failed: {0}")]
    Io(String),
    #[error("command argument is not valid UTF-8")]
    NonUtf8,
}

impl std::fmt::Display for DestDeny {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message())
    }
}

/// Classify one dest. Glob vs hardlink only. Does not jail `..`.
pub fn classify_dest(path: &Path, policy: &DenyPolicy) -> Option<DestDenyKind> {
    classify_dest_hit(path, policy).map(|hit| hit.kind)
}

struct DestDenyHit {
    kind: DestDenyKind,
    matched: Option<String>,
}

fn classify_dest_hit(path: &Path, policy: &DenyPolicy) -> Option<DestDenyHit> {
    classify_dest_hit_root(path, policy, None)
}

/// A directory named `.env` is denied as that directory. Seatbelt then
/// applies the deny to everything inside it. Match those children here
/// so `why` does not call them allowed. Stop at the workspace root so a
/// parent directory outside the workspace cannot deny the whole tree.
fn ancestor_deny_glob(path: &Path, policy: &DenyPolicy, root: Option<&Path>) -> Option<String> {
    let mut cursor = path.parent();
    while let Some(dir) = cursor {
        if dir.as_os_str().is_empty() {
            break;
        }
        if dir.is_absolute()
            && let Some(root) = root
            && !ancestor_inside_workspace(dir, root)
        {
            break;
        }
        if let Some(glob) = first_matching_deny_glob_under(policy.globs(), &path_as_glob(dir), root)
        {
            return Some(glob);
        }
        let next = dir.parent();
        if next == Some(dir) {
            break;
        }
        cursor = next;
    }
    None
}

fn ancestor_inside_workspace(dir: &Path, root: &Path) -> bool {
    let dir_s = path_as_glob(dir);
    for spelling in firmlink_spellings(root) {
        let root_s = path_as_glob(&spelling).trim_end_matches('/').to_string();
        if root_s.is_empty() {
            continue;
        }
        let prefix = format!("{root_s}/");
        if dir_s.len() > prefix.len() && dir_s[..prefix.len()].eq_ignore_ascii_case(&prefix) {
            return true;
        }
    }
    false
}

fn classify_dest_hit_root(
    path: &Path,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> Option<DestDenyHit> {
    if let Some(glob) = first_matching_deny_glob_under(policy.globs(), &path_as_glob(path), root) {
        return Some(DestDenyHit {
            kind: DestDenyKind::DenyGlob,
            matched: Some(glob),
        });
    }

    let canon = std::fs::canonicalize(path).ok();
    if let Some(canon) = &canon
        && let Some(glob) =
            first_matching_deny_glob_under(policy.globs(), &path_as_glob(canon), root)
    {
        return Some(DestDenyHit {
            kind: DestDenyKind::DenyGlob,
            matched: Some(glob),
        });
    }
    if let Some(glob) = ancestor_deny_glob(path, policy, root) {
        return Some(DestDenyHit {
            kind: DestDenyKind::DenyGlob,
            matched: Some(glob),
        });
    }
    if let Some(canon) = &canon
        && let Some(glob) = ancestor_deny_glob(canon, policy, root)
    {
        return Some(DestDenyHit {
            kind: DestDenyKind::DenyGlob,
            matched: Some(glob),
        });
    }
    match hardlink_sibling_hit(path, canon.as_deref(), policy, root) {
        HardlinkHit::Denied { sibling } => Some(DestDenyHit {
            kind: DestDenyKind::HardlinkSibling,
            matched: sibling,
        }),
        HardlinkHit::Allowed => None,
    }
}

pub(crate) fn dest_deny_at(
    classified: &Path,
    display: String,
    policy: &DenyPolicy,
) -> Option<DestDeny> {
    dest_deny_at_root(classified, display, policy, None)
}

pub(crate) fn dest_deny_at_root(
    classified: &Path,
    display: String,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> Option<DestDeny> {
    classify_dest_hit_root(classified, policy, root).map(|hit| DestDeny {
        kind: hit.kind,
        path: classified.to_path_buf(),
        display,
        matched: hit.matched,
    })
}

/// Glob-name dest-deny only. No canonicalize and no hardlink sibling
/// scan. Cache trees use this so rustc artifacts are not O(n^2)
/// readdir'd. Plants `**/.env` names, not every `target/debug/deps`
/// inode.
pub(crate) fn dest_deny_glob_only(
    classified: &Path,
    display: String,
    policy: &DenyPolicy,
) -> Option<DestDeny> {
    first_matching_deny_glob(policy.globs(), &path_as_glob(classified)).map(|glob| DestDeny {
        kind: DestDenyKind::DenyGlob,
        path: classified.to_path_buf(),
        display,
        matched: Some(glob),
    })
}

pub fn is_path_denied(path: &Path, policy: &DenyPolicy) -> bool {
    classify_dest(path, policy).is_some()
}

pub fn dest_deny_message(path: &Path, display: &str, policy: &DenyPolicy) -> Option<String> {
    dest_deny_at(path, display.to_owned(), policy).map(|d| d.message())
}

/// Dest-deny raw; if `guard` is `Some`, PathGuard; dest-deny resolved.
///
/// `guard: None` dest-denies raw and, if the path exists, dest-denies the
/// cwd-joined canonicalize. Does not treat cwd as a workspace root.
/// Rejects NUL and existing fifo / socket / device. Does not peel.
/// Does not refuse directories (write dests). See [`open_verified_read`].
pub fn check_dest(
    path: &str,
    policy: &DenyPolicy,
    guard: Option<&PathGuard>,
) -> Result<PathBuf, CheckDestError> {
    check_dest_rooted(path, policy, guard, None)
}

fn check_dest_rooted(
    path: &str,
    policy: &DenyPolicy,
    guard: Option<&PathGuard>,
    workspace: Option<&Path>,
) -> Result<PathBuf, CheckDestError> {
    if path.contains('\0') {
        return Err(CheckDestError::Nul);
    }
    let raw = Path::new(path);
    let glob_root = workspace.or_else(|| guard.map(|g| g.canon_root()));
    if let Some(deny) = dest_deny_at_root(raw, path.to_owned(), policy, glob_root) {
        return Err(CheckDestError::DestDeny(DestDenyError::Denied(deny)));
    }

    // Argv checks this path with no PathGuard, so `run` allows
    // `/dev/null` and refuses other devices. Apply that before a
    // workspace guard can report Escape instead.
    #[cfg(unix)]
    if is_null_device(raw) {
        return Ok(raw.to_path_buf());
    }

    let resolved = match guard {
        Some(g) => match g.check(raw) {
            Ok(checked) => checked,
            Err(err) => {
                #[cfg(unix)]
                reject_special_file(raw)?;
                return Err(err.into());
            }
        },
        None => {
            let joined = if raw.is_absolute() {
                raw.to_path_buf()
            } else {
                match std::env::current_dir() {
                    Ok(cwd) => cwd.join(raw),
                    Err(_) => raw.to_path_buf(),
                }
            };
            if joined.exists() {
                std::fs::canonicalize(&joined).unwrap_or(joined)
            } else {
                joined
            }
        }
    };

    if let Some(deny) = dest_deny_at_root(&resolved, path.to_owned(), policy, glob_root) {
        return Err(CheckDestError::DestDeny(DestDenyError::Denied(deny)));
    }
    reject_special_file(&resolved)?;
    Ok(resolved)
}

/// `check_dest`, refuse directories, open for read, then [`verify_post_open`].
pub fn open_verified_read(
    path: &str,
    policy: &DenyPolicy,
    guard: Option<&PathGuard>,
) -> Result<File, CheckDestError> {
    let resolved = check_dest(path, policy, guard)?;
    refuse_directory(&resolved)?;
    let file = File::open(&resolved).map_err(|e| CheckDestError::Io(e.to_string()))?;
    if file.metadata().map(|m| m.is_dir()).unwrap_or(false) {
        return Err(directory_read_error(&resolved));
    }
    verify_post_open(&resolved, &file, policy)?;
    Ok(file)
}

fn refuse_directory(path: &Path) -> Result<(), CheckDestError> {
    let Ok(meta) = std::fs::metadata(path) else {
        return Ok(());
    };
    if meta.is_dir() {
        return Err(directory_read_error(path));
    }
    Ok(())
}

fn directory_read_error(path: &Path) -> CheckDestError {
    CheckDestError::Directory {
        path: path.display().to_string(),
    }
}

/// The process null device, and only when it is still a character device.
/// A symlink to a regular file is not this device.
#[cfg(unix)]
pub(crate) fn is_null_device(path: &Path) -> bool {
    use std::os::unix::fs::FileTypeExt;
    use std::os::unix::fs::MetadataExt;
    let Ok(meta) = std::fs::metadata(path) else {
        return false;
    };
    if !meta.file_type().is_char_device() {
        return false;
    }
    let Ok(null_meta) = std::fs::metadata("/dev/null") else {
        return false;
    };
    null_meta.file_type().is_char_device() && meta.rdev() == null_meta.rdev()
}

fn reject_special_file(path: &Path) -> Result<(), CheckDestError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::FileTypeExt;
        let Ok(meta) = std::fs::metadata(path) else {
            return Ok(());
        };
        let ft = meta.file_type();
        let kind = if ft.is_fifo() {
            Some("fifo")
        } else if ft.is_socket() {
            Some("socket")
        } else if ft.is_char_device() || ft.is_block_device() {
            Some("device")
        } else {
            None
        };
        if let Some(kind) = kind {
            if kind == "device" && is_null_device(path) {
                return Ok(());
            }
            return Err(CheckDestError::SpecialFile {
                path: path.display().to_string(),
                kind,
            });
        }
    }
    let _ = path;
    Ok(())
}

/// Unix inode/dev; Windows file index + volume serial.
/// Re-runs hardlink dest-deny when nlink / nNumberOfLinks > 1.
pub fn verify_post_open(path: &Path, fd: &File, policy: &DenyPolicy) -> Result<(), DestDenyError> {
    #[cfg(unix)]
    {
        verify_post_open_unix(path, fd, policy)
    }
    #[cfg(windows)]
    {
        verify_post_open_windows(path, fd, policy)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (path, fd, policy);
        Ok(())
    }
}

#[cfg(unix)]
fn verify_post_open_unix(path: &Path, fd: &File, policy: &DenyPolicy) -> Result<(), DestDenyError> {
    use std::os::unix::fs::MetadataExt;

    let path_meta = std::fs::symlink_metadata(path)
        .map_err(|e| DestDenyError::ToctouStat(format!("cannot stat {}: {e}", path.display())))?;
    let fd_meta = fd
        .metadata()
        .map_err(|e| DestDenyError::ToctouStat(format!("cannot fstat fd: {e}")))?;
    if path_meta.ino() != fd_meta.ino() || path_meta.dev() != fd_meta.dev() {
        return Err(DestDenyError::Toctou {
            path: path.display().to_string(),
        });
    }
    if fd_meta.nlink() > 1 {
        let canon = std::fs::canonicalize(path).ok();
        if hardlink_sibling_denied(path, canon.as_deref(), policy) {
            return Err(DestDenyError::LateHardlink {
                path: path.display().to_string(),
            });
        }
    }
    Ok(())
}

#[cfg(windows)]
fn verify_post_open_windows(
    path: &Path,
    fd: &File,
    policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
    use std::os::windows::io::AsRawHandle;

    let path_info = win_path_by_handle(path)
        .map_err(|e| DestDenyError::ToctouStat(format!("cannot stat {}: {e}", path.display())))?;
    let fd_info = win_handle_info(fd.as_raw_handle())
        .map_err(|e| DestDenyError::ToctouStat(format!("cannot fstat fd: {e}")))?;
    if path_info.index != fd_info.index || path_info.volume != fd_info.volume {
        return Err(DestDenyError::Toctou {
            path: path.display().to_string(),
        });
    }
    if fd_info.nlink > 1 {
        let canon = std::fs::canonicalize(path).ok();
        if hardlink_sibling_denied(path, canon.as_deref(), policy) {
            return Err(DestDenyError::LateHardlink {
                path: path.display().to_string(),
            });
        }
    }
    Ok(())
}

/// Refuse if any host-extracted dest is a secret glob or hardlink sibling.
///
/// Does not check out-of-tree. Hosts then run PathGuard on the same dests.
pub fn deny_patch_dests(
    dests: &[impl AsRef<Path>],
    policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
    for dest in dests {
        let dest = dest.as_ref();
        if let Some(deny) = dest_deny_at(dest, dest.display().to_string(), policy) {
            return Err(DestDenyError::Denied(deny));
        }
    }
    Ok(())
}

/// Like [`deny_patch_dests`], with a host-chosen display string per dest.
pub fn deny_patch_dests_with_display(
    dests: &[(&Path, &str)],
    policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
    for (dest, display) in dests {
        if let Some(deny) = dest_deny_at(dest, (*display).to_owned(), policy) {
            return Err(DestDenyError::Denied(deny));
        }
    }
    Ok(())
}

/// Argv / command token scan. Does not parse a full shell.
pub fn reject_command_secret_path_tokens(
    command: &str,
    policy: &DenyPolicy,
) -> Result<(), DestDenyError> {
    for (display, candidate) in command_path_tokens(command) {
        if candidate_is_denied(&candidate, policy) {
            return Err(DestDenyError::CommandToken { token: display });
        }
    }
    Ok(())
}

/// Join a relative dest to `root`. Absolute dests stay as given.
pub fn dest_under_root(root: &Path, path: &str) -> PathBuf {
    let p = Path::new(path);
    if p.is_absolute() {
        p.to_path_buf()
    } else {
        root.join(p)
    }
}

/// Script body after a shell `-c` cluster (`-c`, `-lc`, `-ic`) or `-cBODY`.
///
/// Cluster letters are the usual bash short options that combine with
/// `-c`. A long word such as `-color` is not a cluster.
fn shell_c_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = token.strip_prefix('-')?;
    if rest.starts_with('-') {
        return None;
    }
    if is_shell_c_cluster(rest) {
        return next;
    }
    let c_at = rest.find('c')?;
    let prefix = rest.get(..=c_at)?;
    if !is_shell_c_cluster(prefix) {
        return None;
    }
    let after = rest.get(c_at + 1..)?;
    if after.is_empty() {
        return next;
    }
    Some(after)
}

fn is_shell_c_cluster(rest: &str) -> bool {
    let len = rest.len();
    // `-cwa` is pwsh -CommandWithArgs, not a bash short-option cluster.
    if rest.eq_ignore_ascii_case("cwa") {
        return false;
    }
    (1..=4).contains(&len) && rest.contains('c') && rest.chars().all(|ch| ch.is_ascii_alphabetic())
}

/// Dest-deny each raw argv dest under `root`.
///
/// Empty and flag-looking tokens are skipped. A shell `-c` token, including
/// short-option clusters that contain `c` (`-lc`, `-ic`, `-lic`, `-cl`)
/// and an attached `-cBODY`, dest-denies paths inside the script body
/// via [`check_command_dests`]. When that body (or any peeled command
/// string) contains an `env`/`env.exe` token, dest-denies the following
/// tokens with the same env-flag dest check used for argv0 env.
/// When argv0 is `env`/`env.exe`, dest-denies the operand of
/// `-S`/`--split-string` via [`check_command_dests`], then leftover
/// tokens in that string as env flags (`--file=`, `-f`, `NAME=value`).
/// An `env`/`env.exe` token in any argv slot is walked the same way, so
/// a prefix that is not `timeout`/`nohup`/`nice`/`time`/`stdbuf` cannot
/// hide `-S`/`--file`. A nested `env` operand (or `env -- env …`) is
/// walked the same way.
/// `cmd /c` and `powershell -Command` / `-EncodedCommand` bodies are
/// dest-denied as command strings. After `cmd` / `pwsh`, remaining
/// argv is walked so `/s` / `-NoProfile` cannot hide `/c`,
/// `-EncodedCommand`, `-EncodedArguments`, or `-File`. Unique prefixes
/// (`-en`, `-comma`, `-cwa`) match. A second leading `-`/`/` is stripped
/// (`--Command`, `--EncodedCommand`, `--File`). `-File` / `-f` / `/File`
/// (and `-File:…`) dest-deny the script path. `pwsh -Command -`,
/// `pwsh -File -` (including `--switch` and unique prefixes), and
/// positional `pwsh -` / `powershell -` are
/// [`DestDenyError::StdinScript`]: dest-deny does not read host stdin.
/// `cmd /c -` is unchanged. Those bodies are also peeled
/// inside a shell `-c` string. Generic `/c`, `-Command`, `-EncodedCommand`,
/// `-cwa`, or `-File` on another argv0 is not.
/// Dest-denies argv `-f`/`--file` (including attached `--file=.env`) via
/// [`check_dest`]. Also dest-denies the suffix after `=` on any `--*` /
/// `-*=` token (`tool --config=.env`). A GNU glued short dest (`-a.env`,
/// `-D.env`, `-C.env`, clustered `-la.env`) dest-denies the remainder
/// after an ASCII-letter cluster when that remainder starts with `.`
/// `/` or `~`. `-areadme.md` and `-color` stay allowed. `--color=always`
/// and `--jobs=4` stay allowed when the suffix is not a dest-deny name.
/// A non-flag `NAME=value` dest-denies the value. Does not dest-deny a
/// flattened join of all argv. Does not dest-deny a following separate
/// token unless that token is already a raw dest.
pub fn check_command_argv(
    cmd: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    for (i, token) in cmd.iter().enumerate() {
        let token = token.as_ref();
        if !token.is_empty() && !token.starts_with('-') {
            let dest = dest_under_root(root, token);
            check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
            if let Some(value) = assignment_dest_value(token) {
                let dest = dest_under_root(root, value);
                check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
            }
        }
        if let Some(value) = attached_flag_dest(token) {
            let dest = dest_under_root(root, value);
            check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
        }
        if let Some(body) = shell_c_body(token, cmd.get(i + 1).map(|s| s.as_ref())) {
            check_command_dests(body, root, policy)?;
        }
        if is_cmd_program(token) || is_powershell_program(token) {
            check_cmd_powershell_remaining_dests(token, &cmd[i + 1..], root, policy)?;
        }
        if is_env_program(token) {
            check_env_flag_dests(&cmd[i + 1..], root, policy)?;
        }
    }
    Ok(())
}

pub(crate) fn is_env_program(program: impl AsRef<OsStr>) -> bool {
    let raw = program.as_ref().to_string_lossy();
    let name = program_basename(&raw);
    name.eq_ignore_ascii_case("env") || name.eq_ignore_ascii_case("env.exe")
}

fn program_basename(program: &str) -> &str {
    program.rsplit(['/', '\\']).next().unwrap_or(program)
}

fn is_cmd_program(program: &str) -> bool {
    let name = program_basename(program);
    name.eq_ignore_ascii_case("cmd") || name.eq_ignore_ascii_case("cmd.exe")
}

fn is_powershell_program(program: &str) -> bool {
    let name = program_basename(program);
    name.eq_ignore_ascii_case("powershell")
        || name.eq_ignore_ascii_case("powershell.exe")
        || name.eq_ignore_ascii_case("pwsh")
        || name.eq_ignore_ascii_case("pwsh.exe")
}

/// `cmd /c` / `/k` script body (`/c`, `/C`, `/kBODY`).
fn cmd_script_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = token.strip_prefix('/')?;
    let first = rest.chars().next()?;
    if !matches!(first, 'c' | 'C' | 'k' | 'K') {
        return None;
    }
    let after = rest.get(first.len_utf8()..)?;
    if after.is_empty() {
        return next;
    }
    Some(after)
}

/// Strip one or two leading `-`/`/` from a PowerShell host switch.
/// `--Command` and `/Command` both yield `Command`.
fn strip_ps_switch(token: &str) -> Option<&str> {
    let rest = token.strip_prefix(['-', '/'])?;
    Some(rest.strip_prefix(['-', '/']).unwrap_or(rest))
}

/// PowerShell `-Command` / `-c` / `/C` / `-cwa` / `-CommandWithArgs` script
/// body, including attached `-Command:…` and unique prefixes (`-comm`).
/// Not `-EncodedCommand` (see [`powershell_encoded_payload`]).
fn powershell_command_body<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = strip_ps_switch(token)?;
    if let Some((name, value)) = rest.split_once(':') {
        if is_powershell_command_name(name) {
            return Some(value);
        }
        return None;
    }
    if is_powershell_command_name(rest) {
        return next;
    }
    None
}

/// PowerShell `-EncodedCommand` / `-enc` / `-ec` / `-en` / `-e` payload, including
/// attached `-EncodedCommand:…` and unique prefixes (`-en`). Not `-Command`.
fn powershell_encoded_payload<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = strip_ps_switch(token)?;
    if let Some((name, value)) = rest.split_once(':') {
        if is_powershell_encoded_command_name(name) {
            return Some(value);
        }
        return None;
    }
    if is_powershell_encoded_command_name(rest) {
        return next;
    }
    None
}

/// PowerShell `-EncodedArguments` / `-ea` payload, including attached
/// `-EncodedArguments:…`. Unique prefixes of `encodedarguments` that are
/// not prefixes of `encodedcommand` (`-encodeda`). Host `-ea` is this
/// switch, not `-ErrorAction`.
fn powershell_encoded_arguments_payload<'a>(
    token: &'a str,
    next: Option<&'a str>,
) -> Option<&'a str> {
    let rest = strip_ps_switch(token)?;
    if let Some((name, value)) = rest.split_once(':') {
        if is_powershell_encoded_arguments_name(name) {
            return Some(value);
        }
        return None;
    }
    if is_powershell_encoded_arguments_name(rest) {
        return next;
    }
    None
}

fn is_powershell_encoded_command_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "encodedcommand"
        || lower == "enc"
        || lower == "ec"
        || lower == "e"
        || ("encodedcommand".starts_with(&lower)
            && !"erroraction".starts_with(&lower)
            && !"errorvariable".starts_with(&lower)
            && !"executionpolicy".starts_with(&lower))
}

/// PowerShell `-File` / `-f` / `/File` script dest, including attached
/// `-File:…` / `-f:…` and unique prefixes (`-fi`, `-fil`).
fn powershell_file_dest<'a>(token: &'a str, next: Option<&'a str>) -> Option<&'a str> {
    let rest = strip_ps_switch(token)?;
    if let Some((name, value)) = rest.split_once(':') {
        if is_powershell_file_name(name) {
            return Some(value);
        }
        return None;
    }
    if is_powershell_file_name(rest) {
        return next;
    }
    None
}

fn is_powershell_file_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "file" || lower == "f" || (lower.len() >= 2 && "file".starts_with(&lower))
}

fn is_powershell_command_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "command"
        || lower == "c"
        || (lower.len() >= 4 && "command".starts_with(&lower))
        || lower == "commandwithargs"
        || lower == "cwa"
        || (lower.len() >= 8 && "commandwithargs".starts_with(&lower))
}

fn is_powershell_encoded_arguments_name(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    lower == "encodedarguments"
        || lower == "ea"
        || ("encodedarguments".starts_with(&lower) && !"encodedcommand".starts_with(&lower))
}

/// After `cmd` / `pwsh`, walk remaining tokens. First `/c`/`/k`,
/// `-EncodedCommand`, `-EncodedArguments`, `-File`, or `-Command`
/// (including `--switch` and unique prefixes) wins. A leftover
/// operand that is exactly `-` is positional File-from-stdin.
fn check_cmd_powershell_remaining_dests(
    program: &str,
    rest: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    if is_cmd_program(program) {
        for (j, token) in rest.iter().enumerate() {
            if let Some(body) = cmd_script_body(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
            {
                return check_command_dests(body, root, policy);
            }
        }
    }
    if is_powershell_program(program) {
        for (j, token) in rest.iter().enumerate() {
            if let Some(payload) =
                powershell_encoded_payload(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
            {
                return check_powershell_encoded_dests(payload, root, policy);
            }
            if let Some(payload) = powershell_encoded_arguments_payload(
                token.as_ref(),
                rest.get(j + 1).map(|s| s.as_ref()),
            ) {
                return check_powershell_encoded_dests(payload, root, policy);
            }
            if let Some(path) =
                powershell_file_dest(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
            {
                refuse_powershell_stdin_dash(path)?;
                let dest = dest_under_root(root, path);
                return check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))
                    .map(|_| ());
            }
            if let Some(body) =
                powershell_command_body(token.as_ref(), rest.get(j + 1).map(|s| s.as_ref()))
            {
                refuse_powershell_stdin_dash(body)?;
                return check_command_dests(body, root, policy);
            }
        }
        // File is the default positional. `pwsh -` reads a script from stdin.
        for token in rest {
            if token.as_ref() == "-" {
                return Err(DestDenyError::StdinScript.into());
            }
        }
    }
    Ok(())
}

fn refuse_powershell_stdin_dash(body: &str) -> Result<(), CheckDestError> {
    if body == "-" {
        return Err(DestDenyError::StdinScript.into());
    }
    Ok(())
}

/// Decode `-EncodedCommand` UTF-16LE base64 and dest-deny the script.
/// Invalid payloads fail closed as [`DestDenyError::EncodedCommand`].
fn check_powershell_encoded_dests(
    payload: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    let script = decode_powershell_encoded_command(payload).ok_or(DestDenyError::EncodedCommand)?;
    check_command_dests(&script, root, policy)
}

/// RFC 4648 base64 of UTF-16LE. Fail-closed on empty, invalid alphabet,
/// leftover bits, odd length, or unpaired surrogates.
fn decode_powershell_encoded_command(payload: &str) -> Option<String> {
    let stripped: String = payload
        .chars()
        .filter(|c| !matches!(*c, ' ' | '\t' | '\r' | '\n'))
        .collect();
    if stripped.is_empty() {
        return None;
    }
    let bytes = decode_rfc4648_base64(stripped.as_bytes())?;
    if bytes.len() % 2 != 0 {
        return None;
    }
    let units: Vec<u16> = bytes
        .chunks_exact(2)
        .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
        .collect();
    String::from_utf16(&units).ok()
}

fn decode_rfc4648_base64(input: &[u8]) -> Option<Vec<u8>> {
    fn digit(b: u8) -> Option<u8> {
        match b {
            b'A'..=b'Z' => Some(b - b'A'),
            b'a'..=b'z' => Some(b - b'a' + 26),
            b'0'..=b'9' => Some(b - b'0' + 52),
            b'+' => Some(62),
            b'/' => Some(63),
            _ => None,
        }
    }

    let mut pad = 0usize;
    let mut end = input.len();
    while end > 0 && input[end - 1] == b'=' {
        pad += 1;
        end -= 1;
        if pad > 2 {
            return None;
        }
    }
    if input[..end].contains(&b'=') {
        return None;
    }
    if end % 4 == 1 {
        return None;
    }

    let mut out = Vec::with_capacity(end * 3 / 4);
    let mut acc: u32 = 0;
    let mut bits: u32 = 0;
    for &b in &input[..end] {
        let v = u32::from(digit(b)?);
        acc = (acc << 6) | v;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((acc >> bits) as u8);
            acc &= (1 << bits) - 1;
        }
    }
    if acc != 0 {
        return None;
    }
    Some(out)
}

/// Suffix after `=` on a flag token (`--config=.env`, `-f=.env`), or
/// a GNU glued short dest (`-a.env`, clustered `-la.env`). After one
/// or more ASCII letters of a short option with no `=`, a remainder
/// that starts with `.` `/` or `~` is the dest. Not `NAME=value` (no
/// leading `-`). Empty values are ignored. `--flag`, `-la`, and
/// `-areadme.md` are not dests.
fn attached_flag_dest(token: &str) -> Option<&str> {
    if !token.starts_with('-') || token == "-" || token == "--" {
        return None;
    }
    if let Some((_, value)) = token.split_once('=') {
        if value.is_empty() {
            return None;
        }
        return Some(value);
    }
    if token.starts_with("--") {
        return None;
    }
    let rest = token.get(1..)?;
    let mut letters = 0usize;
    for (i, ch) in rest.char_indices() {
        if ch.is_ascii_alphabetic() {
            letters += 1;
            continue;
        }
        if letters == 0 {
            return None;
        }
        let remainder = rest.get(i..)?;
        if remainder.starts_with(['.', '/', '~']) {
            return Some(remainder);
        }
        return None;
    }
    None
}

/// Value after the first `=` on a non-flag token.
///
/// Empty tokens and tokens that start with `-` are ignored
/// (`--file=.env` stays on [`attached_flag_dest`]). One matching
/// quote pair around the value is stripped. An empty value is ignored.
fn assignment_dest_value(token: &str) -> Option<&str> {
    if token.is_empty() || token.starts_with('-') {
        return None;
    }
    let (_, mut value) = token.split_once('=')?;
    let bytes = value.as_bytes();
    if bytes.len() >= 2 {
        let quote = bytes[0];
        if (quote == b'\'' || quote == b'"') && bytes[bytes.len() - 1] == quote {
            value = &value[1..bytes.len() - 1];
        }
    }
    if value.is_empty() { None } else { Some(value) }
}

#[cfg(feature = "nono")]
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum CmdWrapper {
    Timeout,
    Nohup,
    Nice,
    Time,
    Stdbuf,
}

#[cfg(feature = "nono")]
pub(crate) fn cmd_wrapper(program: impl AsRef<OsStr>) -> Option<CmdWrapper> {
    let raw = program.as_ref().to_string_lossy();
    let name = raw.rsplit(['/', '\\']).next().unwrap_or(raw.as_ref());
    if name.eq_ignore_ascii_case("timeout") || name.eq_ignore_ascii_case("timeout.exe") {
        Some(CmdWrapper::Timeout)
    } else if name.eq_ignore_ascii_case("nohup") || name.eq_ignore_ascii_case("nohup.exe") {
        Some(CmdWrapper::Nohup)
    } else if name.eq_ignore_ascii_case("nice") || name.eq_ignore_ascii_case("nice.exe") {
        Some(CmdWrapper::Nice)
    } else if name.eq_ignore_ascii_case("time") || name.eq_ignore_ascii_case("time.exe") {
        Some(CmdWrapper::Time)
    } else if name.eq_ignore_ascii_case("stdbuf") || name.eq_ignore_ascii_case("stdbuf.exe") {
        Some(CmdWrapper::Stdbuf)
    } else {
        None
    }
}

/// Skip wrapper flags plus the timeout duration. Returns the index of
/// the first remaining command operand.
#[cfg(feature = "nono")]
pub(crate) fn skip_wrapper_prefix(kind: CmdWrapper, args: &[impl AsRef<str>]) -> usize {
    let mut i = 0;
    let mut options_done = false;
    let mut skip_timeout_duration = kind == CmdWrapper::Timeout;
    while i < args.len() {
        let raw = args[i].as_ref();
        if !options_done {
            if raw == "--" {
                options_done = true;
                i += 1;
                continue;
            }
            if let Some(skip) = wrapper_flag_skip(kind, raw) {
                i = i.saturating_add(skip);
                continue;
            }
        }
        if skip_timeout_duration {
            skip_timeout_duration = false;
            i += 1;
            continue;
        }
        return i;
    }
    i
}

#[cfg(feature = "nono")]
fn wrapper_takes_value(kind: CmdWrapper, flag: char) -> bool {
    match kind {
        CmdWrapper::Timeout => matches!(flag, 's' | 'k'),
        CmdWrapper::Nice => flag == 'n',
        CmdWrapper::Nohup | CmdWrapper::Time => false,
        CmdWrapper::Stdbuf => matches!(flag, 'o' | 'e' | 'i'),
    }
}

#[cfg(feature = "nono")]
fn wrapper_long_takes_value(kind: CmdWrapper, long: &str) -> bool {
    match kind {
        CmdWrapper::Timeout => matches!(long, "signal" | "kill-after"),
        CmdWrapper::Nice => long == "adjustment",
        CmdWrapper::Nohup | CmdWrapper::Time => false,
        CmdWrapper::Stdbuf => matches!(long, "output" | "error" | "input"),
    }
}

#[cfg(feature = "nono")]
fn wrapper_flag_skip(kind: CmdWrapper, arg: &str) -> Option<usize> {
    if arg == "-" {
        return Some(1);
    }
    if !arg.starts_with('-') {
        return None;
    }
    if let Some(long) = arg.strip_prefix("--") {
        if long.contains('=') {
            return Some(1);
        }
        return Some(if wrapper_long_takes_value(kind, long) {
            2
        } else {
            1
        });
    }
    let mut chars = arg[1..].chars();
    while let Some(c) = chars.next() {
        if wrapper_takes_value(kind, c) {
            return Some(if chars.next().is_some() { 1 } else { 2 });
        }
    }
    Some(1)
}

pub(crate) fn env_takes_value(flag: char) -> bool {
    matches!(flag, 'u' | 'C' | 'S' | 'P' | 'a' | 'f')
}

pub(crate) fn env_flag_skip(arg: &str) -> Option<usize> {
    if arg == "-" {
        return Some(1);
    }
    if !arg.starts_with('-') {
        return None;
    }
    if let Some(long) = arg.strip_prefix("--") {
        if long.contains('=') {
            return Some(1);
        }
        return Some(match long {
            "unset" | "split-string" | "chdir" | "argv0" | "file" => 2,
            _ => 1,
        });
    }
    let mut chars = arg[1..].chars();
    while let Some(c) = chars.next() {
        if env_takes_value(c) {
            return Some(if chars.next().is_some() { 1 } else { 2 });
        }
    }
    Some(1)
}

fn check_env_flag_dests(
    args: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    check_env_flag_dests_inner(args, root, policy, false)
}

/// Dest-deny a `-S`/`--split-string` operand as a command string, then
/// re-walk leftover tokens as env flags (`--file=`, `-f`, `NAME=value`).
fn check_env_split_string_dests(
    operand: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    check_command_dests(operand, root, policy)?;
    let leftover: Vec<&str> = operand.split_whitespace().collect();
    check_env_flag_dests_inner(&leftover, root, policy, true)
}

fn check_env_flag_dests_inner(
    args: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
    deny_assign_values: bool,
) -> Result<(), CheckDestError> {
    let mut i = 0;
    while i < args.len() {
        let raw = args[i].as_ref();
        if raw == "--" || raw == "-" {
            return continue_env_after_operand(&args[i + 1..], root, policy);
        }
        if !raw.starts_with('-') {
            if raw.contains('=') {
                if deny_assign_values
                    && let Some((_, value)) = raw.split_once('=')
                    && !value.is_empty()
                {
                    check_env_file_dest(value, root, policy)?;
                }
                i += 1;
                continue;
            }
            return continue_env_after_operand(&args[i..], root, policy);
        }
        if let Some(long) = raw.strip_prefix("--") {
            if let Some((name, value)) = long.split_once('=') {
                check_env_named_operand(name, value, root, policy)?;
                i += 1;
                continue;
            }
            let next = args.get(i + 1).map(|s| s.as_ref());
            match long {
                "split-string" | "file" | "unset" | "chdir" | "argv0" => {
                    if let Some(next) = next {
                        check_env_named_operand(long, next, root, policy)?;
                    }
                    i += 2;
                }
                _ => i += 1,
            }
            continue;
        }
        let mut chars = raw[1..].chars();
        let mut value_flag = None;
        let mut attached = String::new();
        while let Some(c) = chars.next() {
            if env_takes_value(c) {
                value_flag = Some(c);
                attached = chars.collect();
                break;
            }
        }
        match value_flag {
            Some(flag) => {
                let operand = if attached.is_empty() {
                    args.get(i + 1).map(|s| s.as_ref())
                } else {
                    Some(attached.as_str())
                };
                if let Some(operand) = operand {
                    match flag {
                        'S' => check_env_split_string_dests(operand, root, policy)?,
                        'f' => check_env_file_dest(operand, root, policy)?,
                        _ => {}
                    }
                }
                i += if attached.is_empty() { 2 } else { 1 };
            }
            None => i += 1,
        }
    }
    Ok(())
}

fn continue_env_after_operand(
    args: &[impl AsRef<str>],
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    for (i, token) in args.iter().enumerate() {
        if is_env_program(token.as_ref()) {
            return check_env_flag_dests(&args[i + 1..], root, policy);
        }
    }
    Ok(())
}

fn check_env_named_operand(
    name: &str,
    value: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    match name {
        "split-string" => check_env_split_string_dests(value, root, policy),
        "file" => check_env_file_dest(value, root, policy),
        _ => Ok(()),
    }
}

fn check_env_file_dest(path: &str, root: &Path, policy: &DenyPolicy) -> Result<(), CheckDestError> {
    let dest = dest_under_root(root, path);
    check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root)).map(|_| ())
}

/// Join extracted command dests under `root` and dest-deny each.
///
/// Absolute dests stay as given. Empty tokens are skipped. Flag-looking
/// peeled tokens are skipped except an attached `--flag=.env` /
/// `-f=.env` suffix or a GNU glued short dest (`-a.env`, clustered
/// `-la.env`), which is dest-denied via [`check_dest`]. After
/// peeling, an `env`/`env.exe` token dest-denies the following tokens
/// with the same env-flag dest check used for argv0 env.
pub fn check_command_dests(
    command: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    for (_display, candidate) in command_path_tokens(command) {
        for peeled in peel_shell_parts(&candidate) {
            if peeled.is_empty() {
                continue;
            }
            if let Some(value) = attached_flag_dest(peeled) {
                let dest = dest_under_root(root, value);
                check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
                continue;
            }
            if peeled.starts_with('-') {
                continue;
            }
            let dest = dest_under_root(root, peeled);
            check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
            if let Some(value) = assignment_dest_value(peeled) {
                let dest = dest_under_root(root, value);
                check_dest_rooted(&dest.to_string_lossy(), policy, None, Some(root))?;
            }
        }
    }
    check_command_string_env_dests(command, root, policy)
}

/// After peeling a command string, dest-deny env `-S`/`--file` operands.
///
/// Recurses into a shell `-c` body. Also peels `cmd` / `pwsh` `/c`,
/// `-Command`, `-CommandWithArgs`, `-EncodedCommand`, `-EncodedArguments`,
/// and `-File` (including `--switch` and unique prefixes) from remaining
/// string tokens. Attached `--flag=.env` and GNU glued shorts
/// (`-a.env`, clustered `-la.env`) are dest-denied via
/// [`check_command_dests`].
fn check_command_string_env_dests(
    command: &str,
    root: &Path,
    policy: &DenyPolicy,
) -> Result<(), CheckDestError> {
    for part in peel_shell_parts(command) {
        let tokens = command_string_tokens(part);
        for (i, token) in tokens.iter().enumerate() {
            if is_env_program(*token) {
                check_env_flag_dests(&tokens[i + 1..], root, policy)?;
            }
            if let Some(body) = shell_c_body(token, tokens.get(i + 1).copied()) {
                check_command_string_env_dests(body, root, policy)?;
            }
            if is_cmd_program(token) || is_powershell_program(token) {
                check_cmd_powershell_remaining_dests(token, &tokens[i + 1..], root, policy)?;
            }
        }
    }
    Ok(())
}

/// Whitespace words; matching quotes yield the inner string as one token.
fn command_string_tokens(command: &str) -> Vec<&str> {
    let bytes = command.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i].is_ascii_whitespace() {
            i += 1;
            continue;
        }
        if bytes[i] == b'\'' || bytes[i] == b'"' {
            let q = bytes[i];
            i += 1;
            let start = i;
            while i < bytes.len() && bytes[i] != q {
                i += 1;
            }
            out.push(&command[start..i]);
            if i < bytes.len() {
                i += 1;
            }
            continue;
        }
        let start = i;
        while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        out.push(&command[start..i]);
    }
    out
}

/// Committed dotenv templates, not live env files.
pub fn is_env_template_basename(name: &str) -> bool {
    let base = name
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(name)
        .to_ascii_lowercase();
    base.starts_with(".env.")
        && (base.ends_with(".example") || base.ends_with(".sample") || base.ends_with(".template"))
}

/// Gitignore-style dest-deny glob subset.
///
/// Rejects brace alternation, backslash escapes, empty path segments,
/// and `.` / `..` segments. Default [`default_secret_denies`] rows pass.
/// Hosts match [`AgentLockError`] when an `agent.lock` extra fails.
pub fn validate_deny_glob(glob: &str) -> Result<(), &'static str> {
    let glob = glob.trim();
    if glob.is_empty() {
        return Err("empty dest-deny glob");
    }
    if glob.contains('{') || glob.contains('}') {
        return Err("brace alternation is not supported");
    }
    if glob.contains('\\') {
        return Err("backslash escapes are not supported");
    }
    let normalized = normalize_glob_text(glob);
    let segs: Vec<&str> = normalized.split('/').collect();
    if segs.iter().any(|s| s.is_empty()) {
        return Err("empty path segment");
    }
    if segs.iter().any(|s| *s == "." || *s == "..") {
        return Err("'.' / '..' path segment");
    }
    Ok(())
}

/// Seatbelt regex for one dest-deny glob under an RW prefix.
///
/// `**/.env` matches `prefix/.env` and `prefix/sub/.env`. Interior `**`
/// is recursive (`src/**/*.pem` matches `src/x.pem` and `src/a/b.pem`).
/// ASCII letters become `[Aa]` so Seatbelt matches the case-insensitive
/// userspace glob dialect. SBPL has no in-tree `(?i)` support.
/// Used by macOS wrap and by the dialect table test on every OS.
pub fn dest_deny_glob_regex(prefix: &str, glob: &str) -> Option<String> {
    validate_deny_glob(glob).ok()?;
    let mut glob = glob.trim();
    if glob.is_empty() {
        return None;
    }
    let nested = glob.starts_with("**/");
    if nested {
        glob = glob.strip_prefix("**/")?;
    }
    let trailing_dir = glob.ends_with("/**");
    if trailing_dir {
        glob = glob.strip_suffix("/**")?;
    }
    if glob.is_empty() {
        return None;
    }
    let mut body = String::new();
    let chars: Vec<char> = glob.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '*' {
            if i + 1 < chars.len() && chars[i + 1] == '*' {
                body.push_str("(.*/)?");
                i += 2;
                if i < chars.len() && chars[i] == '/' {
                    i += 1;
                }
                continue;
            }
            body.push_str("[^/]*");
            i += 1;
            continue;
        }
        if matches!(
            chars[i],
            '.' | '+' | '?' | '(' | ')' | '[' | ']' | '|' | '^' | '$'
        ) {
            body.push('\\');
            body.push(chars[i]);
            i += 1;
            continue;
        }
        push_ascii_letter_class(&mut body, chars[i]);
        i += 1;
    }
    if trailing_dir {
        body.push_str("(/.*)?");
    }
    let prefix = case_fold_regex_letters(prefix);
    if nested {
        Some(format!("^{prefix}/(.*/)?{body}$"))
    } else {
        Some(format!("^{prefix}/{body}$"))
    }
}

fn push_ascii_letter_class(out: &mut String, c: char) {
    if c.is_ascii_alphabetic() {
        out.push('[');
        out.push(c.to_ascii_uppercase());
        out.push(c.to_ascii_lowercase());
        out.push(']');
    } else {
        out.push(c);
    }
}

fn case_fold_regex_letters(s: &str) -> String {
    let mut out = String::new();
    let mut escaped = false;
    for c in s.chars() {
        if escaped {
            out.push(c);
            escaped = false;
            continue;
        }
        if c == '\\' {
            out.push('\\');
            escaped = true;
            continue;
        }
        push_ascii_letter_class(&mut out, c);
    }
    out
}

pub fn path_matches_deny_glob(pattern: &str, path: &str) -> bool {
    let pattern = normalize_glob_text(pattern);
    let path = normalize_glob_text(path);
    let pat: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    match_glob_segments(&pat, &segs)
}

pub fn path_is_denied_glob(globs: &[String], path: &str) -> bool {
    first_matching_deny_glob(globs, path).is_some()
}

fn first_matching_deny_glob(globs: &[String], path: &str) -> Option<String> {
    first_matching_deny_glob_under(globs, path, None).filter(|g| g != "..")
}

/// Glob match for `path` relative to `root` when `root` is set.
///
/// Slash-globs are anchored at the workspace, after stripping either
/// firmlink spelling (`/tmp` and `/private/tmp`). A `..` that leaves the
/// root is denied. Single-segment globs (`*.pem`, `id_rsa`) also match
/// the basename. `**/` globs still match paths outside the root.
pub fn path_is_denied_under_root(globs: &[String], path: &str, root: &Path) -> bool {
    first_matching_deny_glob_under(globs, path, Some(root)).is_some()
}

fn first_matching_deny_glob_under(
    globs: &[String],
    path: &str,
    root: Option<&Path>,
) -> Option<String> {
    let Some(root) = root else {
        return first_matching_deny_glob_unscoped(globs, path);
    };
    let had_dotdot = path.split(['/', '\\']).any(|seg| seg == "..");
    let Some(collapsed) = lexical_absolute(path) else {
        return Some("..".to_string());
    };
    let (match_path, outside) = match strip_workspace_root(&collapsed, root) {
        Some(rel) => (rel, false),
        None if had_dotdot => return Some("..".to_string()),
        None => (collapsed, true),
    };
    let template = is_env_template_basename(&match_path);
    let base = match_path.rsplit('/').next().unwrap_or(match_path.as_str());
    globs
        .iter()
        .find(|g| {
            if template && is_default_env_star_glob(g) {
                return false;
            }
            let slashed = normalize_glob_text(g).contains('/');
            if outside && slashed && !normalize_glob_text(g).starts_with("**/") {
                return false;
            }
            if path_matches_deny_glob(g, &match_path) {
                return true;
            }
            !slashed && path_matches_deny_glob(g, base)
        })
        .cloned()
}

/// Collapse `.` and `..`. `Err` is not used; `None` means `..` left the
/// filesystem root.
fn lexical_absolute(path: &str) -> Option<String> {
    let norm = normalize_glob_text(path);
    let absolute = norm.starts_with('/');
    let mut segs = Vec::new();
    for seg in norm.split('/') {
        if seg.is_empty() || seg == "." {
            continue;
        }
        if seg == ".." {
            if segs.pop().is_none() && absolute {
                return None;
            }
            continue;
        }
        segs.push(seg);
    }
    if absolute {
        Some(format!("/{}", segs.join("/")))
    } else {
        Some(segs.join("/"))
    }
}

fn strip_workspace_root(path: &str, root: &Path) -> Option<String> {
    let path_segs = lexical_absolute(path)?;
    for spelling in firmlink_spellings(root) {
        let Some(root_s) = lexical_absolute(&path_as_glob(&spelling)) else {
            continue;
        };
        if let Some(rel) = strip_prefix_path(&path_segs, &root_s) {
            return Some(rel);
        }
    }
    None
}

fn strip_prefix_path(path: &str, root: &str) -> Option<String> {
    let path = path.trim_end_matches('/');
    let root = root.trim_end_matches('/');
    if path.eq_ignore_ascii_case(root) {
        return Some(String::new());
    }
    let prefix = format!("{root}/");
    if path.len() >= prefix.len() && path[..prefix.len()].eq_ignore_ascii_case(&prefix) {
        return Some(path[prefix.len()..].to_string());
    }
    None
}

fn firmlink_spellings(path: &Path) -> Vec<PathBuf> {
    let mut out = vec![path.to_path_buf()];
    if let Some(alias) = firmlink_alias_path(path)
        && !out.iter().any(|p| p == &alias)
    {
        out.push(alias);
    }
    out
}

fn firmlink_alias_path(path: &Path) -> Option<PathBuf> {
    let raw = path.to_str()?.replace('\\', "/");
    const PAIRS: [(&str, &str); 3] = [
        ("/tmp", "/private/tmp"),
        ("/var", "/private/var"),
        ("/etc", "/private/etc"),
    ];
    for (public, private) in PAIRS {
        if raw == public || raw.starts_with(&format!("{public}/")) {
            return Some(PathBuf::from(format!(
                "{private}{}",
                raw.strip_prefix(public).unwrap_or("")
            )));
        }
        if raw == private || raw.starts_with(&format!("{private}/")) {
            return Some(PathBuf::from(format!(
                "{public}{}",
                raw.strip_prefix(private).unwrap_or("")
            )));
        }
    }
    None
}

pub(crate) fn first_matching_deny_glob_unscoped(globs: &[String], path: &str) -> Option<String> {
    let template = is_env_template_basename(path);
    let base = path.rsplit(['/', '\\']).next().unwrap_or(path);
    globs
        .iter()
        .find(|g| {
            if template && is_default_env_star_glob(g) {
                return false;
            }
            let slashed = normalize_glob_text(g).contains('/');
            path_matches_deny_glob(g, path) || (!slashed && path_matches_deny_glob(g, base))
        })
        .cloned()
}

pub(crate) fn is_default_env_star_glob(pattern: &str) -> bool {
    normalize_glob_text(pattern) == "**/.env.*"
}

fn path_as_glob(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn normalize_glob_text(s: &str) -> String {
    s.replace('\\', "/").to_ascii_lowercase()
}

fn match_glob_segments(pat: &[&str], path: &[&str]) -> bool {
    match (pat.split_first(), path.split_first()) {
        (None, None) => true,
        (None, Some(_)) => false,
        (Some((&"**", rest)), _) => {
            if rest.is_empty() {
                return true;
            }
            for i in 0..=path.len() {
                if match_glob_segments(rest, &path[i..]) {
                    return true;
                }
            }
            false
        }
        (Some((p, prest)), Some((h, hrest))) => {
            glob_segment(p, h) && match_glob_segments(prest, hrest)
        }
        (Some(_), None) => false,
    }
}

fn glob_segment(pat: &str, text: &str) -> bool {
    match_star(pat.as_bytes(), text.as_bytes())
}

fn match_star(pat: &[u8], text: &[u8]) -> bool {
    match pat.split_first() {
        None => text.is_empty(),
        Some((&b'*', rest)) => {
            for i in 0..=text.len() {
                if match_star(rest, &text[i..]) {
                    return true;
                }
            }
            false
        }
        Some((p, prest)) => match text.split_first() {
            Some((t, trest)) if p == t => match_star(prest, trest),
            _ => false,
        },
    }
}

#[derive(Debug)]
enum HardlinkHit {
    Allowed,
    Denied { sibling: Option<String> },
}

/// Earliest deny glob wins. Equal globs use the basename so the
/// reported sibling does not follow directory order.
fn denied_basename_rank(
    globs: &[String],
    path: &Path,
    root: Option<&Path>,
) -> Option<(usize, String)> {
    let glob = first_matching_deny_glob_under(globs, &path_as_glob(path), root)?;
    if glob == ".." {
        return None;
    }
    let idx = globs
        .iter()
        .position(|candidate| candidate == &glob)
        .unwrap_or(usize::MAX);
    let base = path.file_name()?.to_string_lossy().into_owned();
    Some((idx, base))
}

fn prefer_sibling(best: Option<(usize, String)>, next: (usize, String)) -> Option<(usize, String)> {
    match best {
        None => Some(next),
        Some((idx, name)) if next.0 < idx || (next.0 == idx && next.1 < name) => Some(next),
        Some(kept) => Some(kept),
    }
}

fn hardlink_sibling_denied(path: &Path, canon: Option<&Path>, policy: &DenyPolicy) -> bool {
    matches!(
        hardlink_sibling_hit(path, canon, policy, None),
        HardlinkHit::Denied { .. }
    )
}

fn hardlink_sibling_hit(
    path: &Path,
    canon: Option<&Path>,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> HardlinkHit {
    #[cfg(unix)]
    {
        hardlink_sibling_hit_unix(path, canon, policy, root)
    }
    #[cfg(windows)]
    {
        hardlink_sibling_hit_windows(path, canon, policy, root)
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (path, canon, policy, root);
        HardlinkHit::Allowed
    }
}

#[cfg(unix)]
fn hardlink_sibling_hit_unix(
    path: &Path,
    canon: Option<&Path>,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> HardlinkHit {
    use std::os::unix::fs::MetadataExt;

    let meta = match canon
        .map(std::fs::metadata)
        .unwrap_or_else(|| std::fs::symlink_metadata(path))
    {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
            return HardlinkHit::Denied { sibling: None };
        }
        Err(_) => return HardlinkHit::Allowed,
    };
    // Directory nlink counts children, not extra names for this inode.
    if meta.file_type().is_dir() {
        return HardlinkHit::Allowed;
    }
    let nlink = meta.nlink();
    if nlink <= 1 {
        return HardlinkHit::Allowed;
    }
    let mut parents = Vec::new();
    push_scan_parent(&mut parents, path.parent());
    if let Some(c) = canon {
        push_scan_parent(&mut parents, c.parent());
    }
    if parents.is_empty() {
        return HardlinkHit::Denied { sibling: None };
    }
    let mut found = 0u64;
    let mut best: Option<(usize, String)> = None;
    for parent in &parents {
        let entries = match std::fs::read_dir(parent) {
            Ok(rd) => rd,
            Err(_) if best.is_some() => break,
            Err(_) => return HardlinkHit::Denied { sibling: None },
        };
        for entry in entries.flatten() {
            let entry_path = entry.path();
            let sibling_meta = match std::fs::symlink_metadata(&entry_path) {
                Ok(m) => m,
                Err(_) => continue,
            };
            if sibling_meta.dev() != meta.dev() || sibling_meta.ino() != meta.ino() {
                continue;
            }
            found += 1;
            if let Some(rank) = denied_basename_rank(policy.globs(), &entry_path, root) {
                best = prefer_sibling(best, rank);
            }
        }
    }
    if let Some((_, sibling)) = best {
        return HardlinkHit::Denied {
            sibling: Some(sibling),
        };
    }
    if found < nlink {
        HardlinkHit::Denied { sibling: None }
    } else {
        HardlinkHit::Allowed
    }
}

#[cfg(unix)]
fn push_scan_parent(parents: &mut Vec<PathBuf>, parent: Option<&Path>) {
    let parent = match parent {
        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
        Some(_) => PathBuf::from("."),
        None => return,
    };
    let key = std::fs::canonicalize(&parent).unwrap_or(parent);
    if !parents.iter().any(|p| p == &key) {
        parents.push(key);
    }
}

/// Win32 `ERROR_NO_MORE_FILES` (FindNextFile).
#[cfg(any(windows, test))]
const WIN_ERROR_NO_MORE_FILES: u32 = 18;
/// Win32 `ERROR_HANDLE_EOF` (FindNextFileNameW).
#[cfg(any(windows, test))]
const WIN_ERROR_HANDLE_EOF: u32 = 38;

#[cfg(any(windows, test))]
fn win_find_next_exhausted(err: u32) -> bool {
    err == WIN_ERROR_NO_MORE_FILES || err == WIN_ERROR_HANDLE_EOF
}

/// Dest-deny from NTFS names plus `nNumberOfLinks`.
/// Incomplete listing (`names.len() < nlink`) is HardlinkSibling.
#[cfg(any(windows, test))]
fn hardlink_hit_from_win_names(
    names: &[std::ffi::OsString],
    nlink: u32,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> HardlinkHit {
    if names.len() < nlink as usize {
        return HardlinkHit::Denied { sibling: None };
    }
    if names.len() <= 1 {
        return HardlinkHit::Allowed;
    }
    let mut best: Option<(usize, String)> = None;
    for n in names {
        let s = n.to_string_lossy().replace('\\', "/");
        if let Some(rank) = denied_basename_rank(policy.globs(), Path::new(&s), root) {
            best = prefer_sibling(best, rank);
        }
    }
    if let Some((_, sibling)) = best {
        return HardlinkHit::Denied {
            sibling: Some(sibling),
        };
    }
    HardlinkHit::Allowed
}

/// `MetadataExt::file_index` is unstable (`windows_by_handle`). List names
/// with FindFirstFileNameW instead.
#[cfg(windows)]
fn hardlink_sibling_hit_windows(
    path: &Path,
    canon: Option<&Path>,
    policy: &DenyPolicy,
    root: Option<&Path>,
) -> HardlinkHit {
    let probe = canon.unwrap_or(path);
    let meta = match std::fs::metadata(probe) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
            return HardlinkHit::Denied { sibling: None };
        }
        Err(_) => return HardlinkHit::Allowed,
    };
    if meta.is_dir() {
        return HardlinkHit::Allowed;
    }
    let nlink = match win_path_by_handle(probe) {
        Ok(info) => info.nlink,
        Err(_) => return HardlinkHit::Denied { sibling: None },
    };
    match win_hardlink_names(probe) {
        Ok(names) => hardlink_hit_from_win_names(&names, nlink, policy, root),
        Err(_) => HardlinkHit::Denied { sibling: None },
    }
}

#[cfg(windows)]
fn win_hardlink_names(path: &Path) -> std::io::Result<Vec<std::ffi::OsString>> {
    use std::os::windows::ffi::{OsStrExt, OsStringExt};

    type Handle = *mut core::ffi::c_void;
    type Dword = u32;
    const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
    const ERROR_MORE_DATA: Dword = 234;

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn FindFirstFileNameW(
            lp_file_name: *const u16,
            dw_flags: Dword,
            string_length: *mut Dword,
            link_name: *mut u16,
        ) -> Handle;
        fn FindNextFileNameW(
            h_find_stream: Handle,
            string_length: *mut Dword,
            link_name: *mut u16,
        ) -> i32;
        fn FindClose(h_find_file: Handle) -> i32;
        fn GetLastError() -> Dword;
    }

    struct FindNameHandle(Handle);
    impl Drop for FindNameHandle {
        fn drop(&mut self) {
            if self.0 != INVALID_HANDLE_VALUE {
                // SAFETY: `self.0` came from FindFirstFileNameW.
                unsafe {
                    FindClose(self.0);
                }
                self.0 = INVALID_HANDLE_VALUE;
            }
        }
    }

    fn wide_to_os(buf: &[u16], claimed: usize) -> std::ffi::OsString {
        let end = buf
            .iter()
            .position(|&c| c == 0)
            .unwrap_or(claimed.min(buf.len()));
        std::ffi::OsString::from_wide(&buf[..end])
    }

    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let mut len: Dword = 256;
    let mut buf = vec![0u16; 256];
    let handle = loop {
        // SAFETY: `wide` is a NUL-terminated path; `buf` is at least `len` units.
        let h = unsafe { FindFirstFileNameW(wide.as_ptr(), 0, &mut len, buf.as_mut_ptr()) };
        if h != INVALID_HANDLE_VALUE {
            break FindNameHandle(h);
        }
        let err = unsafe { GetLastError() };
        if err == ERROR_MORE_DATA {
            buf.resize(len as usize, 0);
            continue;
        }
        return Err(std::io::Error::from_raw_os_error(err as i32));
    };

    let mut names = vec![wide_to_os(&buf, len as usize)];
    loop {
        len = buf.len() as Dword;
        // SAFETY: `handle.0` came from FindFirstFileNameW; `buf` matches `len`.
        let ok = unsafe { FindNextFileNameW(handle.0, &mut len, buf.as_mut_ptr()) };
        if ok == 0 {
            let err = unsafe { GetLastError() };
            if err == ERROR_MORE_DATA {
                buf.resize(len as usize, 0);
                continue;
            }
            if win_find_next_exhausted(err) {
                break;
            }
            return Err(std::io::Error::from_raw_os_error(err as i32));
        }
        names.push(wide_to_os(&buf, len as usize));
    }
    Ok(names)
}

#[cfg(windows)]
struct WinHandleInfo {
    volume: u32,
    index: u64,
    nlink: u32,
}

#[cfg(windows)]
fn win_path_by_handle(path: &Path) -> std::io::Result<WinHandleInfo> {
    use std::os::windows::ffi::OsStrExt;

    type Handle = *mut core::ffi::c_void;
    type Dword = u32;
    const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
    const FILE_READ_ATTRIBUTES: Dword = 0x0080;
    const FILE_SHARE_READ: Dword = 0x0001;
    const FILE_SHARE_WRITE: Dword = 0x0002;
    const FILE_SHARE_DELETE: Dword = 0x0004;
    const OPEN_EXISTING: Dword = 3;
    const FILE_FLAG_BACKUP_SEMANTICS: Dword = 0x0200_0000;
    const FILE_FLAG_OPEN_REPARSE_POINT: Dword = 0x0020_0000;

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn CreateFileW(
            lp_file_name: *const u16,
            dw_desired_access: Dword,
            dw_share_mode: Dword,
            lp_security_attributes: *mut core::ffi::c_void,
            dw_creation_disposition: Dword,
            dw_flags_and_attributes: Dword,
            h_template_file: Handle,
        ) -> Handle;
        fn CloseHandle(h_object: Handle) -> i32;
        fn GetLastError() -> Dword;
    }

    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    // SAFETY: `wide` is a NUL-terminated path.
    let handle = unsafe {
        CreateFileW(
            wide.as_ptr(),
            FILE_READ_ATTRIBUTES,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            core::ptr::null_mut(),
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
            core::ptr::null_mut(),
        )
    };
    if handle == INVALID_HANDLE_VALUE {
        let err = unsafe { GetLastError() };
        return Err(std::io::Error::from_raw_os_error(err as i32));
    }
    let info = win_handle_info(handle);
    unsafe {
        CloseHandle(handle);
    }
    info
}

#[cfg(windows)]
fn win_handle_info(handle: *mut core::ffi::c_void) -> std::io::Result<WinHandleInfo> {
    type Dword = u32;

    #[repr(C)]
    struct ByHandleFileInformation {
        dw_file_attributes: Dword,
        ft_creation_time_lo: Dword,
        ft_creation_time_hi: Dword,
        ft_last_access_time_lo: Dword,
        ft_last_access_time_hi: Dword,
        ft_last_write_time_lo: Dword,
        ft_last_write_time_hi: Dword,
        dw_volume_serial_number: Dword,
        n_file_size_high: Dword,
        n_file_size_low: Dword,
        n_number_of_links: Dword,
        n_file_index_high: Dword,
        n_file_index_low: Dword,
    }

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GetFileInformationByHandle(
            h_file: *mut core::ffi::c_void,
            lp_file_information: *mut ByHandleFileInformation,
        ) -> i32;
        fn GetLastError() -> Dword;
    }

    let mut info = ByHandleFileInformation {
        dw_file_attributes: 0,
        ft_creation_time_lo: 0,
        ft_creation_time_hi: 0,
        ft_last_access_time_lo: 0,
        ft_last_access_time_hi: 0,
        ft_last_write_time_lo: 0,
        ft_last_write_time_hi: 0,
        dw_volume_serial_number: 0,
        n_file_size_high: 0,
        n_file_size_low: 0,
        n_number_of_links: 0,
        n_file_index_high: 0,
        n_file_index_low: 0,
    };
    // SAFETY: `handle` is an open file handle; `info` is the Win32 layout.
    let ok = unsafe { GetFileInformationByHandle(handle, &mut info) };
    if ok == 0 {
        let err = unsafe { GetLastError() };
        return Err(std::io::Error::from_raw_os_error(err as i32));
    }
    Ok(WinHandleInfo {
        volume: info.dw_volume_serial_number,
        index: (u64::from(info.n_file_index_high) << 32) | u64::from(info.n_file_index_low),
        nlink: info.n_number_of_links,
    })
}

fn peel_shell_meta(s: &str) -> &str {
    s.trim_matches(|c: char| matches!(c, ';' | '|' | '&' | ')' | '(' | '<' | '>' | '`' | ','))
}

fn peel_shell_parts(s: &str) -> impl Iterator<Item = &str> {
    s.split([';', '|', '&', ')', '(', '<', '>', '`', ','])
        .map(peel_shell_meta)
        .filter(|p| !p.is_empty())
}

fn candidate_is_denied(candidate: &str, policy: &DenyPolicy) -> bool {
    for peeled in peel_shell_parts(candidate) {
        if peeled.starts_with('-') {
            continue;
        }
        if is_path_denied(Path::new(peeled), policy) {
            return true;
        }
        if let Some(value) = assignment_dest_value(peeled)
            && is_path_denied(Path::new(value), policy)
        {
            return true;
        }
        if let Some((_, after)) = peeled.rsplit_once(':') {
            let after = peel_shell_meta(after);
            if !after.is_empty()
                && !after.starts_with('-')
                && is_path_denied(Path::new(after), policy)
            {
                return true;
            }
        }
    }
    false
}

fn command_path_tokens(command: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    collect_function_calls(command, &mut out);
    collect_quoted_and_words(command, &mut out);
    out
}

fn collect_function_calls(s: &str, out: &mut Vec<(String, String)>) {
    let mut pos = 0;
    while let Some((end, display, path)) = next_function_call(s, pos) {
        out.push((display, path));
        pos = end;
    }
}

fn next_function_call(s: &str, from: usize) -> Option<(usize, String, String)> {
    let bytes = s.as_bytes();
    let mut i = from;
    while i < bytes.len() {
        if is_ident_start(bytes[i]) {
            let start = i;
            i += 1;
            while i < bytes.len() && is_ident_cont(bytes[i]) {
                i += 1;
            }
            let ident_end = i;
            while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                i += 1;
            }
            if i < bytes.len() && bytes[i] == b'(' {
                i += 1;
                while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                    i += 1;
                }
                if i < bytes.len() && (bytes[i] == b'\'' || bytes[i] == b'"') {
                    let q = bytes[i];
                    i += 1;
                    let path_start = i;
                    while i < bytes.len() && bytes[i] != q {
                        i += 1;
                    }
                    if i < bytes.len() && bytes[i] == q {
                        let path = s[path_start..i].to_string();
                        i += 1;
                        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
                            i += 1;
                        }
                        if i < bytes.len() && bytes[i] == b')' {
                            i += 1;
                            let display = s[start..i].to_string();
                            return Some((i, display, path));
                        }
                    }
                }
            }
            i = ident_end.max(start + 1);
            continue;
        }
        i += 1;
    }
    None
}

fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == b'_'
}

fn is_ident_cont(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

fn collect_quoted_and_words(s: &str, out: &mut Vec<(String, String)>) {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i].is_ascii_whitespace() {
            i += 1;
            continue;
        }
        if bytes[i] == b'\'' || bytes[i] == b'"' {
            let q = bytes[i];
            i += 1;
            let start = i;
            while i < bytes.len() && bytes[i] != q {
                i += 1;
            }
            let inner = &s[start..i];
            if i < bytes.len() {
                i += 1;
            }
            collect_function_calls(inner, out);
            collect_quoted_and_words(inner, out);
            out.push((inner.to_string(), inner.to_string()));
            continue;
        }
        let start = i;
        while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        let raw = &s[start..i];
        let peeled = peel_shell_meta(raw);
        out.push((raw.to_string(), peeled.to_string()));
        if let Some((_, after)) = peeled.rsplit_once(':') {
            out.push((raw.to_string(), after.to_string()));
        }
    }
}

/// v1 list is byte-identical to Bline `default_secret_denies()`.
/// Do not add `**/.azure/**` or `**/.config/gh/**`.
pub fn default_secret_denies() -> Vec<String> {
    vec![
        "**/.env".into(),
        "**/.env.*".into(),
        "**/*.pem".into(),
        "**/*.key".into(),
        "**/*.p12".into(),
        "**/*.pfx".into(),
        "**/id_rsa".into(),
        "**/id_ed25519".into(),
        "**/id_ecdsa".into(),
        "**/id_dsa".into(),
        "**/id_eddsa".into(),
        "**/.npmrc".into(),
        "**/.pypirc".into(),
        "**/.docker/config.json".into(),
        "**/kubeconfig".into(),
        "**/.kube/config".into(),
        "**/secrets.json".into(),
        "**/service-account*.json".into(),
        "**/.ssh/**".into(),
        "**/token.json".into(),
        "**/secring.gpg".into(),
        "**/.gnupg/private-keys-v1.d/**".into(),
        "**/credentials.json".into(),
        "**/.aws/credentials".into(),
        "**/.netrc".into(),
        "**/secrets/**".into(),
        "**/credentials/**".into(),
        "**/gateway/pairing.json".into(),
        "**/auth.json".into(),
        "**/auth-*.json".into(),
    ]
}

#[cfg(test)]
mod classify_hardlink_tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn hardlink_denied_when_canon_is_missing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let env = dir.path().join(".env");
        std::fs::write(&env, "API_KEY=secret\n").expect("write .env");
        let sibling = dir.path().join("notes.txt");
        std::fs::hard_link(&env, &sibling).expect("hardlink");
        let policy = DenyPolicy::default();
        assert!(
            hardlink_sibling_denied(&sibling, None, &policy),
            "nlink > 1 must dest-deny when canonicalize is unavailable"
        );
        assert!(!hardlink_sibling_denied(
            Path::new("no-such-workpen-hardlink-xyz"),
            None,
            &policy
        ));
    }

    #[test]
    fn win_find_next_exhausted_is_eof_not_other_errors() {
        assert!(win_find_next_exhausted(WIN_ERROR_NO_MORE_FILES));
        assert!(win_find_next_exhausted(WIN_ERROR_HANDLE_EOF));
        assert!(!win_find_next_exhausted(5));
        assert!(!win_find_next_exhausted(234));
    }

    #[test]
    fn win_names_shorter_than_nlink_is_hardlink_sibling() {
        let policy = DenyPolicy::default();
        let names = [std::ffi::OsString::from(r"C:\ws\notes.txt")];
        match hardlink_hit_from_win_names(&names, 2, &policy, None) {
            HardlinkHit::Denied { sibling: None } => {}
            other => panic!("incomplete name list must deny, got {other:?}"),
        }
    }

    #[test]
    fn win_names_matching_nlink_without_deny_glob_is_allowed() {
        let policy = DenyPolicy::default();
        let names = [std::ffi::OsString::from(r"C:\ws\notes.txt")];
        match hardlink_hit_from_win_names(&names, 1, &policy, None) {
            HardlinkHit::Allowed => {}
            other => panic!("single name and nlink 1 must allow, got {other:?}"),
        }
        let two = [
            std::ffi::OsString::from(r"C:\ws\a.txt"),
            std::ffi::OsString::from(r"C:\ws\b.txt"),
        ];
        match hardlink_hit_from_win_names(&two, 2, &policy, None) {
            HardlinkHit::Allowed => {}
            other => panic!("listed names with no deny glob must allow, got {other:?}"),
        }
    }

    #[test]
    fn win_names_denied_glob_reports_sibling_basename() {
        let policy = DenyPolicy::default();
        let names = [
            std::ffi::OsString::from(r"C:\ws\.env"),
            std::ffi::OsString::from(r"C:\ws\notes.txt"),
        ];
        match hardlink_hit_from_win_names(&names, 2, &policy, None) {
            HardlinkHit::Denied {
                sibling: Some(name),
            } => assert_eq!(name, ".env"),
            other => panic!("hardlink of .env must name sibling, got {other:?}"),
        }
    }

    #[test]
    fn win_names_prefer_earlier_deny_glob_over_list_order() {
        let policy = DenyPolicy::default();
        let names = [
            std::ffi::OsString::from(r"C:\ws\.env.example-link"),
            std::ffi::OsString::from(r"C:\ws\notes.txt"),
            std::ffi::OsString::from(r"C:\ws\.env"),
        ];
        match hardlink_hit_from_win_names(&names, 3, &policy, None) {
            HardlinkHit::Denied {
                sibling: Some(name),
            } => assert_eq!(name, ".env"),
            other => panic!("earlier deny glob must win, got {other:?}"),
        }
    }
}