kache 0.20.0

Zero-copy, content-addressed build cache for Rust, C/C++ and more, with S3 and shared-filesystem remotes.
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
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
//! Compiler abstraction.
//!
//! Each supported compiler adapter (today: rustc and C-family compilers)
//! implements the [`Compiler`] trait and exports a [`CompilerAdapter`]
//! descriptor. Detection walks those descriptors instead of returning a closed
//! enum, so adding an adapter is adding a module-owned descriptor plus wrapper
//! dispatch, not growing a central taxonomy of future tool kinds.
//!
//! **Scope.** The trait covers the operations with a clean generic shape
//! today: `parse`, `refuse_reasons`, `cache_key`, `execute`, and
//! `classify_output` (per-file kind classification used by the wrapper to
//! dispatch link strategy and post-restore processing without filename
//! pattern matching). Storage metadata (crate types, features,
//! target/profile) and the restore loop's path resolution still touch
//! [`crate::args::RustcArgs`] fields directly in [`crate::wrapper`]; those
//! move behind the trait when adding a second compiler forces the
//! abstraction.

use anyhow::Result;
use std::path::{Path, PathBuf};

use crate::link::LinkStrategy;

pub mod cc;
pub mod flags;
pub mod platform;
pub mod rustc;

pub use platform::Platform;

pub use crate::compile::CompileResult;

/// Stable adapter identifier.
///
/// This is intentionally an open string newtype instead of a closed enum:
/// adapter ids name concrete implementations that exist today, while future
/// adapters bring their own ids without forcing kache to define an abstract
/// "kind" hierarchy up front.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CompilerId(&'static str);

impl CompilerId {
    pub const fn new(id: &'static str) -> Self {
        Self(id)
    }

    pub const fn as_str(self) -> &'static str {
        self.0
    }
}

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

/// Module-owned adapter descriptor used for argv detection.
#[derive(Debug, Clone, Copy)]
pub struct CompilerAdapter {
    id: CompilerId,
    display_name: &'static str,
    recognizes: fn(&[String]) -> bool,
}

impl CompilerAdapter {
    pub const fn new(
        id: CompilerId,
        display_name: &'static str,
        recognizes: fn(&[String]) -> bool,
    ) -> Self {
        Self {
            id,
            display_name,
            recognizes,
        }
    }

    pub const fn id(self) -> CompilerId {
        self.id
    }

    pub const fn display_name(self) -> &'static str {
        self.display_name
    }

    pub fn recognizes(self, args: &[String]) -> bool {
        (self.recognizes)(args)
    }
}

/// Reason an invocation cannot be cached. Empty list = cacheable.
///
/// Two variants:
///
/// - `NotPrimary`: the invocation is a query / probe (`--print`,
///   `-vV`) that exists to provide information to the caller, not to
///   produce a build artifact for downstream consumption. Caching is
///   meaningless — the call is one-shot informational.
/// - `Unsupported`: kache could in principle cache this, but the
///   feature / flag / mode isn't modeled yet. EVERYTHING that's
///   technically cacheable-with-engineering-effort lands here:
///   link-mode caching, multi-source per-source split, preprocessor /
///   assembly variant outputs, output-to-stdout, response-file
///   expansion, PCH / modules, classifier gaps. Message MUST include
///   "(not yet supported)" or equivalent so users reading the bench
///   output can tell it's a deferral, not a permanent limitation.
///
/// There is deliberately no third "won't ever cache" variant. For cc
/// (and rustc) every deterministic input-to-output function IS
/// cacheable in principle — even `-E` preprocessor output, even `-S`
/// assembly output, even stdout bytes. What separates them from `-c`
/// today is engineering priority, not categorical impossibility. The
/// taxonomy reflects that honestly so future work to support any of
/// them can drop a row to `Unsupported` and find this comment
/// describing the deferral, rather than running into a "NotACompile"
/// variant whose name lies about feasibility.
#[derive(Debug, Clone)]
pub enum RefuseReason {
    /// Not a primary compilation (e.g. `--print`, `-vV`, query mode).
    NotPrimary,
    /// Kache could cache this with engineering effort but doesn't yet.
    /// Message should include "(not yet supported)" so the deferral
    /// nature is explicit. Examples: link mode, multi-source compile,
    /// preprocessor / assembly variant outputs, output-to-stdout,
    /// response files, PCH, modules, unmodeled classifier flags.
    Unsupported(&'static str),
}

impl RefuseReason {
    /// Stable, human-readable *detail* of why caching was refused — the
    /// specifics (`cc link mode (whole-program caching) — not yet`). Pairs
    /// with [`category`](Self::category), which gives the coarse class. Used
    /// by the wrapper for the structured passthrough reason and by reporting.
    /// The string is a contract — changing it is observable.
    pub fn description(&self) -> &'static str {
        match self {
            RefuseReason::NotPrimary => "query / probe (--print, -vV)",
            RefuseReason::Unsupported(detail) => detail,
        }
    }

    /// Coarse class of the refusal, for the passthrough report's `category`
    /// column. `not-a-compile` is a query/probe that is conceptually not a
    /// compilation at all; `unsupported` is a real compile kache could cache
    /// with engineering effort but doesn't model yet (its detail reads
    /// "— not yet"). Neither is a failure — the build runs the compiler.
    pub fn category(&self) -> &'static str {
        match self {
            RefuseReason::NotPrimary => "not-a-compile",
            RefuseReason::Unsupported(_) => "unsupported",
        }
    }
}

/// Compiler-agnostic context passed to [`Compiler::cache_key`].
pub struct KeyCtx<'a, 'db> {
    pub file_hasher: &'a crate::cache_key::FileHasher<'db>,
    /// Strips machine-local path prefixes from key inputs so the same
    /// source produces the same key across hosts and worktrees. Lives
    /// in the context (not as a free function) so future per-compiler
    /// impls can pass a normalizer with extra rules (e.g. cc-family
    /// might know about `$SDKROOT`).
    pub path_normalizer: &'a crate::path_normalizer::PathNormalizer,
    /// kache's cache directory. Compiler-probe results (e.g. the cc
    /// `--version` identity line) are memoized under here so a probe
    /// runs once per build instead of once per translation unit — see
    /// [`crate::probe`].
    pub cache_dir: &'a Path,
    /// Opaque user-declared salt folded into the final key by every
    /// compiler family (see [`crate::cache_key::apply_key_salt`]).
    /// `None` leaves the key byte-identical to the unsalted case.
    pub key_salt: Option<&'a str>,
    /// User-declared env-var name patterns folded into the final key by every
    /// compiler family, for expansion-time reads the compiler never reports
    /// (see [`crate::cache_key::apply_key_env_vars`]). Empty leaves the key
    /// byte-identical to the undeclared case.
    pub key_env_vars: &'a [String],
    /// Digest from the invocation's already-resolved extra-input snapshot.
    /// Rustc folds it into the key; other compiler families currently resolve
    /// their own declaration because Cargo dep-info completion is Rust-only.
    pub extra_inputs_digest: Option<&'a str>,
}

/// Categorization of a compiler output file.
///
/// Used by the wrapper to drive two decisions per restored file without
/// scattering filename pattern matching: which [`LinkStrategy`] to use, and
/// which post-restore processing to apply (dep-info path expansion, codesign,
/// etc.). Centralizing the dispatch on `ArtifactKind` is what makes "skip
/// codesign for `.o`" or "rewrite paths in `.d`" structurally enforced
/// instead of dependent on remembering to add a string-suffix check at every
/// call site.
///
/// Open enum: future compilers extend with [`ArtifactKind::Other`] without
/// touching shared code; the safe default for an unrecognized kind is
/// `Hardlink` + no post-processing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArtifactKind {
    /// Linkable static library (`.rlib`, future C/C++ `.a` / `.lib`).
    Library,
    /// Dynamic library (`.dylib`, `.so`, `.dll`). Mutable post-build on
    /// macOS (codesigning).
    DynamicLibrary,
    /// Metadata-only artifact (Rust `.rmeta`).
    Metadata,
    /// Object file (`.o`, `.obj`, `.rcgu.o`). Linker input only — never loaded
    /// directly, never codesigned.
    Object,
    /// Dependency-info file (`.d` / `.pp`). Content references absolute paths
    /// that need rewriting on store/restore for cross-worktree portability.
    DepInfo,
    /// Executable. Mutable post-build (codesigning, stripping).
    Executable,
    /// A wasm target's linked module (`.wasm`) — the shape a `bin` or
    /// `cdylib` built for `wasm32-*` takes (kunobi-ninja/kache#431).
    ///
    /// Deliberately its own kind rather than a [`Self::DynamicLibrary`]:
    /// it shares that kind's *mutation* profile (build tooling such as
    /// substrate's wasm-builder post-processes the emitted module, so it
    /// must restore as an independent file, never a shared inode) but not
    /// its *loader* profile — a wasm module is never mapped by the OS
    /// loader, so it must not pick up the codesign post-restore action.
    WasmModule,
    /// Debug info sidecar (`.dwo`, `.pdb`, `.dSYM`).
    DebugSidecar,
    /// A kache-produced tar of a debug-info bundle *directory* — today the
    /// macOS `.dSYM` baked at store time (kunobi-ninja/kache#319). The store
    /// holds flat files only (single-component artifact names, file-level
    /// hashing/linking), so the bundle is tarred into one flat file at store
    /// time and unpacked next to the binary by
    /// [`PostRestoreAction::UnpackDebugBundle`] on restore.
    DebugBundle,
    /// Compiler-specific output that doesn't fit the categories above.
    /// Defaults to immutable handling.
    Other(&'static str),
}

impl ArtifactKind {
    /// Link strategy for restoring this kind. Mutable artifacts (executables,
    /// dynamic libraries) must end up as independent files on filesystems
    /// without CoW reflink, so post-build mutations don't propagate into the
    /// cache blob. Immutable kinds may share an inode (hardlink fallback).
    pub fn link_strategy(self) -> LinkStrategy {
        match self {
            ArtifactKind::Executable | ArtifactKind::DynamicLibrary | ArtifactKind::WasmModule => {
                LinkStrategy::Copy
            }
            _ => LinkStrategy::Hardlink,
        }
    }
}

/// One compiler output artifact.
///
/// `store_name` is the stable filename used inside a cache entry. It is
/// usually the basename of `path`, but it is explicit so adapters can
/// later represent directory/discovered outputs without making the store
/// infer names from paths.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Artifact {
    pub path: PathBuf,
    pub store_name: String,
    pub kind: ArtifactKind,
    pub required: bool,
}

/// Full output set produced by one compiler invocation.
///
/// Today the store still persists files as `(source_path, store_name)`
/// pairs. Keeping the richer artifact set at the compiler boundary lets
/// C/C++ and Rust grow side-output modeling without changing the cache
/// format in the same PR.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ArtifactSet {
    outputs: Vec<Artifact>,
}

impl ArtifactSet {
    pub fn new(outputs: Vec<Artifact>) -> Self {
        Self { outputs }
    }

    pub fn empty() -> Self {
        Self::default()
    }

    pub fn from_output_files(
        output_files: Vec<(PathBuf, String)>,
        classify: impl Fn(&str) -> ArtifactKind,
    ) -> Self {
        Self::new(
            output_files
                .into_iter()
                .map(|(path, store_name)| {
                    let kind = classify(&store_name);
                    Artifact {
                        path,
                        store_name,
                        kind,
                        required: true,
                    }
                })
                .collect(),
        )
    }

    pub fn is_empty(&self) -> bool {
        self.outputs.is_empty()
    }

    /// Append one artifact kache produced itself (not a compiler output) —
    /// today the store-time debug bundle tar (kunobi-ninja/kache#319). The
    /// caller owns keeping `path` alive until the store put has hashed it.
    pub fn push(&mut self, artifact: Artifact) {
        self.outputs.push(artifact);
    }

    pub fn outputs(&self) -> &[Artifact] {
        &self.outputs
    }

    pub fn total_size(&self) -> u64 {
        self.outputs
            .iter()
            .map(|artifact| {
                std::fs::metadata(&artifact.path)
                    .map(|m| m.len())
                    .unwrap_or(0)
            })
            .sum()
    }
}

/// Best-guess classification from filename alone, no compile-context.
///
/// Used by callers that scan a directory of artifacts (e.g. analyzing
/// `target/` from the CLI) where there's no parsed [`Compiler::Parsed`]
/// to disambiguate. Extensionless files return
/// [`ArtifactKind::Other`]`("extensionless")` — callers in target-scan
/// contexts should treat that as `Executable` (the rustc convention for
/// bin output on Unix); callers without that context should fall back
/// to the safe default (immutable, no post-processing).
///
/// This is the single source of truth for "filename → artifact kind"
/// across kache: [`Compiler::classify_output`] implementations delegate
/// to it for the known-extension cases. Adding a new artifact extension
/// happens here, not at every call site that does suffix matching.
pub fn classify_by_filename(name: &str) -> ArtifactKind {
    // kache-produced debug-bundle tar (`<bin>.dsym.tar`, see #319). Checked
    // before the extension match because `Path::extension` sees only "tar",
    // which would land in `Other("unknown-ext")` — and restore dispatches the
    // unpack action off this classification.
    if name.ends_with(".dsym.tar") {
        return ArtifactKind::DebugBundle;
    }
    let ext = std::path::Path::new(name)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");
    match ext {
        "rlib" => ArtifactKind::Library,
        "rmeta" => ArtifactKind::Metadata,
        "d" | "pp" => ArtifactKind::DepInfo,
        // Covers `.o` and compound `.rcgu.o` (Path::extension takes the
        // shortest tail, which is "o" for both).
        "o" | "obj" => ArtifactKind::Object,
        "dylib" | "so" | "dll" => ArtifactKind::DynamicLibrary,
        "wasm" => ArtifactKind::WasmModule,
        "dwo" | "pdb" | "dSYM" => ArtifactKind::DebugSidecar,
        "exe" => ArtifactKind::Executable,
        "" => ArtifactKind::Other("extensionless"),
        _ => ArtifactKind::Other("unknown-ext"),
    }
}

/// Canonical rustc `--emit` kind that a stored output filename satisfies, or
/// `None` if the file is not a recognized emit product (e.g. a `.dSYM` / `.pdb`
/// debug sidecar that no `--emit` kind requests directly).
///
/// This is the "filename → emit kind" sibling of [`classify_by_filename`] and
/// the single source of truth for the emit-coverage gate (kunobi-ninja/kache#325):
/// the store records the set of kinds an entry actually contains, and lookup
/// refuses an entry that doesn't cover what the invocation's `--emit` requested.
///
/// The returned strings match rustc's own `--emit` tokens (and the `emit` field
/// of its `artifact` JSON notifications), so they compare directly against
/// [`crate::args::RustcArgs::emit`]. A lib `--emit=link` legitimately also emits
/// `.rmeta`, so `metadata` may appear in an entry's covered set without having
/// been requested — the gate is superset-tolerant, so that is fine.
/// The canonical rustc `--emit` kinds the coverage gate reasons about — exactly
/// the values [`emit_kind_for_filename`] can return (kunobi-ninja/kache#325). A
/// requested kind outside this set is ignored by the gate so it never refuses on
/// a kind kache can't map to a stored file.
pub use kache_format::GATED_EMIT_KINDS;

pub fn emit_kind_for_filename(name: &str) -> Option<&'static str> {
    let ext = std::path::Path::new(name)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");
    match ext {
        // Linked output: rlib / staticlib / dylib / cdylib / bin / proc-macro.
        // Linked output, plus `wasm` — a wasm32 target's `bin`/`cdylib`
        // link product (kunobi-ninja/kache#431). Without `wasm` here the
        // coverage gate saw an entry as not covering the `--emit=link` it
        // was built for, so every wasm module refused to store: on the
        // substrate bench that silently blocked the runtime crates, the
        // most expensive compiles in the build.
        "rlib" | "so" | "dylib" | "dll" | "exe" | "a" | "lib" | "wasm" => Some("link"),
        "rmeta" => Some("metadata"),
        "o" | "obj" => Some("obj"),
        "d" | "pp" => Some("dep-info"),
        "s" | "asm" => Some("asm"),
        "ll" => Some("llvm-ir"),
        "bc" => Some("llvm-bc"),
        "mir" => Some("mir"),
        // Extensionless file = bin executable (rustc's Unix convention).
        "" => Some("link"),
        _ => None,
    }
}

/// Why a signature is being applied. Today the only purpose is
/// [`SigningPurpose::OsLoading`], but `Sign(SigningPurpose)` is structured
/// this way so future cases (distribution signing, supply-chain attestation)
/// add a new variant rather than a new action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SigningPurpose {
    /// Re-establish a signature so the OS will load this artifact.
    /// macOS arm64 → ad-hoc codesign. Linux / Windows → no-op today.
    OsLoading,
}

/// One thing that needs to happen to a restored artifact before it's
/// ready for use. The wrapper composes a per-file plan via
/// [`plan_post_restore`].
///
/// An action is one of two kinds, distinguished by
/// [`PostRestoreAction::is_content_transform`]:
///   - a **content transform** — kache computes the new bytes itself
///     ([`PostRestoreAction::transform`]); applied in memory against the
///     store blob *before* the file is materialized, so the restored
///     file is written once already in final form.
///   - an **external mutation** — an OS tool rewrites the file in place
///     ([`PostRestoreAction::apply`]); run after the file is
///     materialized as a private, writable copy the tool can safely mutate.
///
/// Adding a new action variant means: classify it in
/// `is_content_transform`, one arm in `transform` or `apply`, one
/// condition in [`plan_post_restore`]. The wrapper restore loop does not
/// change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PostRestoreAction {
    /// Rewrite absolute paths inside a `.d` (dep-info) file so cargo's
    /// freshness stat()s find them in the current worktree's `target/`.
    ExpandDepInfoPaths,

    /// Apply a signature for the given purpose. Cross-platform — no-op on
    /// platforms that don't require it.
    Sign(SigningPurpose),

    /// Unpack a kache-produced debug-bundle tar ([`ArtifactKind::DebugBundle`])
    /// into a sibling bundle directory: `foo.dsym.tar` → `foo.dSYM` next to it,
    /// so lldb finds a UUID-matched `.dSYM` adjacent to the restored binary and
    /// the binary's stale `N_OSO` debug-map records become inert
    /// (kunobi-ninja/kache#319). The tar file itself stays materialized — it IS
    /// the cached artifact (a hardlinked store blob), and deleting it would
    /// break the blob accounting every other restored artifact follows.
    UnpackDebugBundle,
}

/// Compose the post-restore action sequence for an artifact, given its
/// kind. Pure function — testable per kind without filesystem.
///
/// Today the plan only depends on `kind`. When `Platform` lands as a
/// first-class abstraction, this signature gains `&platform` and signing
/// becomes conditional on the platform actually requiring it.
pub fn plan_post_restore(kind: ArtifactKind) -> Vec<PostRestoreAction> {
    let mut plan = Vec::new();
    if matches!(kind, ArtifactKind::DepInfo) {
        plan.push(PostRestoreAction::ExpandDepInfoPaths);
    }
    if matches!(
        kind,
        ArtifactKind::Executable | ArtifactKind::DynamicLibrary
    ) {
        plan.push(PostRestoreAction::Sign(SigningPurpose::OsLoading));
    }
    if matches!(kind, ArtifactKind::DebugBundle) {
        plan.push(PostRestoreAction::UnpackDebugBundle);
    }
    plan
}

impl PostRestoreAction {
    /// True if this action rewrites the artifact's *content*, with kache
    /// computing the new bytes itself (dep-info path expansion).
    ///
    /// Content transforms are applied **in memory against the store
    /// blob, before the file is materialized** ([`Self::transform`]) —
    /// the restore loop writes the result as a fresh file rather than
    /// linking the blob and patching it in place, which would fail on a
    /// read-only or inode-shared restore.
    ///
    /// False for actions that hand the file to an external OS tool
    /// (codesign), which needs a real, writable, private file on disk;
    /// those run via [`Self::apply`] after materialization.
    pub fn is_content_transform(self) -> bool {
        match self {
            PostRestoreAction::ExpandDepInfoPaths => true,
            // Unpacking creates *sibling* files on disk from an
            // already-materialized tar — it does not rewrite the tar's own
            // bytes, so it must run after materialization, not before.
            PostRestoreAction::Sign(_) => false,
            PostRestoreAction::UnpackDebugBundle => false,
        }
    }

    /// Apply this action as an in-memory content transform: store-blob
    /// bytes in, final restored bytes out.
    ///
    /// `anchor` is the directory dep-info (`.d`) relative paths expand
    /// against — cargo's target dir for *this* invocation (see
    /// [`crate::args::RustcArgs::target_dir`]). It MUST be the same kind
    /// of anchor the store side relativized with, or the
    /// relativize→expand round trip produces paths cargo's freshness
    /// `stat()`s cannot find.
    ///
    /// Only meaningful when [`Self::is_content_transform`] is true;
    /// other actions return the input unchanged.
    pub fn transform(self, content: Vec<u8>, anchor: &std::path::Path) -> Vec<u8> {
        match self {
            PostRestoreAction::ExpandDepInfoPaths => {
                // dep-info is UTF-8 text. If a `.d` somehow is not valid
                // UTF-8, pass it through untouched rather than risk
                // corrupting it.
                match String::from_utf8(content) {
                    Ok(text) => crate::link::rewrite_depinfo_content(
                        &text,
                        anchor,
                        crate::link::DepInfoMode::Expand,
                    )
                    .into_bytes(),
                    Err(e) => e.into_bytes(),
                }
            }
            PostRestoreAction::Sign(_) => content,
            PostRestoreAction::UnpackDebugBundle => content,
        }
    }

    /// Execute this action as an external mutation of an
    /// already-materialized file.
    ///
    /// The caller guarantees `path` is a **private, writable** file —
    /// not a shared link to a store blob — because external tools mutate
    /// the file in place and must never reach the cache blob. Only
    /// meaningful when [`Self::is_content_transform`] is false.
    ///
    /// `platform` is the host abstraction for OS-specific concerns
    /// (codesigning today; debug-path rewriting later). Passing it
    /// explicitly — rather than calling `platform::current()` here —
    /// keeps tests deterministic: a unit test can inject a counting /
    /// failing / no-op platform.
    pub fn apply(&self, path: &std::path::Path, platform: &dyn Platform) -> Result<()> {
        match self {
            PostRestoreAction::Sign(SigningPurpose::OsLoading) => {
                // Verify-then-sign lives inside the platform impl so
                // the kache-fork bug 59866c0 (mutating already-valid
                // signatures) can't be reintroduced from this site.
                platform.ensure_binary_loadable(path)
            }
            PostRestoreAction::UnpackDebugBundle => unpack_debug_bundle(path),
            PostRestoreAction::ExpandDepInfoPaths => {
                // A content transform — handled in memory via
                // `transform()` before materialization, never here.
                debug_assert!(
                    false,
                    "ExpandDepInfoPaths is a content transform; route it through transform()"
                );
                Ok(())
            }
        }
    }
}

/// Cap on total bytes written while unpacking one debug bundle. A `.dSYM`
/// is at most a few hundred MB even for very large binaries; anything past
/// 2 GiB is a corrupt or hostile archive, not debug info
/// (kunobi-ninja/kache#319; mirrors `remote_layout`'s extraction cap, #212).
const MAX_DEBUG_BUNDLE_BYTES: u64 = 2_147_483_648; // 2 GiB

/// Unpack a restored `<name>.dsym.tar` into a sibling `<name>.dSYM` bundle
/// directory (kunobi-ninja/kache#319).
///
/// The tar was produced by kache itself at store time
/// ([`Platform::package_debug_bundle`]) with entries relative to the bundle
/// root (`Contents/...`), but for a shared or MITM'd remote bucket the bytes
/// are attacker-influenced, so extraction is hardened like
/// `remote_layout::extract_entry_pack` (#211/#212): reject absolute/rooted
/// paths, `..` components, and links; cap total declared bytes. Extraction
/// goes to a private temp dir sibling first, then renames over the bundle
/// path, so a failed unpack never leaves a half-written `.dSYM` that lldb
/// would trust.
///
/// Errors propagate: the wrapper's restore loop treats any restore failure
/// as a clean miss and recompiles, which is exactly the right response to a
/// tampered or corrupt entry.
fn unpack_debug_bundle(tar_path: &std::path::Path) -> Result<()> {
    unpack_debug_bundle_with_cap(tar_path, MAX_DEBUG_BUNDLE_BYTES)
}

/// [`unpack_debug_bundle`] with an explicit byte cap, so the bomb guard is
/// testable without materializing a multi-GiB archive.
fn unpack_debug_bundle_with_cap(tar_path: &std::path::Path, max_bytes: u64) -> Result<()> {
    use anyhow::Context as _;

    let file_name = tar_path
        .file_name()
        .and_then(|n| n.to_str())
        .with_context(|| {
            format!(
                "debug bundle has no usable file name: {}",
                tar_path.display()
            )
        })?;
    let stem = file_name
        .strip_suffix(".dsym.tar")
        .with_context(|| format!("debug bundle artifact is not a `.dsym.tar`: {}", file_name))?;
    let parent = tar_path
        .parent()
        .with_context(|| format!("debug bundle has no parent dir: {}", tar_path.display()))?;
    let bundle_dir = parent.join(format!("{stem}.dSYM"));

    let tmp_dir = tempfile::Builder::new()
        .prefix(".kache-dsym-")
        .tempdir_in(parent)
        .context("creating temp dir for debug bundle unpack")?;

    let file = std::fs::File::open(tar_path)
        .with_context(|| format!("opening debug bundle {}", tar_path.display()))?;
    let mut archive = tar::Archive::new(file);
    let mut total_bytes = 0u64;
    for entry in archive.entries().context("reading debug bundle tar")? {
        let mut entry = entry.context("reading debug bundle tar entry")?;
        // Bomb guard: the declared entry sizes upper-bound what the tar
        // framing will ever yield, so reject before writing anything.
        total_bytes = total_bytes.saturating_add(entry.size());
        if total_bytes > max_bytes {
            anyhow::bail!(
                "debug bundle exceeds the {max_bytes}-byte extraction cap \
                 (corrupt or hostile archive)"
            );
        }
        let path = entry
            .path()
            .context("debug bundle entry path")?
            .to_path_buf();
        // A single portable check: on Unix an absolute path IS a leading
        // RootDir, and on Windows the Prefix arm also catches drive-relative
        // shapes (`C:x`) that `is_absolute()` misses — so the component test
        // subsumes `is_absolute()` on every platform.
        if matches!(
            path.components().next(),
            Some(std::path::Component::RootDir | std::path::Component::Prefix(_))
        ) {
            anyhow::bail!("debug bundle entry has absolute path: {}", path.display());
        }
        if path
            .components()
            .any(|c| c == std::path::Component::ParentDir)
        {
            anyhow::bail!("debug bundle entry has path traversal: {}", path.display());
        }
        let entry_type = entry.header().entry_type();
        if entry_type.is_symlink() || entry_type.is_hard_link() {
            anyhow::bail!(
                "debug bundle entry is a link (rejected): {}",
                path.display()
            );
        }

        let dest = tmp_dir.path().join(&path);
        if entry_type.is_dir() {
            std::fs::create_dir_all(&dest)
                .with_context(|| format!("creating {}", dest.display()))?;
            continue;
        }
        if let Some(dir) = dest.parent() {
            std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
        }
        entry
            .unpack(&dest)
            .with_context(|| format!("unpacking debug bundle entry {}", path.display()))?;
    }

    // Replace any stale bundle atomically-ish: remove, then rename the fully
    // unpacked temp dir into place. A stale `.dSYM` from an earlier build at
    // this path would otherwise shadow the restored one for lldb.
    if bundle_dir.symlink_metadata().is_ok() {
        if bundle_dir.is_dir() {
            std::fs::remove_dir_all(&bundle_dir)
                .with_context(|| format!("removing stale bundle {}", bundle_dir.display()))?;
        } else {
            std::fs::remove_file(&bundle_dir)
                .with_context(|| format!("removing stale bundle {}", bundle_dir.display()))?;
        }
    }
    let tmp_path = tmp_dir.keep();
    std::fs::rename(&tmp_path, &bundle_dir).with_context(|| {
        format!(
            "publishing debug bundle {} -> {}",
            tmp_path.display(),
            bundle_dir.display()
        )
    })?;
    Ok(())
}

/// A cacheable compiler.
///
/// Implementations are state-light. Each owns its native parsed
/// representation as `Self::Parsed` so we don't flatten compiler-specific
/// shapes into one generic struct.
pub trait Compiler {
    type Parsed;

    fn id(&self) -> CompilerId;

    /// Parse raw argv into the compiler's native representation.
    /// Caller has already established this is the right compiler adapter via
    /// [`detect_compiler`].
    fn parse(&self, args: &[String]) -> Result<Self::Parsed>;

    /// Reasons (if any) this invocation must bypass the cache.
    /// Empty Vec = cacheable.
    fn refuse_reasons(&self, parsed: &Self::Parsed) -> Vec<RefuseReason>;

    /// Compute the cache key for a parsed invocation.
    fn cache_key(&self, parsed: &Self::Parsed, ctx: &KeyCtx<'_, '_>) -> Result<String>;

    /// Execute the compilation, capturing exit code, stdout, stderr, and
    /// the list of output files produced.
    fn execute(&self, parsed: &Self::Parsed) -> Result<CompileResult>;

    /// Classify an output file by its filename, given the parsed invocation
    /// for context (e.g. crate type to disambiguate executables from
    /// libraries when both share a no-extension shape).
    ///
    /// `name` is the filename only — no path components. Returns
    /// [`ArtifactKind::Other`] when the file doesn't match any known pattern;
    /// callers default to immutable / no-post-processing behavior in that
    /// case.
    fn classify_output(&self, parsed: &Self::Parsed, name: &str) -> ArtifactKind;
}

/// Adapter descriptors currently supported by kache.
///
/// Registration is deliberately concrete and local: adding an adapter means
/// adding its module-owned descriptor here, with no broad enum of possible
/// future tool kinds.
pub const COMPILER_ADAPTERS: &[CompilerAdapter] = &[rustc::ADAPTER, cc::ADAPTER];

/// Detect which compiler adapter an argv vector is invoking.
///
/// Each compiler impl owns its own `recognizes` rule; this function just walks
/// the descriptor list.
///
/// Returns `None` if no supported compiler matches — caller should
/// fall through to direct execution (or to compiler-family probe
/// handling via [`cc::CcCompiler::recognizes_family_probe`], which is its own
/// concern, not an adapter).
pub fn detect_compiler(args: &[String]) -> Option<&'static CompilerAdapter> {
    COMPILER_ADAPTERS
        .iter()
        .find(|adapter| adapter.recognizes(args))
}

/// Detect a `RUSTC_WRAPPER` + `RUSTC_WORKSPACE_WRAPPER` chain with an
/// unrecognized workspace wrapper. Cargo passes `<wrapper> rustc <args>`;
/// the wrapper may be an absolute path or a bare name resolved via PATH.
/// We match the inner rustc, not the wrapper name.
#[cfg(unix)]
fn is_executable(path: &std::path::Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path)
        .map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
        .unwrap_or(false)
}

#[cfg(not(unix))]
fn is_executable(path: &std::path::Path) -> bool {
    path.is_file()
}

pub(crate) fn is_kache_subcommand_or_flag(s: &str) -> bool {
    if s.starts_with('-') {
        return true;
    }
    use clap::CommandFactory;
    let mut cmd = crate::Cli::command();
    cmd.build();
    cmd.find_subcommand(s).is_some()
}

/// Do these compiler args (argv after the program) form a pure version/info
/// query rather than a compile? Cargo probes a toolchain this way — most
/// notably Kani's `kani-compiler -vV` (kunobi-ninja/kache#656). Such an
/// invocation compiles nothing, so there is nothing to cache; running an
/// *unknown* program just to sniff its `-E` family would add a spurious
/// invocation to a pure passthrough. Detection callers skip the probe for it.
///
/// Requires *every* arg to be a query flag (and at least one): a real compile
/// may carry a `-V`/`--version`-shaped **value** (e.g. an output file named
/// `-V`, `-o -V`, or `-MF --version`), which must still be recognized and
/// probed — matching any single arg would wrongly treat those as queries and
/// pass a cacheable compile through untouched. An empty arg list is a bare
/// invocation, not a query, so unknown compilers still probe.
pub(crate) fn is_version_or_info_query(args: &[String]) -> bool {
    !args.is_empty()
        && args.iter().all(|a| {
            matches!(
                a.as_str(),
                "-vV"
                    | "-V"
                    | "--version"
                    | "-dumpversion"
                    | "-dumpfullversion"
                    | "-dumpmachine"
                    | "-print-search-dirs"
                    | "--print-search-dirs"
            )
        })
}

pub(crate) fn resolve_program_on_path(program: &str) -> Option<std::path::PathBuf> {
    let path = std::env::var_os("PATH");
    let pathext = std::env::var_os("PATHEXT");
    resolve_program_on_path_with(program, path.as_deref(), pathext.as_deref())
}

fn resolve_program_on_path_with(
    program: &str,
    path: Option<&std::ffi::OsStr>,
    pathext: Option<&std::ffi::OsStr>,
) -> Option<std::path::PathBuf> {
    if program.contains('/') || program.contains('\\') {
        return Some(std::path::PathBuf::from(program));
    }
    let dirs: Vec<std::path::PathBuf> = std::env::split_paths(path?).collect();

    let extensions: Vec<String> = if cfg!(windows) {
        if let Some(pathext) = pathext {
            std::env::split_paths(pathext)
                .filter_map(|p| p.to_str().map(|s| s.to_string()))
                .collect()
        } else {
            vec![
                ".exe".to_string(),
                ".bat".to_string(),
                ".cmd".to_string(),
                ".com".to_string(),
            ]
        }
    } else {
        vec!["".to_string()]
    };

    for dir in dirs {
        let p = dir.join(program);
        if is_executable(&p) {
            return Some(p);
        }
        for ext in &extensions {
            if ext.is_empty() {
                continue;
            }
            let mut suffixed = p.clone().into_os_string();
            suffixed.push(ext);
            let suffixed_path = std::path::PathBuf::from(suffixed);
            if is_executable(&suffixed_path) {
                return Some(suffixed_path);
            }
        }
    }
    None
}

fn is_program_on_path(program: &str) -> bool {
    resolve_program_on_path(program).is_some()
}

/// Detect a real compiler invocation that must run uncached.
///
/// Cargo preserves `RUSTC` when it invokes `RUSTC_WRAPPER`, which identifies
/// custom drivers such as Kani's `kani-compiler` without maintaining a list of
/// tool names. `nvcc` remains an explicit passthrough because Kache supports it
/// as a compiler launcher but cannot safely cache its multi-phase outputs.
pub(crate) fn is_passthrough_compiler_invocation(args: &[String]) -> bool {
    let rustc = std::env::var_os("RUSTC");
    is_passthrough_compiler_invocation_with(args, rustc.as_deref())
}

pub(crate) fn is_passthrough_compiler_invocation_with(
    args: &[String],
    configured_rustc: Option<&std::ffi::OsStr>,
) -> bool {
    let Some(program) = args.first() else {
        return false;
    };
    if is_kache_subcommand_or_flag(program) {
        return false;
    }
    let is_configured_rustc =
        configured_rustc.is_some_and(|rustc| rustc == std::ffi::OsStr::new(program.as_str()));
    let is_nvcc = command_basename(program)
        .map(strip_windows_exe_suffix)
        .is_some_and(|name| name.eq_ignore_ascii_case("nvcc"));
    is_configured_rustc || is_nvcc
}

pub fn is_workspace_wrapper_chain(args: &[String]) -> bool {
    let workspace_wrapper = std::env::var_os("RUSTC_WORKSPACE_WRAPPER");
    is_workspace_wrapper_chain_with(args, workspace_wrapper.as_deref(), is_program_on_path)
}

fn is_workspace_wrapper_chain_with(
    args: &[String],
    workspace_wrapper: Option<&std::ffi::OsStr>,
    program_on_path: impl FnOnce(&str) -> bool,
) -> bool {
    if args.len() < 2 || !rustc::RustcCompiler::recognizes(&args[1..]) {
        return false;
    }
    if args[0].contains('/') || args[0].contains('\\') {
        return true;
    }
    if workspace_wrapper.is_some_and(|wrapper| wrapper == std::ffi::OsStr::new(&args[0])) {
        return true;
    }
    !is_kache_subcommand_or_flag(&args[0]) && program_on_path(&args[0])
}

/// Extract the bare command name from an `argv[0]`, splitting on both Unix
/// (`/`) and Windows (`\`) separators regardless of host OS.
///
/// [`std::path::Path::file_name`] is deliberately avoided: off-Windows it does
/// not treat `\` as a separator, so a Windows path like
/// `G:\…\bin\clippy-driver.exe` would come back whole. Every compiler adapter's
/// `recognizes` rule must see the same basename whether it runs on the target
/// platform or in a cross-platform test, so detection of e.g. `clippy-driver`
/// holds for both. Returns `None` when the trailing component is empty.
pub(crate) fn command_basename(arg0: &str) -> Option<&str> {
    arg0.rsplit(['/', '\\'])
        .next()
        .filter(|name| !name.is_empty())
}

/// Strip a trailing, case-insensitive `.exe` suffix (Windows executables) so
/// `rustc.exe` / `clippy-driver.exe` compare equal to their bare names.
pub(crate) fn strip_windows_exe_suffix(name: &str) -> &str {
    let bytes = name.as_bytes();
    if bytes.len() >= 4 && bytes[bytes.len() - 4..].eq_ignore_ascii_case(b".exe") {
        &name[..bytes.len() - 4]
    } else {
        name
    }
}

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

    #[test]
    fn version_or_info_query_needs_every_arg_to_be_a_query_flag() {
        let q = |a: &[&str]| {
            is_version_or_info_query(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>())
        };
        // Pure queries.
        assert!(q(&["-vV"]));
        assert!(q(&["--version"]));
        assert!(q(&["-dumpmachine"]));
        // A compile that merely carries a query-shaped *value* is NOT a query:
        // matching any single arg would wrongly skip recognition/probing and
        // pass a cacheable compile through untouched.
        assert!(!q(&["-c", "hello.c", "-o", "-V"]));
        assert!(!q(&["-MF", "--version"]));
        assert!(!q(&["-vV", "hello.c"]));
        // A bare invocation (no args) is not a query — unknown compilers must
        // still be probed (kunobi-ninja/kache#538).
        assert!(!q(&[]));
    }

    #[test]
    fn test_is_kache_subcommand_or_flag() {
        assert!(is_kache_subcommand_or_flag("help"));
        assert!(is_kache_subcommand_or_flag("-h"));
        assert!(is_kache_subcommand_or_flag("--help"));
        assert!(is_kache_subcommand_or_flag("-V"));
        assert!(is_kache_subcommand_or_flag("--version"));
        assert!(is_kache_subcommand_or_flag("gc"));
        assert!(is_kache_subcommand_or_flag("list"));
        assert!(!is_kache_subcommand_or_flag("not-a-subcommand"));
    }

    fn s(args: &[&str]) -> Vec<String> {
        args.iter().map(|a| a.to_string()).collect()
    }

    #[test]
    fn detect_compiler_returns_none_for_empty_argv() {
        assert!(detect_compiler(&[]).is_none());
    }

    #[test]
    fn detect_compiler_recognizes_rustc_paths() {
        assert_eq!(
            detect_compiler(&s(&["rustc"])).map(|adapter| adapter.id()),
            Some(rustc::RUSTC_ID)
        );
        assert_eq!(
            detect_compiler(&s(&["/usr/bin/rustc", "src/lib.rs"])).map(|adapter| adapter.id()),
            Some(rustc::RUSTC_ID)
        );
        assert_eq!(
            detect_compiler(&s(&["clippy-driver"])).map(|adapter| adapter.id()),
            Some(rustc::RUSTC_ID)
        );
        // Regression for issue #287: the exact argv cargo passes for
        // `cargo clippy` on Windows. Detection must route this to the rustc
        // adapter (wrapper mode) rather than fall through to clap subcommand
        // parsing, which is what surfaced as "unrecognized subcommand".
        assert_eq!(
            detect_compiler(&s(&[
                r"G:\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\bin\clippy-driver.exe",
                "rustc",
                "-vV",
            ]))
            .map(|adapter| adapter.id()),
            Some(rustc::RUSTC_ID)
        );
    }

    #[test]
    fn detect_compiler_recognizes_cc_paths() {
        assert_eq!(
            detect_compiler(&s(&["cc"])).map(|adapter| adapter.id()),
            Some(cc::CC_ID)
        );
        assert_eq!(
            detect_compiler(&s(&["gcc"])).map(|adapter| adapter.id()),
            Some(cc::CC_ID)
        );
        assert_eq!(
            detect_compiler(&s(&["clang++"])).map(|adapter| adapter.id()),
            Some(cc::CC_ID)
        );
        assert_eq!(
            detect_compiler(&s(&["/usr/bin/cc", "-c", "foo.c"])).map(|adapter| adapter.id()),
            Some(cc::CC_ID)
        );
        // Regression for issue #514: target-prefixed cross compilers must enter
        // wrapper mode instead of falling through to clap as unknown commands.
        assert_eq!(
            detect_compiler(&s(&[
                "/opt/cross/bin/arm-linux-gnueabihf-gcc",
                "-c",
                "foo.c",
            ]))
            .map(|adapter| adapter.id()),
            Some(cc::CC_ID)
        );
        assert!(detect_compiler(&s(&["arm-linux-gnueabihf-gcc-ar"])).is_none());
    }

    #[test]
    fn detect_compiler_returns_none_for_cc_probe_shape() {
        // The cc-crate compiler-family probe (`kache -E <file>`) is
        // intentionally NOT a compiler adapter — it's a non-compiler
        // invocation pattern handled separately in run_wrapper_mode
        // via `CcCompiler::recognizes_family_probe`. Asserting None
        // here pins that boundary: detect_compiler must not grow into
        // a grab-bag of "anything kache should passthrough".
        assert!(detect_compiler(&s(&["-E", "/tmp/probe.c"])).is_none());
        assert!(detect_compiler(&s(&["-E", "/tmp/detect_compiler_family.c"])).is_none());
    }

    #[test]
    fn detect_compiler_returns_none_for_unrelated_argv() {
        assert!(detect_compiler(&s(&["cargo", "build"])).is_none());
        assert!(detect_compiler(&s(&["make"])).is_none());
        assert!(detect_compiler(&s(&["ld"])).is_none());
        assert!(detect_compiler(&s(&["--crate-name"])).is_none());
    }

    #[test]
    fn workspace_wrapper_chain_detects_unrecognized_drivers() {
        // Issue #505: dylint-driver and any future RUSTC_WORKSPACE_WRAPPER
        // tool. Cargo passes `kache <wrapper-path> rustc <args>`.
        assert!(is_workspace_wrapper_chain(&s(&[
            "/Users/dev/.dylint_drivers/nightly/dylint-driver",
            "rustc",
            "--crate-name",
        ])));
        // Windows backslash path (host-OS-independent).
        assert!(is_workspace_wrapper_chain(&s(&[
            r"C:\tools\custom-driver.exe",
            "rustc",
        ])));
    }

    #[test]
    fn workspace_wrapper_chain_detects_bare_name_via_env() {
        // Cargo may pass a bare wrapper name (resolved via PATH) when
        // RUSTC_WORKSPACE_WRAPPER is set without a path separator.
        let args = s(&["mydriver", "rustc"]);
        assert!(is_workspace_wrapper_chain_with(
            &args,
            Some(std::ffi::OsStr::new("mydriver")),
            |_| false,
        ));
        assert!(!is_workspace_wrapper_chain_with(
            &args,
            Some(std::ffi::OsStr::new("other-driver")),
            |_| false,
        ));
    }

    #[test]
    fn workspace_wrapper_chain_detects_bare_name_via_path() {
        use std::fs::File;
        let temp_dir = tempfile::TempDir::new().unwrap();
        let wrapper_name = "custom-wrapper-test-executable";
        #[cfg(windows)]
        {
            let wrapper_path_exe = temp_dir.path().join(format!("{}.exe", wrapper_name));
            File::create(&wrapper_path_exe).unwrap();
        }
        #[cfg(not(windows))]
        {
            let wrapper_path = temp_dir.path().join(wrapper_name);
            File::create(&wrapper_path).unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mut perms = std::fs::metadata(&wrapper_path).unwrap().permissions();
                perms.set_mode(0o755);
                std::fs::set_permissions(&wrapper_path, perms).unwrap();
            }
        }

        let test_path = std::env::join_paths([temp_dir.path()]).unwrap();
        assert!(is_workspace_wrapper_chain_with(
            &s(&[wrapper_name, "rustc"]),
            None,
            |program| {
                resolve_program_on_path_with(program, Some(test_path.as_os_str()), None).is_some()
            },
        ));
    }

    #[test]
    fn workspace_wrapper_chain_rejects_non_paths() {
        // No path separator and not RUSTC_WORKSPACE_WRAPPER → CLI subcommand.
        for subcommand in ["init", "gc", "doctor", "config", "report"] {
            assert!(!is_workspace_wrapper_chain_with(
                &s(&[subcommand, "rustc"]),
                None,
                |_| true,
            ));
        }

        // Non-existent executable name
        assert!(!is_workspace_wrapper_chain_with(
            &s(&["nonexistentwrappername12345", "rustc"]),
            None,
            |_| false,
        ));

        // Inner arg not rustc.
        assert!(!is_workspace_wrapper_chain(&s(&["/usr/bin/cc", "file.c"])));
        assert!(!is_workspace_wrapper_chain(&s(&["cargo", "build"])));

        // Too few args.
        assert!(!is_workspace_wrapper_chain(&s(&["/usr/bin/rustc"])));
    }

    #[test]
    fn passthrough_compiler_accepts_configured_rustc_and_nvcc() {
        assert!(is_passthrough_compiler_invocation_with(
            &s(&["/home/user/.kani/kani-0.67.0/bin/kani-compiler", "-vV"]),
            Some(std::ffi::OsStr::new(
                "/home/user/.kani/kani-0.67.0/bin/kani-compiler",
            )),
        ));
        assert!(is_passthrough_compiler_invocation_with(
            &s(&["custom-rustc-driver", "--crate-name", "demo"]),
            Some(std::ffi::OsStr::new("custom-rustc-driver")),
        ));
        assert!(is_passthrough_compiler_invocation_with(
            &s(&[r"C:\CUDA\bin\nvcc.exe", "-c", "kernel.cu"]),
            None,
        ));
        assert!(is_passthrough_compiler_invocation_with(
            &s(&["nvcc", "-c", "kernel.cu"]),
            None,
        ));
    }

    #[test]
    fn passthrough_compiler_rejects_unrelated_programs() {
        // Exercise the environment-reading facade too. A Kache command must
        // never become a compiler invocation, even if RUSTC has the same name.
        assert!(!is_passthrough_compiler_invocation(&s(&["gc"])));
        assert!(!is_passthrough_compiler_invocation_with(&[], None));
        assert!(!is_passthrough_compiler_invocation_with(
            &s(&["stat"]),
            None,
        ));
        assert!(!is_passthrough_compiler_invocation_with(
            &s(&["/usr/bin/stat"]),
            Some(std::ffi::OsStr::new("/usr/bin/other-driver")),
        ));
        assert!(!is_passthrough_compiler_invocation_with(
            &s(&["gc"]),
            Some(std::ffi::OsStr::new("gc")),
        ));
    }

    #[test]
    fn command_basename_splits_both_separators() {
        assert_eq!(command_basename("rustc"), Some("rustc"));
        assert_eq!(command_basename("/usr/bin/rustc"), Some("rustc"));
        // Windows backslash paths resolve identically on every host OS —
        // std::path::Path::file_name would not split these off-Windows.
        assert_eq!(
            command_basename(r"G:\bin\clippy-driver.exe"),
            Some("clippy-driver.exe")
        );
        assert_eq!(command_basename(r"C:\a/b\c.exe"), Some("c.exe"));
        // A trailing separator leaves no command name.
        assert_eq!(command_basename("/usr/bin/"), None);
        assert_eq!(command_basename(r"C:\bin\"), None);
        assert_eq!(command_basename(""), None);
    }

    #[test]
    fn strip_windows_exe_suffix_is_case_insensitive_and_optional() {
        assert_eq!(strip_windows_exe_suffix("rustc.exe"), "rustc");
        assert_eq!(
            strip_windows_exe_suffix("clippy-driver.EXE"),
            "clippy-driver"
        );
        // No suffix: returned unchanged.
        assert_eq!(strip_windows_exe_suffix("rustc"), "rustc");
        // `.exe` is only stripped from the end, never mid-name.
        assert_eq!(strip_windows_exe_suffix("a.exe.b"), "a.exe.b");
        // Too short to carry a `.exe` suffix.
        assert_eq!(strip_windows_exe_suffix(".ex"), ".ex");
    }

    #[test]
    fn plan_post_restore_dep_info_expands_paths() {
        assert_eq!(
            plan_post_restore(ArtifactKind::DepInfo),
            vec![PostRestoreAction::ExpandDepInfoPaths]
        );
    }

    #[test]
    fn plan_post_restore_executable_signs_for_os_loading() {
        assert_eq!(
            plan_post_restore(ArtifactKind::Executable),
            vec![PostRestoreAction::Sign(SigningPurpose::OsLoading)]
        );
    }

    #[test]
    fn plan_post_restore_dynamic_library_signs_for_os_loading() {
        // Same plan as Executable: dylibs are loaded by the dynamic linker
        // and need an OS-acceptable signature on macOS arm64. Encoded as a
        // single condition in `plan_post_restore` so adding a third
        // OS-loaded kind requires changing one place.
        assert_eq!(
            plan_post_restore(ArtifactKind::DynamicLibrary),
            vec![PostRestoreAction::Sign(SigningPurpose::OsLoading)]
        );
    }

    #[test]
    fn plan_post_restore_object_is_empty() {
        // Regression guard: `.o` / `.rcgu.o` files must not pick up any
        // post-restore action — in particular not codesign (kache-fork
        // bug 572f321).
        assert!(plan_post_restore(ArtifactKind::Object).is_empty());
    }

    #[test]
    fn plan_post_restore_passive_kinds_are_empty() {
        // DebugBundle is deliberately NOT in this list: it is the one
        // non-executable kind with a post-restore action (the unpack,
        // see #319) — pinned separately below.
        for kind in [
            ArtifactKind::Library,
            ArtifactKind::Metadata,
            ArtifactKind::DebugSidecar,
            // A wasm module is never OS-loaded, so it must NOT pick up the
            // codesign action its Copy-strategy siblings get (#431).
            ArtifactKind::WasmModule,
            ArtifactKind::Other("test"),
        ] {
            assert!(
                plan_post_restore(kind).is_empty(),
                "{kind:?} should have no post-restore actions"
            );
        }
    }

    #[test]
    fn plan_post_restore_debug_bundle_unpacks_exactly() {
        // kunobi-ninja/kache#319: the bundle tar gets exactly the unpack —
        // in particular NOT codesign (it is not a loadable binary) and NOT
        // dep-info expansion.
        assert_eq!(
            plan_post_restore(ArtifactKind::DebugBundle),
            vec![PostRestoreAction::UnpackDebugBundle]
        );
    }

    // ── transform() / apply() ────────────────────────────────────
    //
    // Coverage for the action executors. ExpandDepInfoPaths is a content
    // transform: it maps store-blob bytes to final bytes in memory.
    // Sign(OsLoading) is an external mutation routed through the
    // injected Platform.

    #[test]
    fn expand_dep_info_paths_is_a_content_transform() {
        // The classification that routes an action to `transform` (in
        // memory, pre-materialization) vs `apply` (external, post-).
        assert!(PostRestoreAction::ExpandDepInfoPaths.is_content_transform());
        assert!(!PostRestoreAction::Sign(SigningPurpose::OsLoading).is_content_transform());
        // The unpack needs the tar materialized on disk first, so it is an
        // external (post-materialization) action, and its transform leg
        // passes the tar bytes through untouched.
        assert!(!PostRestoreAction::UnpackDebugBundle.is_content_transform());
        let bytes = b"tar bytes".to_vec();
        assert_eq!(
            PostRestoreAction::UnpackDebugBundle
                .transform(bytes.clone(), std::path::Path::new("/anchor")),
            bytes
        );
    }

    #[test]
    fn transform_expand_dep_info_paths_roots_relative_paths_at_anchor() {
        // The sentinel-path shape `rewrite_depinfo_content`'s Relativize
        // mode produces; Expand (the restore-side transform) reverses it.
        // The anchor is the restoring build's target dir — NOT the
        // process cwd.
        let blob = b"__kache_root__/target/debug/foo: __kache_root__/src/lib.rs".to_vec();
        let anchor = std::path::Path::new("/restored/worktree");

        let out = PostRestoreAction::ExpandDepInfoPaths.transform(blob, anchor);
        let content = String::from_utf8(out).unwrap();

        assert!(
            content.contains("/restored/worktree/target/debug/foo"),
            "expected anchor-rooted target path, got: {content}"
        );
        assert!(
            content.contains("/restored/worktree/src/lib.rs"),
            "expected anchor-rooted source path, got: {content}"
        );
        assert!(
            !content.contains("__kache_root__/"),
            "no kache dep-info markers should remain, got: {content}"
        );
    }

    #[test]
    fn transform_expand_dep_info_paths_preserves_parent_relative_deps() {
        let blob =
            b"foo.o: ../../src/foo.cc ../include/foo.h __kache_root__/generated/header.h".to_vec();
        let anchor = std::path::Path::new("/restored/worktree/obj");

        let out = PostRestoreAction::ExpandDepInfoPaths.transform(blob, anchor);
        let content = String::from_utf8(out).unwrap();

        assert!(
            content.contains("../../src/foo.cc"),
            "compiler-emitted parent-relative source paths must survive: {content}"
        );
        assert!(
            content.contains("../include/foo.h"),
            "compiler-emitted parent-relative header paths must survive: {content}"
        );
        assert!(
            content.contains("/restored/worktree/obj/generated/header.h"),
            "kache sentinel paths should still expand: {content}"
        );
    }

    #[test]
    fn transform_expand_dep_info_paths_passes_through_non_utf8() {
        // A `.d` is always UTF-8 in practice, but the transform must
        // never corrupt bytes it can't interpret — it returns them
        // unchanged rather than panicking.
        let blob = vec![0xff, 0xfe, 0x00, 0x42];
        let out = PostRestoreAction::ExpandDepInfoPaths
            .transform(blob.clone(), std::path::Path::new("/anchor"));
        assert_eq!(out, blob);
    }

    #[test]
    fn apply_sign_os_loading_routes_through_platform() {
        // The dispatch contract: Sign(OsLoading) must hand off to the
        // platform's ensure_binary_loadable, not re-implement codesign
        // logic in-line. CountingPlatform proves the call happened
        // exactly once per apply().
        use crate::compiler::platform::tests::CountingPlatform;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("not-actually-a-binary");
        std::fs::write(&path, b"definitely not Mach-O").unwrap();

        let platform = CountingPlatform::new();
        PostRestoreAction::Sign(SigningPurpose::OsLoading)
            .apply(&path, &platform)
            .expect("apply must not error even when the platform impl is a no-op");
        assert_eq!(
            platform.ensure_calls(),
            1,
            "Sign(OsLoading) must dispatch to platform.ensure_binary_loadable exactly once"
        );
    }

    // ── UnpackDebugBundle (kunobi-ninja/kache#319) ───────────────

    /// Build an in-memory tar with the given `(path, content)` regular-file
    /// entries — both well-formed bundles and malicious shapes for the
    /// hardening tests.
    fn synthetic_tar(entries: &[(&str, &[u8])]) -> Vec<u8> {
        let mut builder = tar::Builder::new(Vec::new());
        for (path, content) in entries {
            let mut header = tar::Header::new_gnu();
            header.set_size(content.len() as u64);
            header.set_mode(0o644);
            header.set_mtime(0);
            header.set_entry_type(tar::EntryType::Regular);
            builder
                .append_data(&mut header, path, &content[..])
                .unwrap();
        }
        builder.into_inner().unwrap()
    }

    #[test]
    fn apply_unpack_debug_bundle_creates_sibling_dsym_dir() {
        use crate::compiler::platform::tests::CountingPlatform;
        let dir = tempfile::tempdir().unwrap();
        let tar_path = dir.path().join("foo-abc123.dsym.tar");
        std::fs::write(
            &tar_path,
            synthetic_tar(&[
                ("Contents/Info.plist", b"plist"),
                ("Contents/Resources/DWARF/foo-abc123", b"dwarf bytes"),
            ]),
        )
        .unwrap();

        PostRestoreAction::UnpackDebugBundle
            .apply(&tar_path, &CountingPlatform::new())
            .unwrap();

        // `foo-abc123.dsym.tar` → sibling `foo-abc123.dSYM` bundle dir.
        let bundle = dir.path().join("foo-abc123.dSYM");
        assert_eq!(
            std::fs::read(bundle.join("Contents/Resources/DWARF/foo-abc123")).unwrap(),
            b"dwarf bytes"
        );
        assert_eq!(
            std::fs::read(bundle.join("Contents/Info.plist")).unwrap(),
            b"plist"
        );
        // The tar stays materialized: it IS the cached artifact (a
        // hardlinked store blob) and blob accounting expects it on disk.
        assert!(tar_path.is_file(), "the restored tar must not be deleted");
    }

    #[test]
    fn apply_unpack_debug_bundle_replaces_stale_bundle() {
        use crate::compiler::platform::tests::CountingPlatform;
        let dir = tempfile::tempdir().unwrap();
        let bundle = dir.path().join("foo.dSYM");
        std::fs::create_dir_all(bundle.join("Contents")).unwrap();
        std::fs::write(bundle.join("Contents/stale"), b"old").unwrap();

        let tar_path = dir.path().join("foo.dsym.tar");
        std::fs::write(
            &tar_path,
            synthetic_tar(&[("Contents/Resources/DWARF/foo", b"new dwarf")]),
        )
        .unwrap();

        PostRestoreAction::UnpackDebugBundle
            .apply(&tar_path, &CountingPlatform::new())
            .unwrap();

        assert!(
            !bundle.join("Contents/stale").exists(),
            "a stale bundle must be replaced wholesale, not merged — lldb \
             would otherwise trust leftover files from another build"
        );
        assert_eq!(
            std::fs::read(bundle.join("Contents/Resources/DWARF/foo")).unwrap(),
            b"new dwarf"
        );
    }

    /// A tar whose single entry carries a raw (hostile) name that
    /// `tar::Builder` itself refuses to write — forged by patching the
    /// header's name field and re-checksumming, exactly what an attacker
    /// controlling a shared bucket would serve.
    fn forged_tar_with_entry_name(name: &[u8]) -> Vec<u8> {
        let mut header = tar::Header::new_gnu();
        header.set_size(5);
        header.set_mode(0o644);
        header.set_entry_type(tar::EntryType::Regular);
        let mut builder = tar::Builder::new(Vec::new());
        builder
            .append_data(&mut header, "placeholder", &b"pwned"[..])
            .unwrap();
        let mut bytes = builder.into_inner().unwrap();
        assert!(name.len() < 100, "GNU tar name field is 100 bytes");
        bytes[..name.len()].copy_from_slice(name);
        bytes[name.len()..100].fill(0);
        // Recompute the header checksum the tar reader validates.
        let mut patched = tar::Header::new_gnu();
        patched.as_mut_bytes().copy_from_slice(&bytes[..512]);
        patched.set_cksum();
        bytes[..512].copy_from_slice(patched.as_bytes());
        bytes
    }

    #[test]
    fn apply_unpack_debug_bundle_rejects_path_traversal() {
        use crate::compiler::platform::tests::CountingPlatform;
        let dir = tempfile::tempdir().unwrap();
        let outdir = dir.path().join("deps");
        std::fs::create_dir_all(&outdir).unwrap();
        let tar_path = outdir.join("evil.dsym.tar");
        std::fs::write(&tar_path, forged_tar_with_entry_name(b"../escaped-file")).unwrap();

        let err = PostRestoreAction::UnpackDebugBundle
            .apply(&tar_path, &CountingPlatform::new())
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("path traversal"),
            "a `..` entry must be rejected, got: {err}"
        );
        assert!(
            !dir.path().join("escaped-file").exists(),
            "nothing may be written outside the temp extraction dir"
        );
        assert!(
            !outdir.join("evil.dSYM").exists(),
            "a rejected archive must not publish a bundle"
        );
    }

    #[test]
    fn apply_unpack_debug_bundle_rejects_absolute_entry() {
        use crate::compiler::platform::tests::CountingPlatform;
        let dir = tempfile::tempdir().unwrap();
        let tar_path = dir.path().join("abs.dsym.tar");
        std::fs::write(
            &tar_path,
            forged_tar_with_entry_name(b"/tmp/kache-absolute-escape"),
        )
        .unwrap();

        let err = PostRestoreAction::UnpackDebugBundle
            .apply(&tar_path, &CountingPlatform::new())
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("absolute path"),
            "an absolute entry must be rejected, got: {err}"
        );
    }

    #[test]
    fn apply_unpack_debug_bundle_rejects_non_dsym_tar_name() {
        use crate::compiler::platform::tests::CountingPlatform;
        // Structural misuse — the action planned for a file that is not a
        // `.dsym.tar` cannot derive a bundle path, and silently unpacking
        // somewhere would be worse than a clean restore failure.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("foo.tar");
        std::fs::write(&path, synthetic_tar(&[("Contents/x", b"y")])).unwrap();
        let err = PostRestoreAction::UnpackDebugBundle
            .apply(&path, &CountingPlatform::new())
            .unwrap_err()
            .to_string();
        assert!(err.contains(".dsym.tar"), "got: {err}");
    }

    /// Symlink and hardlink entries are each rejected ON THEIR OWN — the
    /// two link kinds are independent smuggling vectors, so neither may
    /// depend on the other also being present (kunobi-ninja/kache#319).
    #[test]
    fn apply_unpack_debug_bundle_rejects_each_link_kind_alone() {
        use crate::compiler::platform::tests::CountingPlatform;
        for entry_type in [tar::EntryType::Symlink, tar::EntryType::Link] {
            let dir = tempfile::tempdir().unwrap();
            let tar_path = dir.path().join("linky.dsym.tar");
            let mut header = tar::Header::new_gnu();
            header.set_size(0);
            header.set_mode(0o644);
            header.set_entry_type(entry_type);
            let mut builder = tar::Builder::new(Vec::new());
            builder
                .append_link(&mut header, "Contents/evil", "/etc/passwd")
                .unwrap();
            std::fs::write(&tar_path, builder.into_inner().unwrap()).unwrap();

            let err = PostRestoreAction::UnpackDebugBundle
                .apply(&tar_path, &CountingPlatform::new())
                .unwrap_err()
                .to_string();
            assert!(
                err.contains("is a link"),
                "{entry_type:?} alone must be rejected, got: {err}"
            );
        }
    }

    /// The extraction cap rejects strictly past the limit and accepts a
    /// bundle landing exactly ON it — the boundary a corrupt-size header
    /// would probe (kunobi-ninja/kache#319).
    #[test]
    fn unpack_debug_bundle_cap_boundary_is_exact() {
        let payload = vec![b'x'; 100];
        let dir = tempfile::tempdir().unwrap();
        let tar_path = dir.path().join("capped.dsym.tar");
        std::fs::write(
            &tar_path,
            synthetic_tar(&[("Contents/blob", payload.as_slice())]),
        )
        .unwrap();

        let err = unpack_debug_bundle_with_cap(&tar_path, 99)
            .unwrap_err()
            .to_string();
        assert!(err.contains("extraction cap"), "got: {err}");
        assert!(!dir.path().join("capped.dSYM").exists());

        unpack_debug_bundle_with_cap(&tar_path, 100)
            .expect("a bundle exactly at the cap is within budget");
        assert!(dir.path().join("capped.dSYM/Contents/blob").exists());
    }

    /// `ArtifactSet::push` genuinely appends — the store-time debug bundle
    /// rides on it (kunobi-ninja/kache#319).
    #[test]
    fn artifact_set_push_appends_the_artifact() {
        let mut set = ArtifactSet::empty();
        set.push(Artifact {
            path: std::path::PathBuf::from("/tmp/x.dsym.tar"),
            store_name: "x.dsym.tar".to_string(),
            kind: ArtifactKind::DebugBundle,
            required: false,
        });
        assert_eq!(set.outputs().len(), 1);
        assert_eq!(set.outputs()[0].store_name, "x.dsym.tar");
        assert_eq!(set.outputs()[0].kind, ArtifactKind::DebugBundle);
    }

    // ── classify → plan integration ──────────────────────────────
    //
    // The wrapper does `compiler.classify_output(...) → plan_post_restore(...)`
    // per cached file. These tests exercise that chain end-to-end so a
    // mistake in either side (e.g. `.rcgu.o` getting classified as
    // Executable, or a kind silently picking up the wrong actions) is
    // caught here without needing wrapper-level integration plumbing.

    #[test]
    fn rustc_classify_to_plan_chain_for_typical_lib_build() {
        use crate::compiler::rustc::RustcCompiler;
        let compiler = RustcCompiler::new();
        let lib_args = compiler
            .parse(&[
                "rustc".into(),
                "src/lib.rs".into(),
                "--crate-name".into(),
                "foo".into(),
                "--crate-type".into(),
                "lib".into(),
            ])
            .unwrap();

        let cases: &[(&str, Vec<PostRestoreAction>)] = &[
            ("libfoo-abc.rlib", vec![]),
            ("libfoo-abc.rmeta", vec![]),
            ("foo-abc.d", vec![PostRestoreAction::ExpandDepInfoPaths]),
            ("foo-abc.rcgu.o", vec![]),
            ("foo-abc.dwo", vec![]),
        ];

        for (name, expected) in cases {
            let kind = compiler.classify_output(&lib_args, name);
            assert_eq!(
                &plan_post_restore(kind),
                expected,
                "for {name}: kind = {kind:?}"
            );
        }
    }

    #[test]
    fn classify_by_filename_recognizes_known_extensions() {
        // Single source of truth — every caller in the codebase that does
        // suffix matching should delegate here. Locking the mapping in.
        assert_eq!(
            classify_by_filename("libfoo-abc.rlib"),
            ArtifactKind::Library
        );
        assert_eq!(
            classify_by_filename("libfoo-abc.rmeta"),
            ArtifactKind::Metadata
        );
        assert_eq!(classify_by_filename("foo-abc.d"), ArtifactKind::DepInfo);
        assert_eq!(
            classify_by_filename("host_pathsub.o.pp"),
            ArtifactKind::DepInfo
        );
        assert_eq!(classify_by_filename("foo.o"), ArtifactKind::Object);
        assert_eq!(
            classify_by_filename("foo-abc.123.rcgu.o"),
            ArtifactKind::Object
        );
        assert_eq!(classify_by_filename("foo.obj"), ArtifactKind::Object);
        assert_eq!(
            classify_by_filename("libfoo.dylib"),
            ArtifactKind::DynamicLibrary
        );
        assert_eq!(
            classify_by_filename("libfoo.so"),
            ArtifactKind::DynamicLibrary
        );
        assert_eq!(
            classify_by_filename("rococo_runtime.wasm"),
            ArtifactKind::WasmModule
        );
        assert_eq!(
            classify_by_filename("foo.dll"),
            ArtifactKind::DynamicLibrary
        );
        assert_eq!(
            classify_by_filename("foo-abc.dwo"),
            ArtifactKind::DebugSidecar
        );
        assert_eq!(classify_by_filename("foo.pdb"), ArtifactKind::DebugSidecar);
        assert_eq!(classify_by_filename("foo.exe"), ArtifactKind::Executable);
        // kache's own store-time debug bundle tar (#319): the compound
        // `.dsym.tar` suffix must win over the bare "tar" extension, which
        // would otherwise classify Other("unknown-ext") and lose the
        // restore-side unpack dispatch.
        assert_eq!(
            classify_by_filename("foo-abc123.dsym.tar"),
            ArtifactKind::DebugBundle
        );
        assert_eq!(
            classify_by_filename("foo.tar"),
            ArtifactKind::Other("unknown-ext")
        );
        // DebugBundle restores via hardlink like every immutable kind — the
        // tar is never mutated in place (the unpack writes siblings).
        assert_eq!(
            ArtifactKind::DebugBundle.link_strategy(),
            LinkStrategy::Hardlink
        );
    }

    #[test]
    fn classify_by_filename_distinguishes_extensionless_from_unknown() {
        // Two distinct "Other" tags so callers can choose what convention
        // to apply: target/-scan callers treat extensionless as bin output;
        // others fall back to safe defaults.
        match classify_by_filename("my_bin-abc123") {
            ArtifactKind::Other("extensionless") => {}
            other => panic!("expected Other(extensionless), got {other:?}"),
        }
        match classify_by_filename("foo.lock") {
            ArtifactKind::Other("unknown-ext") => {}
            other => panic!("expected Other(unknown-ext), got {other:?}"),
        }
    }

    /// kunobi-ninja/kache#325: filename → canonical `--emit` kind, the SSOT for
    /// the emit-coverage gate. Every mapped value is in [`GATED_EMIT_KINDS`];
    /// unmapped sidecars return `None`.
    #[test]
    fn emit_kind_for_filename_maps_outputs() {
        let cases = [
            ("libfoo-abc.rlib", Some("link")),
            ("libfoo.so", Some("link")),
            ("libfoo.dylib", Some("link")),
            ("foo.dll", Some("link")),
            ("foo.exe", Some("link")),
            // A wasm32 target's link product (#431): before this, the
            // coverage gate saw a `--emit=link` wasm entry as covering
            // nothing, so every wasm module refused to store.
            ("rococo_runtime.wasm", Some("link")),
            ("my_bin-abc123", Some("link")), // extensionless bin
            ("libfoo-abc.rmeta", Some("metadata")),
            ("foo-abc.123.rcgu.o", Some("obj")),
            ("foo.obj", Some("obj")),
            ("foo-abc.d", Some("dep-info")),
            ("foo.s", Some("asm")),
            ("foo.ll", Some("llvm-ir")),
            ("foo.bc", Some("llvm-bc")),
            ("foo.mir", Some("mir")),
            ("foo.dwo", None),
            ("foo.pdb", None),
            ("foo.lock", None),
            // The store-time debug bundle (#319) satisfies no `--emit` kind —
            // it must never make the emit-coverage gate think an entry covers
            // something it doesn't.
            ("foo-abc.dsym.tar", None),
        ];
        for (name, expected) in cases {
            assert_eq!(emit_kind_for_filename(name), expected, "for {name}");
            if let Some(kind) = expected {
                assert!(
                    GATED_EMIT_KINDS.contains(&kind),
                    "{kind} (from {name}) must be in GATED_EMIT_KINDS"
                );
            }
        }
    }

    #[test]
    fn rustc_classify_to_plan_chain_for_typical_bin_build() {
        use crate::compiler::rustc::RustcCompiler;
        let compiler = RustcCompiler::new();
        let bin_args = compiler
            .parse(&[
                "rustc".into(),
                "src/main.rs".into(),
                "--crate-name".into(),
                "foo".into(),
                "--crate-type".into(),
                "bin".into(),
            ])
            .unwrap();

        let cases: &[(&str, Vec<PostRestoreAction>)] = &[
            // Extensionless binary on Unix → Executable → must sign.
            (
                "foo-abc",
                vec![PostRestoreAction::Sign(SigningPurpose::OsLoading)],
            ),
            // Dep-info still rewrites paths even in a bin build.
            ("foo-abc.d", vec![PostRestoreAction::ExpandDepInfoPaths]),
            // Per-codegen-unit object files must NEVER pick up codesign
            // (kache-fork bug 572f321). This case is the regression guard
            // for the whole bug class.
            ("foo-abc.rcgu.o", vec![]),
            // Debug sidecars are passive too.
            ("foo-abc.dwo", vec![]),
            // The store-time macOS debug bundle (#319): classified through
            // the same chain restore uses, so a cached `.dsym.tar` picks up
            // exactly the unpack — and never codesign.
            (
                "foo-abc.dsym.tar",
                vec![PostRestoreAction::UnpackDebugBundle],
            ),
        ];

        for (name, expected) in cases {
            let kind = compiler.classify_output(&bin_args, name);
            assert_eq!(
                &plan_post_restore(kind),
                expected,
                "for {name}: kind = {kind:?}"
            );
        }
    }
}

/// Compiler-name shim support (kunobi-ninja/kache#310).
///
/// A directory of symlinks named after the compilers, each pointing at the
/// `kache` binary, prepended to `PATH`, routes every build's compiler calls
/// through kache with no `CC`/`CXX` edits and no per-project build-system
/// changes. That is the lowest-friction way to put kache in front of arbitrary
/// builds, which matters most for people supporting many differently
/// structured projects where editing each build's compiler config is not
/// practical.
///
/// kache otherwise decides it is wrapping a compiler purely from `argv[1..]`,
/// so under a shim (`argv[0] = gcc`, `argv[1] = foo.c`) it would find no
/// compiler at `argv[1]`, fall through to CLI mode, and fail parsing `foo.c`
/// as a subcommand.
pub(crate) mod shim {
    use std::collections::BTreeSet;
    use std::path::{Path, PathBuf};

    /// The compiler names a generated shim directory populates. Deliberately
    /// the canonical drivers only: a shim is a `PATH` ambush, so it should
    /// cover what builds actually invoke rather than every name kache can
    /// recognize. Versioned and target-prefixed spellings are still handled
    /// when a user creates them by hand, because detection reuses
    /// `CcCompiler::recognizes`.
    // Only the generator consumes this, and generation is Unix-only (it
    // creates symlinks). Detection below stays cross-platform, so a hand-made
    // `gcc.exe` copy of kache still works on Windows.
    #[cfg_attr(not(unix), allow(dead_code))]
    pub(crate) const SHIM_NAMES: &[&str] = &["cc", "c++", "gcc", "g++", "clang", "clang++"];

    /// Whether `argv[0]` names a compiler, meaning kache is being invoked
    /// through a shim rather than as itself.
    pub(crate) fn invoked_as_compiler(arg0: &str) -> bool {
        // Reuses the full name set (exact, versioned, target-prefixed, MinGW
        // alternatives), so a hand-made `x86_64-linux-gnu-gcc` shim works
        // without a second list to keep in sync.
        super::cc::CcCompiler::recognizes(std::slice::from_ref(&arg0.to_string()))
    }

    /// The real compiler behind a shim: the first `name` on `PATH` that is not
    /// kache itself.
    ///
    /// Skipping by *resolved identity* rather than by directory is what makes
    /// this safe. It finds every shim wherever the user put them, tolerates
    /// several shim directories, and cannot be defeated by a relative or
    /// symlinked `PATH` entry — all of which would otherwise re-select the
    /// shim and recurse.
    pub(crate) fn resolve_real_compiler(
        name: &str,
        path_dirs: &[PathBuf],
        self_exe: Option<&Path>,
        is_candidate: &dyn Fn(&Path) -> bool,
        resolve: &dyn Fn(&Path) -> Option<PathBuf>,
    ) -> Option<PathBuf> {
        let self_real = self_exe.and_then(resolve);
        for dir in path_dirs {
            let candidate = dir.join(name);
            if !is_candidate(&candidate) {
                continue;
            }
            // A candidate that resolves to our own binary IS the shim.
            if let (Some(real), Some(mine)) = (resolve(&candidate), self_real.as_deref())
                && real == mine
            {
                continue;
            }
            return Some(candidate);
        }
        None
    }

    /// Live wiring for [`resolve_real_compiler`].
    pub(crate) fn resolve_real_compiler_from_env(name: &str) -> Option<PathBuf> {
        let path = std::env::var_os("PATH")?;
        let dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
        let self_exe = std::env::current_exe().ok();
        resolve_real_compiler(
            name,
            &dirs,
            self_exe.as_deref(),
            &|candidate| super::is_executable(candidate),
            &|path| std::fs::canonicalize(path).ok(),
        )
    }

    /// User-level farm created by `kache install-shims` with no directory argument.
    pub(crate) fn default_shim_dir() -> PathBuf {
        dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".local/lib/kache/shims")
    }

    /// Distro-package farm (`pacman -S kache-bin`, the kache `.deb`).
    pub(crate) fn system_shim_dir() -> PathBuf {
        PathBuf::from("/usr/lib/kache")
    }

    /// Compiler names already on PATH that are not in [`SHIM_NAMES`].
    ///
    /// `kache install-shims --from-path` uses this so versioned and
    /// target-prefixed drivers (`gcc-13`, `x86_64-pc-linux-gnu-gcc`) get a
    /// symlink without a second hardcoded list. Entries that resolve to kache
    /// itself are skipped, otherwise a re-run would treat the farm as compilers.
    pub(crate) fn extra_compiler_names(
        path_dirs: &[PathBuf],
        self_exe: Option<&Path>,
        is_candidate: &dyn Fn(&Path) -> bool,
        resolve: &dyn Fn(&Path) -> Option<PathBuf>,
    ) -> Vec<String> {
        let self_real = self_exe.and_then(resolve);
        let mut names = BTreeSet::new();
        for dir in path_dirs {
            let Ok(entries) = std::fs::read_dir(dir) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if !is_candidate(&path) {
                    continue;
                }
                if let (Some(real), Some(mine)) = (resolve(&path), self_real.as_deref())
                    && real == mine
                {
                    continue;
                }
                let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
                    continue;
                };
                if SHIM_NAMES.contains(&name) {
                    continue;
                }
                if invoked_as_compiler(name) {
                    names.insert(name.to_string());
                }
            }
        }
        names.into_iter().collect()
    }

    /// Live wiring for [`extra_compiler_names`].
    #[cfg_attr(not(unix), allow(dead_code))]
    pub(crate) fn extra_compiler_names_from_env() -> Vec<String> {
        let path = std::env::var_os("PATH").unwrap_or_default();
        let dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
        let self_exe = std::env::current_exe().ok();
        extra_compiler_names(
            &dirs,
            self_exe.as_deref(),
            &|candidate| super::is_executable(candidate),
            &|path| std::fs::canonicalize(path).ok(),
        )
    }

    /// Whether a compiler-name shim is the first `gcc`/`cc`/… on PATH.
    pub(crate) struct ShimPathStatus {
        pub on_path: bool,
        pub detail: String,
        pub fix: Option<String>,
    }

    fn dir_holds_kache_shims(
        dir: &Path,
        self_real: Option<&Path>,
        resolve: &dyn Fn(&Path) -> Option<PathBuf>,
    ) -> bool {
        let Some(mine) = self_real else {
            return false;
        };
        SHIM_NAMES
            .iter()
            .any(|name| resolve(&dir.join(name)).is_some_and(|real| real == mine))
    }

    /// `on_path` is true when the first PATH hit for any canonical compiler
    /// name resolves to this kache binary. Otherwise, report a farm that exists
    /// but is not first on PATH, or that nothing is installed.
    pub(crate) fn shim_path_status(
        path_dirs: &[PathBuf],
        self_exe: Option<&Path>,
        installed_dirs: &[PathBuf],
        is_candidate: &dyn Fn(&Path) -> bool,
        resolve: &dyn Fn(&Path) -> Option<PathBuf>,
    ) -> ShimPathStatus {
        let self_real = self_exe.and_then(resolve);
        for name in SHIM_NAMES {
            for dir in path_dirs {
                let candidate = dir.join(name);
                if !is_candidate(&candidate) {
                    continue;
                }
                if let (Some(real), Some(mine)) = (resolve(&candidate), self_real.as_deref())
                    && real == mine
                {
                    return ShimPathStatus {
                        on_path: true,
                        detail: format!("{name} on PATH is a kache shim ({})", dir.display()),
                        fix: None,
                    };
                }
                // First hit for this name is some other binary. Try the next name.
                break;
            }
        }

        let installed = installed_dirs
            .iter()
            .find(|dir| dir_holds_kache_shims(dir, self_real.as_deref(), resolve));
        if let Some(dir) = installed {
            return ShimPathStatus {
                on_path: false,
                detail: format!("installed at {}, not first on PATH", dir.display()),
                fix: Some(format!("export PATH=\"{}:$PATH\"", dir.display())),
            };
        }

        let default = default_shim_dir();
        ShimPathStatus {
            on_path: false,
            detail: "not installed".into(),
            fix: Some(format!(
                "kache install-shims && export PATH=\"{}:$PATH\"",
                default.display()
            )),
        }
    }

    /// Live wiring for [`shim_path_status`].
    pub(crate) fn live_shim_path_status() -> ShimPathStatus {
        let path = std::env::var_os("PATH").unwrap_or_default();
        let dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
        let self_exe = std::env::current_exe().ok();
        let default = default_shim_dir();
        let system = system_shim_dir();
        let installed = [default, system];
        shim_path_status(
            &dirs,
            self_exe.as_deref(),
            &installed,
            &|candidate| super::is_executable(candidate),
            &|path| std::fs::canonicalize(path).ok(),
        )
    }

    /// Rewrite a shim invocation into the wrapper-mode argv kache already
    /// understands: the resolved real compiler followed by the original
    /// arguments. `None` when this is not a shim invocation.
    pub(crate) fn wrapper_args(argv: &[String]) -> Option<Result<Vec<String>, String>> {
        let arg0 = argv.first()?;
        if !invoked_as_compiler(arg0) {
            return None;
        }
        let name = super::command_basename(arg0)?;
        let Some(real) = resolve_real_compiler_from_env(name) else {
            return Some(Err(format!(
                "kache was invoked through a compiler shim named `{name}`, but no real `{name}` \
                 was found on PATH behind it. Every `{name}` on PATH resolves to kache itself, \
                 so there is nothing to run. Check that the real toolchain is still on PATH \
                 after the shim directory."
            )));
        };
        let Some(real) = real.to_str() else {
            return Some(Err(format!(
                "the real `{name}` behind the shim has a non-UTF-8 path and cannot be wrapped \
                 safely"
            )));
        };
        let mut rewritten = Vec::with_capacity(argv.len());
        rewritten.push(real.to_string());
        rewritten.extend_from_slice(&argv[1..]);
        Some(Ok(rewritten))
    }
}

#[cfg(test)]
mod shim_tests {
    use super::shim::*;
    use std::path::{Path, PathBuf};

    #[test]
    fn compiler_shaped_argv0_is_recognized_but_kache_itself_is_not() {
        for name in ["cc", "gcc", "g++", "clang++", "/usr/local/bin/gcc"] {
            assert!(invoked_as_compiler(name), "{name} should look like a shim");
        }
        // Versioned and target-prefixed shims work without a second list.
        assert!(invoked_as_compiler("x86_64-linux-gnu-gcc"));
        assert!(invoked_as_compiler("gcc-13"));
        // kache invoked normally, and companion tools, must NOT be shims:
        // treating `kache` as a compiler would recurse, and `gcc-ar` is not a
        // compiler at all.
        assert!(!invoked_as_compiler("kache"));
        assert!(!invoked_as_compiler("/usr/local/bin/kache"));
        assert!(!invoked_as_compiler("gcc-ar"));
    }

    /// The shim must be skipped by RESOLVED IDENTITY, not by directory: that
    /// is what survives several shim dirs, relative PATH entries, and a
    /// symlinked PATH entry, each of which would otherwise re-select the shim
    /// and recurse forever.
    #[test]
    fn resolve_skips_every_path_entry_that_is_kache_itself() {
        let kache = PathBuf::from("/opt/kache/bin/kache");
        let shim_a = PathBuf::from("/shims-a");
        let shim_b = PathBuf::from("/shims-b");
        let real = PathBuf::from("/usr/bin");

        // Both shim dirs hold a `cc` that resolves to the kache binary.
        let resolve = |path: &Path| -> Option<PathBuf> {
            if path.starts_with("/shims-a") || path.starts_with("/shims-b") {
                Some(kache.clone())
            } else {
                Some(path.to_path_buf())
            }
        };
        let exists = |_: &Path| true;

        let found = resolve_real_compiler(
            "cc",
            &[shim_a, shim_b, real],
            Some(&kache),
            &exists,
            &resolve,
        );
        assert_eq!(found, Some(PathBuf::from("/usr/bin/cc")));
    }

    #[test]
    fn resolve_returns_none_when_only_shims_are_on_path() {
        let kache = PathBuf::from("/opt/kache/bin/kache");
        let found = resolve_real_compiler(
            "cc",
            &[PathBuf::from("/shims")],
            Some(&kache),
            &|_| true,
            &|_| Some(kache.clone()),
        );
        assert_eq!(found, None, "must report no real compiler, not recurse");
    }

    /// A non-executable file with the right name must not be selected as the
    /// compiler; PATH lookup semantics, and picking one would fail the build
    /// with a confusing exec error.
    #[test]
    fn resolve_skips_non_executable_candidates() {
        let kache = PathBuf::from("/opt/kache/bin/kache");
        let found = resolve_real_compiler(
            "cc",
            &[PathBuf::from("/not-exec"), PathBuf::from("/usr/bin")],
            Some(&kache),
            &|path: &Path| path.starts_with("/usr/bin"),
            &|path: &Path| Some(path.to_path_buf()),
        );
        assert_eq!(found, Some(PathBuf::from("/usr/bin/cc")));
    }

    /// Guard that restores PATH even if the test panics; process env is
    /// global and a leaked PATH would corrupt every later test.
    #[cfg(unix)]
    struct PathForTest(Option<std::ffi::OsString>);

    #[cfg(unix)]
    impl Drop for PathForTest {
        fn drop(&mut self) {
            match self.0.take() {
                Some(previous) => unsafe { std::env::set_var("PATH", previous) },
                None => unsafe { std::env::remove_var("PATH") },
            }
        }
    }

    /// Drives the LIVE wiring against a real PATH, not the injected core.
    ///
    /// The tests above inject their own PATH list and resolver, so they leave
    /// the half that reads the process's actual PATH and `current_exe`
    /// unproven: a `wrapper_args` that always returned `None` would silently
    /// stop treating anything as a shim — the whole feature off — and still
    /// pass them.
    #[cfg(unix)]
    #[test]
    fn live_resolution_finds_the_real_compiler_behind_a_real_shim() {
        use std::os::unix::fs::PermissionsExt;

        let _lock = crate::config::tests::config_path_lock();
        let dir = tempfile::tempdir().unwrap();
        let shim_dir = dir.path().join("shims");
        let real_dir = dir.path().join("real");
        std::fs::create_dir_all(&shim_dir).unwrap();
        std::fs::create_dir_all(&real_dir).unwrap();

        // A real `cc` that is a genuine executable...
        let real_cc = real_dir.join("cc");
        std::fs::write(&real_cc, "#!/bin/sh\nexit 0\n").unwrap();
        std::fs::set_permissions(&real_cc, std::fs::Permissions::from_mode(0o755)).unwrap();
        // ...shadowed on PATH by a `cc` symlink to this binary, exactly as
        // `kache install-shims` creates.
        let exe = std::env::current_exe().unwrap();
        std::os::unix::fs::symlink(&exe, shim_dir.join("cc")).unwrap();

        let _path = PathForTest(std::env::var_os("PATH"));
        unsafe {
            std::env::set_var(
                "PATH",
                format!("{}:{}", shim_dir.display(), real_dir.display()),
            )
        };

        let found = resolve_real_compiler_from_env("cc").expect("the real cc must be found");
        assert_eq!(
            std::fs::canonicalize(&found).unwrap(),
            std::fs::canonicalize(&real_cc).unwrap(),
            "must skip the shim and select the real compiler"
        );

        let rewritten = wrapper_args(&["cc".to_string(), "foo.c".to_string()])
            .expect("a compiler-shaped argv0 is a shim invocation")
            .expect("resolution succeeds");
        assert_eq!(
            std::fs::canonicalize(&rewritten[0]).unwrap(),
            std::fs::canonicalize(&real_cc).unwrap(),
            "the rewritten argv must run the real compiler"
        );
        assert_eq!(
            &rewritten[1..],
            &["foo.c".to_string()],
            "the original arguments must be preserved verbatim"
        );
    }

    /// With only the shim on PATH there is nothing to run, so this must report
    /// the condition rather than resolve back to itself and recurse.
    #[cfg(unix)]
    #[test]
    fn live_resolution_reports_when_only_the_shim_is_on_path() {
        let _lock = crate::config::tests::config_path_lock();
        let dir = tempfile::tempdir().unwrap();
        let shim_dir = dir.path().join("shims");
        std::fs::create_dir_all(&shim_dir).unwrap();
        let exe = std::env::current_exe().unwrap();
        std::os::unix::fs::symlink(&exe, shim_dir.join("cc")).unwrap();

        let _path = PathForTest(std::env::var_os("PATH"));
        unsafe { std::env::set_var("PATH", format!("{}", shim_dir.display())) };

        assert_eq!(resolve_real_compiler_from_env("cc"), None);
        let err = wrapper_args(&["cc".to_string(), "foo.c".to_string()])
            .expect("still a shim invocation")
            .expect_err("but with no compiler to run");
        assert!(err.contains("no real `cc`"), "unexpected message: {err}");
    }

    #[test]
    fn non_shim_argv_is_left_alone() {
        // Normal `kache <compiler> …` and plain CLI use must not be rewritten.
        assert!(wrapper_args(&["kache".into(), "gcc".into(), "a.c".into()]).is_none());
        assert!(wrapper_args(&["kache".into(), "stats".into()]).is_none());
        assert!(wrapper_args(&[]).is_none());
    }

    #[test]
    fn shim_path_status_passes_when_the_first_gcc_is_kache() {
        let kache = PathBuf::from("/opt/kache/bin/kache");
        let shims = PathBuf::from("/shims");
        let real = PathBuf::from("/usr/bin");
        let resolve = |path: &Path| -> Option<PathBuf> {
            if path.starts_with("/shims") {
                Some(kache.clone())
            } else {
                Some(path.to_path_buf())
            }
        };
        let status = shim_path_status(&[shims, real], Some(&kache), &[], &|_| true, &resolve);
        assert!(status.on_path, "{}", status.detail);
        assert!(status.detail.contains("/shims"), "{}", status.detail);
        assert!(status.fix.is_none());
    }

    #[test]
    fn shim_path_status_reports_installed_farm_that_is_not_on_path() {
        let kache = PathBuf::from("/opt/kache/bin/kache");
        let farm = PathBuf::from("/home/user/.local/lib/kache/shims");
        let real = PathBuf::from("/usr/bin");
        let resolve = |path: &Path| -> Option<PathBuf> {
            if path.starts_with(&farm) {
                Some(kache.clone())
            } else {
                Some(path.to_path_buf())
            }
        };
        let status = shim_path_status(
            &[real],
            Some(&kache),
            std::slice::from_ref(&farm),
            &|_| true,
            &resolve,
        );
        assert!(!status.on_path);
        assert!(
            status.detail.contains("not first on PATH"),
            "{}",
            status.detail
        );
        assert_eq!(
            status.fix.as_deref(),
            Some("export PATH=\"/home/user/.local/lib/kache/shims:$PATH\"")
        );
    }

    #[test]
    fn shim_path_status_reports_missing_farm() {
        let kache = PathBuf::from("/opt/kache/bin/kache");
        let status = shim_path_status(
            &[PathBuf::from("/usr/bin")],
            Some(&kache),
            &[],
            &|_| true,
            &|path| Some(path.to_path_buf()),
        );
        assert!(!status.on_path);
        assert_eq!(status.detail, "not installed");
        let fix = status.fix.expect("missing farm must say how to install");
        assert!(fix.contains("kache install-shims"), "{fix}");
        assert!(fix.contains("export PATH="), "{fix}");
    }

    #[test]
    fn default_and_system_shim_dirs_are_the_documented_locations() {
        let home = default_shim_dir();
        assert!(
            home.ends_with(".local/lib/kache/shims"),
            "user farm must be ~/.local/lib/kache/shims, got {}",
            home.display()
        );
        assert_eq!(system_shim_dir(), PathBuf::from("/usr/lib/kache"));
    }

    #[test]
    fn a_path_that_does_not_hold_kache_is_not_an_installed_farm() {
        let kache = PathBuf::from("/opt/kache/bin/kache");
        let decoy = PathBuf::from("/opt/other/shims");
        let status = shim_path_status(
            &[PathBuf::from("/usr/bin")],
            Some(&kache),
            std::slice::from_ref(&decoy),
            &|_| true,
            &|path| Some(path.to_path_buf()),
        );
        assert!(!status.on_path);
        assert_eq!(
            status.detail, "not installed",
            "a decoy directory must not count as the kache farm: {}",
            status.detail
        );
    }

    #[cfg(unix)]
    #[test]
    fn extra_names_on_path_include_versioned_compilers_not_the_farm() {
        use std::os::unix::fs::PermissionsExt;

        let _lock = crate::config::tests::config_path_lock();
        let dir = tempfile::tempdir().unwrap();
        let shim_dir = dir.path().join("shims");
        let real_dir = dir.path().join("real");
        std::fs::create_dir_all(&shim_dir).unwrap();
        std::fs::create_dir_all(&real_dir).unwrap();

        let exe = std::env::current_exe().unwrap();
        std::os::unix::fs::symlink(&exe, shim_dir.join("gcc")).unwrap();

        let gcc13 = real_dir.join("gcc-13");
        std::fs::write(&gcc13, "#!/bin/sh\nexit 0\n").unwrap();
        std::fs::set_permissions(&gcc13, std::fs::Permissions::from_mode(0o755)).unwrap();
        // Canonical names are already in SHIM_NAMES; --from-path must not
        // re-list them just because a real gcc sits later on PATH.
        let gcc = real_dir.join("gcc");
        std::fs::write(&gcc, "#!/bin/sh\nexit 0\n").unwrap();
        std::fs::set_permissions(&gcc, std::fs::Permissions::from_mode(0o755)).unwrap();

        let _path = PathForTest(std::env::var_os("PATH"));
        unsafe {
            std::env::set_var(
                "PATH",
                format!("{}:{}", shim_dir.display(), real_dir.display()),
            )
        };

        let extra = extra_compiler_names_from_env();
        assert!(
            extra.iter().any(|n| n == "gcc-13"),
            "versioned compiler must be wrapped, got {extra:?}"
        );
        assert!(
            !extra.iter().any(|n| n == "gcc"),
            "canonical names belong to SHIM_NAMES, got {extra:?}"
        );
    }
}